<?php $__env->startSection('title', 'Edit Invoice'); ?>

<?php $__env->startSection('content'); ?>
<div class="card">
    <div class="card-header bg-white fw-bold">
        Edit Invoice
    </div>
    <div class="card-body">
        <form action="<?php echo e(route('invoices.update', $invoice->id)); ?>" method="POST" id="invoiceForm">
            <?php echo csrf_field(); ?>
            <?php echo method_field('PUT'); ?>
            
            <!-- Invoice Meta Info -->
            <div class="row g-3 mb-4">
                <div class="col-md-6">
                    <div class="form-floating">
                        <input type="text" id="invoice_no" name="invoice_no" class="form-control" value="<?php echo e($invoice->invoice_no); ?>" readonly placeholder="Invoice Number">
                        <label for="invoice_no">Invoice Number</label>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-floating">
                        <input type="date" id="invoice_date" name="invoice_date" class="form-control" value="<?php echo e($invoice->invoice_date->format('Y-m-d')); ?>" required>
                        <label for="invoice_date">Invoice Date</label>
                    </div>
                </div>
            </div>

            <hr class="mb-4">

            <!-- Customer Selection -->
            <h5 class="mb-3 fw-bold text-primary">Customer Details</h5>
            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <div class="form-floating">
                        <select name="customer_id" id="customer_id" class="form-select" required>
                            <option value="">-- Select Customer --</option>
                            <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($customer->id); ?>" <?php echo e($invoice->customer_id == $customer->id ? 'selected' : ''); ?>>
                                    <?php echo e($customer->customer_name); ?> (<?php echo e($customer->mobile); ?>)
                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <label for="customer_id">Select Customer <span class="text-danger">*</span></label>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-floating">
                        <input type="text" id="cust_mobile" class="form-control" readonly value="<?php echo e($invoice->customer->mobile ?? ''); ?>" placeholder="Mobile Number">
                        <label for="cust_mobile">Mobile Number</label>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-floating">
                        <input type="text" id="cust_gst" class="form-control" readonly value="<?php echo e($invoice->customer->gst_number ?? ''); ?>" placeholder="GST Number">
                        <label for="cust_gst">GST Number</label>
                    </div>
                </div>
                <div class="col-md-12">
                    <div class="form-floating">
                        <textarea id="cust_address" class="form-control" style="height: 80px" readonly placeholder="Address"><?php echo e($invoice->customer->address1 ?? ''); ?></textarea>
                        <label for="cust_address">Address</label>
                    </div>
                </div>
            </div>

            <hr>

            <!-- Products Table -->
            <h5 class="mb-3">Product Entry</h5>
            <div class="table-responsive mb-4">
                <table class="table table-bordered" id="productTable">
                    <thead class="table-light">
                        <tr>
                            <th width="40%">Product Name</th>
                            <th width="15%">Qty</th>
                            <th width="20%">Rate (₹)</th>
                            <th width="20%">Amount (₹)</th>
                            <th width="5%">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $__currentLoopData = $invoice->items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <tr>
                            <td>
                                <input type="text" name="products[<?php echo e($index); ?>][product_name]" class="form-control" value="<?php echo e($item->product_name); ?>" required>
                            </td>
                            <td>
                                <input type="number" name="products[<?php echo e($index); ?>][qty]" class="form-control qty" value="<?php echo e($item->qty); ?>" min="1" step="0.01" required>
                            </td>
                            <td>
                                <input type="number" name="products[<?php echo e($index); ?>][rate]" class="form-control rate" value="<?php echo e($item->rate); ?>" min="0" step="0.01" required>
                            </td>
                            <td>
                                <input type="number" name="products[<?php echo e($index); ?>][amount]" class="form-control amount" value="<?php echo e($item->amount); ?>" readonly>
                            </td>
                            <td>
                                <button type="button" class="btn btn-danger btn-sm remove-row"><i class="fas fa-times"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="5">
                                <button type="button" class="btn btn-sm btn-primary" id="addRow"><i class="fas fa-plus"></i> Add Product</button>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <!-- Totals Section -->
            <div class="row">
                <div class="col-md-6 offset-md-6">
                    <table class="table table-bordered">
                        <tr>
                            <th>Sub Total (₹)</th>
                            <td>
                                <input type="number" name="subtotal" id="subtotal" class="form-control text-end" value="<?php echo e($invoice->subtotal); ?>" readonly>
                            </td>
                        </tr>
                        <tr>
                            <th>Discount (₹)</th>
                            <td>
                                <input type="number" name="discount" id="discount" class="form-control text-end" value="<?php echo e($invoice->discount); ?>" min="0" step="0.01">
                            </td>
                        </tr>
                        <tr>
                            <th>Grand Total (₹)</th>
                            <td>
                                <input type="number" name="grand_total" id="grand_total" class="form-control text-end fw-bold" value="<?php echo e($invoice->grand_total); ?>" readonly>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>

            <div class="text-end">
                <button type="submit" class="btn btn-primary btn-lg"><i class="fas fa-save"></i> Update Invoice</button>
                <a href="<?php echo e(route('invoices.index')); ?>" class="btn btn-secondary btn-lg">Cancel</a>
            </div>
        </form>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script>
$(document).ready(function() {
    // Fetch Customer Details via AJAX
    $('#customer_id').change(function() {
        let customerId = $(this).val();
        if(customerId) {
            $.get(`<?php echo e(url('api/customers')); ?>/${customerId}`, function(data) {
                $('#cust_mobile').val(data.mobile);
                $('#cust_gst').val(data.gst_number);
                
                let address = data.address1;
                if(data.address2) address += ', ' + data.address2;
                if(data.city) address += ', ' + data.city;
                if(data.state) address += ', ' + data.state;
                if(data.pincode) address += ' - ' + data.pincode;
                $('#cust_address').val(address);
            });
        } else {
            $('#cust_mobile, #cust_gst, #cust_address').val('');
        }
    });

    // Dynamic Rows
    let rowIdx = <?php echo e(count($invoice->items)); ?>;
    $('#addRow').click(function() {
        let tr = `
        <tr>
            <td>
                <input type="text" name="products[${rowIdx}][product_name]" class="form-control" required>
            </td>
            <td>
                <input type="number" name="products[${rowIdx}][qty]" class="form-control qty" value="1" min="1" step="0.01" required>
            </td>
            <td>
                <input type="number" name="products[${rowIdx}][rate]" class="form-control rate" value="0" min="0" step="0.01" required>
            </td>
            <td>
                <input type="number" name="products[${rowIdx}][amount]" class="form-control amount" value="0" readonly>
            </td>
            <td>
                <button type="button" class="btn btn-danger btn-sm remove-row"><i class="fas fa-times"></i></button>
            </td>
        </tr>`;
        $('#productTable tbody').append(tr);
        rowIdx++;
    });

    $(document).on('click', '.remove-row', function() {
        $(this).closest('tr').remove();
        calculateTotals();
    });

    // Calculations
    $(document).on('input', '.qty, .rate', function() {
        let tr = $(this).closest('tr');
        let qty = parseFloat(tr.find('.qty').val()) || 0;
        let rate = parseFloat(tr.find('.rate').val()) || 0;
        tr.find('.amount').val((qty * rate).toFixed(2));
        calculateTotals();
    });

    $('#discount').on('input', function() {
        calculateTotals();
    });

    function calculateTotals() {
        let subtotal = 0;
        $('.amount').each(function() {
            subtotal += parseFloat($(this).val()) || 0;
        });
        $('#subtotal').val(subtotal.toFixed(2));

        let discount = parseFloat($('#discount').val()) || 0;
        let grandTotal = subtotal - discount;
        $('#grand_total').val(grandTotal.toFixed(2));
    }
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH E:\xampp\htdocs\riya\billing\resources\views/invoices/edit.blade.php ENDPATH**/ ?>