<!-- Add Purchase Modal -->
<div class="modal fade" id="purchaseModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <span id="modalTitle">Add New Purchase</span>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="purchaseForm" enctype="multipart/form-data" method="POST">
                    @csrf
                    @method('POST')
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label" for="grn_no">Link GRN (Optional)</label>
                            <select class="form-select" name="grn_no" id="grn_no"
                                onchange="getGRNDetails(this.value)">
                                <option value="">Select GRN</option>
                                <!-- Populated via AJAX -->
                            </select>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label" for="purchase_order_id">Purchase Order No</label>
                            <select class="form-select" name="purchase_order_id" id="purchase_order_id"
                                onchange="getPurchaseOrderDetails(this.value)">
                                <option value="">Select Purchase Order No</option>
                                @foreach ($purchaseOrders as $purchaseOrder)
                                    <option value="{{ $purchaseOrder->id }}"
                                        data-purchase-order="{{ json_encode($purchaseOrder) }}">
                                        {{ $purchaseOrder->purchase_order_no }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="purchase_order_date">Vendor Order Date</label>
                            <input type="date" class="form-control" name="purchase_order_date"
                                id="purchase_order_date" value="">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label" for="purchase_no">Vendor Invoice No <span
                                    class="required">*</span></label>
                            <input type="text" class="form-control" name="purchase_no" id="purchase_no"
                                value="">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="vendor_email">Vendor Email</label>
                            <input type="email" class="form-control" name="vendor_email" id="vendor_email"
                                value="">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label" for="invoice_no">Purchase ID</label>
                            <input type="text" class="form-control" name="invoice_no" id="invoiceNo"
                                value="{{ $nextInvoiceNo }}" readonly>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="invoice_date">Invoice Date</label>
                            <input type="date" class="form-control" name="invoice_date" id="invoice_date"
                                value="{{ $currentDate }}" required>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label" for="purchase_id">Party</label>
                            <select class="form-select" name="purchase_id" id="purchase_id" required>
                                <option value="">Select Party</option>
                                @foreach ($parties as $party)
                                    <option value="{{ $party->id }}">{{ $party->company }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="vendor_reference_no">Vendor Reference No</label>
                            <input type="text" class="form-control" name="vendor_reference_no"
                                id="vendor_reference_no" value="">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label" for="payment_terms">Payment Terms</label>
                            <select class="form-select" name="payment_terms" id="payment_terms">
                                <option value="0">Due on Receipt</option>
                                <option value="7">Net 7 Days</option>
                                <option value="15">Net 15 Days</option>
                                <option value="30">Net 30 Days</option>
                                <option value="45">Net 45 Days</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="company_gstn">GSTN</label>
                            <input type="text" class="form-control" name="company_gstn" id="company_gstn"
                                value="">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label" for="company_address">Address</label>
                            <input type="text" class="form-control" name="company_address" id="company_address"
                                value="">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="company_phone">Phone</label>
                            <input type="text" class="form-control" name="company_phone" id="company_phone"
                                value="">
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label" for="description">Description</label>
                            <input type="text" class="form-control" name="description" id="description"
                                value="">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="delivery_terms">Delivery Terms</label>
                            <input type="text" class="form-control" name="delivery_terms" id="delivery_terms"
                                value="">
                        </div>
                    </div>

                    @include('superadmin.purchasemanagement.purchaseitems')

                    <div class="card mb-3">
                        <div class="card-header">Payment Details</div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label" for="payment_mode">Payment Mode</label>
                                    <select class="form-select" name="payment_mode" id="payment_mode">
                                        <option value="">Select Payment Mode</option>
                                        <option value="Cash">Cash</option>
                                        <option value="Bank Transfer">Bank Transfer</option>
                                        <option value="Cheque">Cheque</option>
                                        <option value="Credit Card">Credit Card</option>
                                        <option value="Credit">Credit</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label" for="payment_reference">Reference</label>
                                    <input type="text" class="form-control" name="payment_reference"
                                        id="payment_reference" placeholder="Payment reference">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label" for="payment_reason">Reason (if any)</label>
                                    <input type="text" class="form-control" name="payment_reason"
                                        id="payment_reason" placeholder="Reason for payment">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label" for="notes">Notes</label>
                        <textarea class="form-control" name="note" id="notes" rows="2"></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label" for="purchase_files">Upload Files</label>
                        <input type="file" class="form-control" name="purchase_files[]" id="purchaseFiles"
                            multiple>
                        <div id="filePreview" class="mt-3 row g-2"></div>
                    </div>

                    <div class="mb-3">
                        <div id="existingFile" class="mt-2"></div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="savePurchase">Save Purchase</button>
            </div>
        </div>
    </div>
</div>

<script>
    // Fetch and populate GRN Dropdown
    function populateGRNDropdown() {
        $.ajax({
            url: '{{ route("superadmin.purchase.pendingGRNs") }}',
            type: 'GET',
            success: function(grns) {
                let $select = $('#grn_no');
                $select.empty().append('<option value="">Select GRN</option>');
                grns.forEach(grn => {
                    $select.append(`<option value="${grn.id}">${grn.grn_no} - ${grn.company_name} (${grn.grn_date})</option>`);
                });
            }
        });
    }

    // Get GRN Details and populate form
    function getGRNDetails(grnId) {
        if (!grnId) return;

        $.ajax({
            url: '{{ route("superadmin.purchase.grnDetails", ":id") }}'.replace(':id', grnId),
            type: 'GET',
            success: function(response) {
                if(response.success) {
                   const grn = response.grn;
                   const items = response.items;
                   const partyId = response.party_id;

                   // Populate fields from GRN
                   if(partyId) $('#purchase_id').val(partyId);
                   $('#vendor_reference_no').val(grn.order_ref_no);
                   $('#description').val('Invoice for GRN ' + grn.grn_no);
                   
                   // Populate items
                   // Note: rates are 0 from GRN, user must fill them.
                   populateItems(items.map(item => ({
                       item_id: item.item_id, // ensure stock item id is mapped
                       description: item.description,
                       uom: item.uom,
                       quantity: item.quantity,
                       rate: 0,
                       amount: 0,
                       // Map backend keys to frontend expectations if divergent
                       stock_item: item.item_id,
                       unit_rate: 0
                   })));
                } else {
                    alert(response.message);
                }
            }
        });
    }

    function getPurchaseOrderDetails(purchaseOrderId) {
        const $option = $('#purchase_order_id').find('option[value="' + purchaseOrderId + '"]');
        if (!$option.length) return;

        const purchaseOrder = $option.data('purchase-order');
        if (!purchaseOrder) return;
        console.log(purchaseOrder);
        $('#purchase_order_date').val(purchaseOrder.purchase_order_date || '');
        // $('#purchase_no').val(purchaseOrder.purchase_order_no || '');
        $('#vendor_email').val(purchaseOrder.company_email || '');
        $('#purchase_id').val(purchaseOrder?.quotation?.vendor_id || '');
        $('#vendor_reference_no').val(purchaseOrder?.quotation?.vendor_reference_no || '');
        $('#notes').val(purchaseOrder.note || '');
        $("#description").val(purchaseOrder.description || '');

        // Optionally fill more fields if present in your form
        $('#company_address').val(purchaseOrder.company_address || '');
        $('#company_gstn').val(purchaseOrder.company_gstn || '');
        $('#company_phone').val(purchaseOrder.company_phone || '');
        $('#bill_address').val(purchaseOrder.bill_address || '');
        $('#ship_address').val(purchaseOrder.ship_address || '');
        $('#rfq_no').val(purchaseOrder.rfq_no || '');
        $('#rfq_date').val(purchaseOrder.rfq_date || '');
        $('#delivery_terms').val(purchaseOrder.delivery_terms || '');
        $('#additional_charges').val(purchaseOrder.additional_charges || '');
        $('#subtotal').val(purchaseOrder.subtotal || '');
        $('#sgst_amount').val(purchaseOrder.sgst_amount || '');
        $('#cgst_amount').val(purchaseOrder.cgst_amount || '');
        $('#igst_amount').val(purchaseOrder.igst_amount || '');
        $('#round_up').val(purchaseOrder.round_up || '');
        $('#grand_total').val(purchaseOrder.grand_total || '');



        console.log(purchaseOrder?.quotation?.items);
        populateItems(purchaseOrder?.quotation?.items || []);

        // If you want to clear or set other fields, do so here
        // $('#invoice_no').val('');

        // If you want to handle items, you may need AJAX to fetch them

        console.log('Loaded PurchaseOrder:', purchaseOrder);
    }

    function populateItems(items) {
        let newRow = $('.item-row:first').clone();
        $('#itemsContainer').empty();
        items.forEach((item, index) => {
            console.log({
                item,
                newRow: newRow.find('select, input').map(v => $(v).attr('name'))
            });
            newRow.find('select, input').each(function() {
                let name = $(this).attr('name');
                let mappedName = $(this).attr('data-name');
                if (name) {
                    let value = mappedName == "index" ? (index + 1) : item[mappedName];
                    let updated = name.replace(/\[\d+\]/, `[${index}]`);
                    $(this).attr('name', updated);
                    $(this).val(value);
                }
            });
            $('#itemsContainer').append(newRow);
            newRow = $('.item-row:last').clone();
        });
        recalculateAll();
        updateRemoveButtons();
    }

    //listen for modal
    document.addEventListener('DOMContentLoaded', function() {
        $('#purchaseModal').on('shown.bs.modal', function() {
            populateGRNDropdown(); // Populate dropdown when modal opens

            const editId = $('#purchaseForm').data('edit-id');
            
            if (editId) {
                const editRow = JSON.parse(atob($('#purchaseForm').data('edit-row')));
                const purchaseOrderId = [...$("#purchase_order_id").find('option')].find(o=>o.text==editRow.purchase_id)?.value;
                $('#purchaseForm').attr('action', `{{ route('superadmin.purchase.update',['purchase'=>'!edit-id!']) }}`.replace('!edit-id!',editId));
                console.log({purchaseOrderId,editRow});
                $('#purchase_order_id').val(purchaseOrderId);
                $('#purchase_order_date').val(editRow.purchase_date);
                $('#purchase_no').val(editRow.invoice_no);
                $('#vendor_email').val(editRow.party.email);
                $('#purchase_id').val(editRow.party_id);
                // $('#vendor_reference_no').val(editRow.reference);
                $('#notes').val(editRow.note);
                $('#invoice_date').val(editRow.invoice_date);
                $('#invoice_no').val(editRow.invoice_no);
                $('#company_gstn').val(editRow.party.gstno);
                $('#company_address').val(editRow.party.billing_address);
                $('#company_phone').val(editRow.party.mobile);
                $('#description').val(editRow.remarks);
                // $('#delivery_terms').val(editRow.delivery_terms);
                $('#additional_charges').val(editRow.additional_charges);
                $('#sub_total').val(editRow.sub_total);
                // $('#sgst_amount').val(editRow.sgst_amount);
                // $('#cgst_amount').val(editRow.cgst_amount);
                // $('#igst_amount').val(editRow.igst_amount);
                // $('#round_up').val(editRow.round_up);
                $('#total_amount').val(editRow.total_amount);
                $('#paid_amount').val(editRow.paid_amount);
                $('#balance_amount').val(editRow.balance_amount);
                $('#payment_mode').val(editRow.payment_mode);
                $('#payment_reference').val(editRow.reference);
                // $('#payment_reason').val(editRow.payment_reason);
                $("#notes").val(editRow.notes);
                populateItems(editRow.items.map(item=>({
                    ...item,
                    stock_item:item.item_id,
                    description:item.description,
                    quantity:item.quantity,
                    uom:item.uom,
                    unit_rate:item.rate
                })));
                $('#modalTitle').text('Edit Purchase');
            } else {
                $('#purchaseForm').attr('action', `{{ route('superadmin.purchase.store') }}`);
                $('#modalTitle').text('Add New Purchase');
            }
        });

        //listen for modal hide
        $('#purchaseModal').on('hidden.bs.modal', function() {
            // console.log('Modal hidden');
        });
    });
</script>
