<?php $__env->startSection('title', 'নতুন জার্নাল এন্ট্রি'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <div class="row mb-3">
        <div class="col-md-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0">
                    <li class="breadcrumb-item"><a href="<?php echo e(route('dashboard')); ?>">ড্যাশবোর্ড</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo e(route('accounting.journal.index')); ?>">জার্নাল এন্ট্রি</a></li>
                    <li class="breadcrumb-item active" aria-current="page">নতুন এন্ট্রি</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="card-title mb-0">
                        <i class="fas fa-plus-circle"></i> নতুন জার্নাল এন্ট্রি তৈরি
                    </h5>
                </div>
                <div class="card-body">
                    <form action="<?php echo e(route('accounting.journal.store')); ?>" method="POST" id="journalForm">
                        <?php echo csrf_field(); ?>

                        <div class="row mb-4">
                            <div class="col-md-3">
                                <label for="entry_date" class="form-label">তারিখ <span class="text-danger">*</span></label>
                                <input type="date" class="form-control <?php $__errorArgs = ['entry_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                       id="entry_date" name="entry_date" 
                                       value="<?php echo e(old('entry_date', date('Y-m-d'))); ?>" required>
                                <?php $__errorArgs = ['entry_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <div class="col-md-3">
                                <label for="voucher_no" class="form-label">ভাউচার নং <span class="text-danger">*</span></label>
                                <input type="text" class="form-control <?php $__errorArgs = ['voucher_no'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                       id="voucher_no" name="voucher_no" 
                                       value="<?php echo e(old('voucher_no', $voucherNo)); ?>" required readonly>
                                <?php $__errorArgs = ['voucher_no'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <div class="col-md-3">
                                <label for="reference_no" class="form-label">রেফারেন্স নং</label>
                                <input type="text" class="form-control <?php $__errorArgs = ['reference_no'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                       id="reference_no" name="reference_no" 
                                       value="<?php echo e(old('reference_no')); ?>">
                                <?php $__errorArgs = ['reference_no'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <div class="col-md-3">
                                <label class="form-label d-block">&nbsp;</label>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" 
                                           id="post_now" name="post_now" value="1">
                                    <label class="form-check-label" for="post_now">
                                        সরাসরি পোস্ট করুন
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="narration" class="form-label">বিবরণ</label>
                            <textarea class="form-control <?php $__errorArgs = ['narration'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                      id="narration" name="narration" rows="2"><?php echo e(old('narration')); ?></textarea>
                            <?php $__errorArgs = ['narration'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="card mb-4">
                            <div class="card-header bg-light">
                                <h6 class="mb-0">জার্নাল এন্ট্রি আইটেমস <span class="text-danger">*</span></h6>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="itemsTable">
                                        <thead class="table-light">
                                            <tr>
                                                <th width="40">#</th>
                                                <th>অ্যাকাউন্ট</th>
                                                <th width="200">বিবরণ</th>
                                                <th width="150" class="text-end">ডেবিট (৳)</th>
                                                <th width="150" class="text-end">ক্রেডিট (৳)</th>
                                                <th width="50"><button type="button" class="btn btn-sm btn-success" id="addRow"><i class="fas fa-plus"></i></button></th>
                                            </tr>
                                        </thead>
                                        <tbody id="itemsBody">
                                            <tr class="item-row">
                                                <td>1</td>
                                                <td>
                                                    <select class="form-select account-select" name="items[0][chart_of_account_id]" required>
                                                        <option value="">-- অ্যাকাউন্ট নির্বাচন করুন --</option>
                                                        <?php $__currentLoopData = $accounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $type => $typeAccounts): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <optgroup label="<?php echo e($type); ?>">
                                                            <?php $__currentLoopData = $typeAccounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $account): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                            <option value="<?php echo e($account->id); ?>">
                                                                <?php echo e($account->code); ?> - <?php echo e($account->name); ?>

                                                            </option>
                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                        </optgroup>
                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control" name="items[0][description]">
                                                </td>
                                                <td>
                                                    <input type="number" class="form-control debit-input text-end" 
                                                           name="items[0][debit]" step="0.01" min="0" 
                                                           oninput="calculateTotals()">
                                                </td>
                                                <td>
                                                    <input type="number" class="form-control credit-input text-end" 
                                                           name="items[0][credit]" step="0.01" min="0" 
                                                           oninput="calculateTotals()">
                                                </td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-sm btn-danger remove-row" disabled>
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                            <tr class="item-row">
                                                <td>2</td>
                                                <td>
                                                    <select class="form-select account-select" name="items[1][chart_of_account_id]" required>
                                                        <option value="">-- অ্যাকাউন্ট নির্বাচন করুন --</option>
                                                        <?php $__currentLoopData = $accounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $type => $typeAccounts): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                        <optgroup label="<?php echo e($type); ?>">
                                                            <?php $__currentLoopData = $typeAccounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $account): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                            <option value="<?php echo e($account->id); ?>">
                                                                <?php echo e($account->code); ?> - <?php echo e($account->name); ?>

                                                            </option>
                                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                        </optgroup>
                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                    </select>
                                                </td>
                                                <td>
                                                    <input type="text" class="form-control" name="items[1][description]">
                                                </td>
                                                <td>
                                                    <input type="number" class="form-control debit-input text-end" 
                                                           name="items[1][debit]" step="0.01" min="0" 
                                                           oninput="calculateTotals()">
                                                </td>
                                                <td>
                                                    <input type="number" class="form-control credit-input text-end" 
                                                           name="items[1][credit]" step="0.01" min="0" 
                                                           oninput="calculateTotals()">
                                                </td>
                                                <td class="text-center">
                                                    <button type="button" class="btn btn-sm btn-danger remove-row">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="3" class="text-end"><strong>মোট:</strong></td>
                                                <td class="text-end">
                                                    <strong id="totalDebit">৳ 0.00</strong>
                                                    <input type="hidden" id="total_debit" name="total_debit" value="0">
                                                </td>
                                                <td class="text-end">
                                                    <strong id="totalCredit">৳ 0.00</strong>
                                                    <input type="hidden" id="total_credit" name="total_credit" value="0">
                                                </td>
                                                <td></td>
                                            </tr>
                                            <tr>
                                                <td colspan="3" class="text-end"><strong>ভারসাম্য:</strong></td>
                                                <td colspan="2" class="text-center">
                                                    <span id="balanceStatus" class="badge bg-danger">ডেবিট এবং ক্রেডিট সমান নয়</span>
                                                </td>
                                                <td></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                                <div class="alert alert-info mt-3">
                                    <i class="fas fa-info-circle"></i> 
                                    নিয়ম: মোট ডেবিট এবং মোট ক্রেডিট সমান হতে হবে। প্রতিটি সারিতে শুধুমাত্র একটি (ডেবিট বা ক্রেডিট) ফিল্ড পূরণ করুন।
                                </div>
                            </div>
                        </div>

                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <a href="<?php echo e(route('accounting.journal.index')); ?>" class="btn btn-secondary me-md-2">
                                <i class="fas fa-times"></i> বাতিল করুন
                            </a>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> সংরক্ষণ করুন
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('styles'); ?>
<style>
    .table td, .table th {
        vertical-align: middle;
    }
    .debit-input:focus, .credit-input:focus {
        border-color: #86b7fe;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }
    .is-balanced .badge {
        background-color: #198754 !important;
    }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
    let rowCount = 2;

    $(document).ready(function() {
        // Add new row
        $('#addRow').click(function() {
            const newRow = `
                <tr class="item-row">
                    <td>${rowCount + 1}</td>
                    <td>
                        <select class="form-select account-select" name="items[${rowCount}][chart_of_account_id]" required>
                            <option value="">-- অ্যাকাউন্ট নির্বাচন করুন --</option>
                            <?php $__currentLoopData = $accounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $type => $typeAccounts): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <optgroup label="<?php echo e($type); ?>">
                                <?php $__currentLoopData = $typeAccounts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $account): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($account->id); ?>">
                                    <?php echo e($account->code); ?> - <?php echo e($account->name); ?>

                                </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </optgroup>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </td>
                    <td>
                        <input type="text" class="form-control" name="items[${rowCount}][description]">
                    </td>
                    <td>
                        <input type="number" class="form-control debit-input text-end" 
                               name="items[${rowCount}][debit]" step="0.01" min="0" 
                               oninput="calculateTotals()">
                    </td>
                    <td>
                        <input type="number" class="form-control credit-input text-end" 
                               name="items[${rowCount}][credit]" step="0.01" min="0" 
                               oninput="calculateTotals()">
                    </td>
                    <td class="text-center">
                        <button type="button" class="btn btn-sm btn-danger remove-row">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                </tr>
            `;
            $('#itemsBody').append(newRow);
            rowCount++;
            updateRowNumbers();
            enableRemoveButtons();
        });

        // Remove row
        $(document).on('click', '.remove-row', function() {
            if ($('.item-row').length > 2) {
                $(this).closest('.item-row').remove();
                updateRowNumbers();
                calculateTotals();
                enableRemoveButtons();
            }
        });

        // Enable/disable remove buttons
        function enableRemoveButtons() {
            $('.remove-row').prop('disabled', $('.item-row').length <= 2);
        }

        // Update row numbers
        function updateRowNumbers() {
            $('.item-row').each(function(index) {
                $(this).find('td:first').text(index + 1);
                // Update input names
                $(this).find('select, input').each(function() {
                    const name = $(this).attr('name');
                    if (name) {
                        const newName = name.replace(/\[\d+\]/, `[${index}]`);
                        $(this).attr('name', newName);
                    }
                });
            });
        }

        // Auto-fill description from account name
        $(document).on('change', '.account-select', function() {
            const selectedText = $(this).find('option:selected').text();
            const accountName = selectedText.split(' - ')[1];
            if (accountName) {
                $(this).closest('tr').find('input[name*="description"]').val(accountName);
            }
        });

        // Only allow debit OR credit per row
        $(document).on('input', '.debit-input', function() {
            if ($(this).val() > 0) {
                $(this).closest('tr').find('.credit-input').val('');
            }
        });

        $(document).on('input', '.credit-input', function() {
            if ($(this).val() > 0) {
                $(this).closest('tr').find('.debit-input').val('');
            }
        });

        calculateTotals();
        enableRemoveButtons();
    });

    function calculateTotals() {
        let totalDebit = 0;
        let totalCredit = 0;

        $('.debit-input').each(function() {
            totalDebit += parseFloat($(this).val()) || 0;
        });

        $('.credit-input').each(function() {
            totalCredit += parseFloat($(this).val()) || 0;
        });

        $('#totalDebit').text('৳ ' + totalDebit.toFixed(2));
        $('#totalCredit').text('৳ ' + totalCredit.toFixed(2));
        $('#total_debit').val(totalDebit);
        $('#total_credit').val(totalCredit);

        const balanceStatus = $('#balanceStatus');
        const balanceDifference = Math.abs(totalDebit - totalCredit);

        if (totalDebit === totalCredit && totalDebit > 0) {
            balanceStatus.removeClass('bg-danger').addClass('bg-success').text('ভারসাম্যপূর্ণ ✓');
            $('tfoot').addClass('is-balanced');
        } else if (totalDebit === 0 && totalCredit === 0) {
            balanceStatus.removeClass('bg-success').addClass('bg-warning').text('ডেটা প্রবেশ করুন');
            $('tfoot').removeClass('is-balanced');
        } else {
            balanceStatus.removeClass('bg-success bg-warning').addClass('bg-danger')
                .text('অসমান: ' + balanceDifference.toFixed(2) + ' এর পার্থক্য');
            $('tfoot').removeClass('is-balanced');
        }
    }

    // Form validation
    $('#journalForm').submit(function(e) {
        const totalDebit = parseFloat($('#total_debit').val()) || 0;
        const totalCredit = parseFloat($('#total_credit').val()) || 0;
        
        if (totalDebit !== totalCredit) {
            e.preventDefault();
            alert('দুঃখিত! ডেবিট এবং ক্রেডিট সমান হতে হবে।\nমোট ডেবিট: ৳' + totalDebit.toFixed(2) + '\nমোট ক্রেডিট: ৳' + totalCredit.toFixed(2));
            return false;
        }

        if (totalDebit === 0) {
            e.preventDefault();
            alert('দুঃখিত! কমপক্ষে একটি লেনদেন যোগ করুন।');
            return false;
        }

        // Check for duplicate accounts
        const accounts = [];
        let hasDuplicate = false;
        
        $('.account-select').each(function() {
            const accountId = $(this).val();
            if (accountId && accounts.includes(accountId)) {
                hasDuplicate = true;
                return false;
            }
            accounts.push(accountId);
        });

        if (hasDuplicate) {
            e.preventDefault();
            alert('দুঃখিত! একই অ্যাকাউন্ট একাধিক বার ব্যবহার করা যাবে না।');
            return false;
        }

        return true;
    });
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/naowarin/somoti.naowarinternational.my.id/resources/views/accounting/journal-entries/create.blade.php ENDPATH**/ ?>