<!-- New Purchase Order Modal -->
<div class="modal fade" id="purchaseInvoiceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Add New Purchase Invoice</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="purchaseInvoiceForm" method="POST" action="{{ route('superadmin.purchase.v1.store') }}"
                enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="row">
                        <!-- Basic Information -->
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="purchase_no" class="form-label">Purchase Invoice No *</label>
                                <input type="text" class="form-control" id="purchase_no"
                                    name="purchase_no" value="{{ $nextPurchaseInvoiceNo ?? '' }}" required readonly>
                            </div>
                            <div class="mb-3">
                                <label for="vendor_invoice_no" class="form-label">Vendor Invoice No<span class="required"> *</span></label>
                                <input type="text" class="form-control" id="vendor_invoice_no" name="vendor_invoice_no" required>
                            </div>

                            <div class="mb-3">
                                <label for="purchase_date" class="form-label">Purchase Invoice Date *</label>
                                <input type="date" class="form-control" id="purchase_date"
                                    name="purchase_date" value="{{ $currentDate ?? date('Y-m-d') }}" required>
                            </div>

                            <div class="mb-3">
                                <label for="vendor_id" class="form-label">Vendor *</label>
                                <select class="form-select" id="vendor_id" name="vendor_id" required onchange="getVendorDetails(this)" >
                                    <option value="">Select Vendor</option>
                                    @if (isset($vendors))
                                        @foreach ($vendors as $vendor)
                                            <option 
                                                value="{{ $vendor->id }}"
                                                data-row="{{ base64_encode(json_encode($vendor)) }}"
                                                >
                                                {{ $vendor->company }}
                                            </option>
                                        @endforeach
                                    @endif
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="vendor_ref_no" class="form-label">Vendor Reference No</label>
                                <input type="text" class="form-control" id="vendor_ref_no" name="vendor_ref_no">
                            </div>

                             <div class="mb-3 d-none" >
                                <label for="company_name" class="form-label">Company Name</label>
                                <input type="text" class="form-control" id="company_name" name="company_name" />
                            </div>
                            <div class="mb-3">
                                <label for="company_phone" class="form-label">Company Phone</label>
                                <input type="text" class="form-control" id="company_phone" name="company_phone">
                            </div>
                        </div>

                        <!-- Purchase Order & Quotation Information -->
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="purchase_order_no" class="form-label">Purchase Order No</label>
                                <select class="form-select" id="purchase_order_no" name="purchase_order_no" data-label="[purchase_order_no] - [vendor.company]">
                                    <option value="">Select Purchase Order</option>
                                    @if (isset($purchaseOrders))
                                        @foreach ($purchaseOrders as $purchaseOrder)
                                            <option value="{{ $purchaseOrder->purchase_order_no }}"
                                                data-row="{{ base64_encode(json_encode($purchaseOrder)) }}">
                                                {{ $purchaseOrder->purchase_order_no }} - {{ $purchaseOrder->vendor->company_name ?? '' }}
                                            </option>
                                        @endforeach
                                    @endif
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="purchase_order_date" class="form-label">Purchase Order Date</label>
                                <input type="date" class="form-control" id="purchase_order_date" name="purchase_order_date">
                            </div>

                            <div class="mb-3 d-none">
                                <label for="quotation_no" class="form-label">Quotation No</label>
                                <input type="text" class="form-control" id="quotation_no" name="quotation_no">
                            </div>

                            <div class="mb-3 d-none">
                                <label for="quotation_date" class="form-label">Quotation Date</label>
                                <input type="date" class="form-control" id="quotation_date" name="quotation_date">
                            </div>

                              <div class="mb-3 d-none">
                                <label for="company_address" class="form-label">Company Address</label>
                                <textarea class="form-control" id="company_address" name="company_address" rows="3"></textarea>
                            </div>

                            

                            <div class="mb-3 d-none">
                                <label for="ship_address" class="form-label">Shipping Address</label>
                                <textarea class="form-control" id="ship_address" name="ship_address" rows="3"></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="company_email" class="form-label">Company Email</label>
                                <input type="email" class="form-control" id="company_email" name="company_email">
                            </div>
                            <div class="mb-3">
                                <label for="company_gstn" class="form-label">Company GSTN</label>
                                <input type="text" class="form-control" id="company_gstn" name="company_gstn">
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="payment_terms">Payment Terms</label>
                                <select class="form-select" name="payment_terms" id="payment_terms">
                                    <option value="">Select Payment Terms</option>
                                    <option value="0">Immediate</option>
                                    <option value="30">30 Days</option>
                                    <option value="45">45 Days</option>
                                    <option value="45+">> 45 Days</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="bill_address" class="form-label">Billing Address</label>
                                <textarea class="form-control" id="bill_address" name="bill_address" rows="2"></textarea>
                            </div>
                        </div>
                    </div>

                 

                    <!-- Items Section -->
                    <div class="row">
                        <div class="col-12">
                            <h6 class="mb-3">Items</h6>
                            @include('v1.purchase.partials.purchase-items')
                        </div>
                    </div>

                    <!-- Totals Section -->
                    <!-- <div class="row mb-3 ">
                        <div class="col-md-8 offset-md-4 d-flex flex-column gap-3">
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">Subtotal</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="subtotal" name="subtotal"
                                        value="0" step="0.01" readonly>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">SGST Amount</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="sgst_amount" name="sgst_amount"
                                        value="0" step="0.01" readonly>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">CGST Amount</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="cgst_amount" name="cgst_amount"
                                        value="0" step="0.01" readonly>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">IGST Amount</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="igst_amount" name="igst_amount"
                                        value="0" step="0.01" readonly>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">Additional Charges</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="additional_charges" name="additional_charges"
                                        value="0" step="0.01" >
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label"><strong>Grand Total</strong></label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="grand_total" name="grand_total"
                                        value="0" step="0.01" readonly>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">TDS Amount</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="tds_amount" name="tds_amount"
                                        value="0" step="0.01" readonly>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">Round Up</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="round_up" name="round_up"
                                        value="0" step="0.01" disabled>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label"><strong>Net Payable Amount</strong></label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="net_payable_amount" name="net_payable_amount"
                                        value="0" step="0.01" readonly>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">Paid Amount</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="paid_amount" name="paid_amount"
                                        value="0" step="0.01" >
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">Balance Amount</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="number" class="form-control" id="balance_amount" name="balance_amount"
                                        value="0" step="0.01" readonly>
                                </div>
                            </div>
                            <input type="hidden" id="payment_status" name="payment_status" value="unpaid">
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">Amount in Words</label>
                                </div>
                                <div class="col-md-6">
                                    <input type="text" class="form-control" id="inr_in_words"
                                        name="inr_in_words">
                                </div>
                            </div>
                        </div>
                    </div> -->
                    <div class="row mb-3">
    <div class="col-md-12">
        <div class="row">
            <!-- Row 1 -->
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Subtotal(INR)</label>
                    <input type="number" class="form-control" id="subtotal" name="subtotal" value="0" step="0.01" readonly style="text-align: right;">
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">SGST Amount(INR)</label>
                    <input type="number" class="form-control" id="sgst_amount" name="sgst_amount" value="0" step="0.01" readonly style="text-align: right;">
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">CGST Amount(INR)</label>
                    <input type="number" class="form-control" id="cgst_amount" name="cgst_amount" value="0" step="0.01" readonly style="text-align: right;">
                </div>
            </div>
            
            <!-- Row 2 -->
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">IGST Amount(INR)</label>
                    <input type="number" class="form-control" id="igst_amount" name="igst_amount" value="0" step="0.01" readonly style="text-align: right;">
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Additional Charges(INR)</label>
                    <input type="number" class="form-control" id="additional_charges" name="additional_charges" value="0" step="0.01" style="text-align: right;">
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label"><strong>Total Invoice Amount(INR)</strong></label>
                    <input type="number" class="form-control" id="grand_total" name="grand_total" value="0" step="0.01" readonly style="text-align: right;">
                </div>
            </div>
            
            <!-- Row 3 -->
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">TDS Amount(INR)</label>
                    <input type="number" class="form-control" id="tds_amount" name="tds_amount" value="0" step="0.01" readonly style="text-align: right;">
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Round Up</label>
                    <input type="number" class="form-control" id="round_up" name="round_up" value="0" step="0.01" disabled style="text-align: right;">
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label"><strong>Net Payable Amount(INR)</strong></label>
                    <input type="number" class="form-control" id="net_payable_amount" name="net_payable_amount" value="0" step="0.01" readonly style="text-align: right;">
                </div>
            </div>
            
            <!-- Row 4 -->
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Paid Amount(INR)</label>
                    <input type="number" class="form-control" id="paid_amount" name="paid_amount" value="0" step="1" style="text-align: right;">
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Balance Amount(INR)</label>
                    <input type="number" class="form-control" id="balance_amount" name="balance_amount" value="0" step="0.01" readonly style="text-align: right;">
                </div>
            </div>
            <div class="col-md-4">
                <div class="mb-3">
                    <label class="form-label">Amount in Words(INR)</label>
                    <input type="text" class="form-control" id="inr_in_words" name="inr_in_words">
                </div>
            </div>
        </div>
        
        <!-- Hidden field -->
        <input type="hidden" id="payment_status" name="payment_status" value="unpaid">
    </div>
</div>

                    <div class="card" id="gst-aggregate">
                        <div class="card-header">Payment Details</div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label">Payment Method</label>
                                    <select class="form-control form-select" id="payment_method" name="payment_method">
                                        <option value="">Select Payment Method</option>
                                        <option value="Cash">Cash</option>
                                        <option value="Cheque">Cheque</option>
                                        <option value="Bank Transfer NEFT">Bank Transfer NEFT</option>
                                        <option value="Bank Transfer RTGS">Bank Transfer RTGS</option>
                                        <option value="Bank Transfer CMS">Bank Transfer CMS</option>
                                        <option value="Credit">Credit</option>
                                        <option value="Other">Other</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Payment Reference No</label>
                                    <input type="text" class="form-control" id="payment_reference_no" name="payment_reference_no">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Reason (if any)</label>
                                    <textarea class="form-control" id="payment_delay_reason" name="payment_delay_reason" rows="2"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Additional Charges, Delivery Terms, Note, Status -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="purchaseFiles" class="form-label">Upload Files</label>
                                <input type="file" class="form-control" id="purchaseFiles"
                                    name="purchaseFiles[]" multiple>
                                <small class="form-text text-muted">Allowed file types: PDF, JPG, JPEG, PNG. Max size:
                                    2MB per file.</small>
                            </div>
                            <!-- show uploaded files -->
                            <div id="filesContainer" class="d-flex align-items-center gap-2 mb-2 flex-wrap" >
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="description" class="form-label">Description</label>
                                <textarea class="form-control" id="description" name="description" rows="4"></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="delivery_terms" class="form-label">Delivery Terms</label>
                                <textarea type="text" class="form-control" id="delivery_terms"
                                    name="delivery_terms"></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="note" class="form-label">Note</label>
                                <textarea class="form-control" id="note" name="note" rows="2"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                   <button type="button" class="btn btn-outline-secondary px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-gray-400" data-dismiss="modal">
                      Cancel
                    </button>
                    <button type="submit" class="btn btn-primary">
                       Save Purchase Invoice
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@push('scripts')
    <script>
        let isFormDirty = false;
    
        // Track changes to any form field inside the modal
        $('#purchaseInvoiceForm').on('change input', 'input, textarea, select', function () {
            isFormDirty = true;
        });

        const listColumns = {!! json_encode($columns) !!};

        function getVendorDetails(element) {
            let selectedOption = $(element).find('option:selected');
            let rowData = JSON.parse(atob(selectedOption.data('row')));
            $('#company_name').val(rowData.company);
            $('#company_address').val(rowData.address);
            $('#company_gstn').val(rowData.gstno);
            $('#company_phone').val(rowData.mobile);
            $('#company_email').val(rowData.email);
            $('#bill_address').val(rowData.billing_address);
            console.log({rowData});
            // console.log({rowData});
        }

        function fillForm(purchaseOrder, options = {}, formElement = $("#purchaseInvoiceForm")) {
            console.log({purchaseOrder});
            const mappedKeys = options.keys || {};
            const mappedValues = options.values || {};
            // Fill form fields
            const ids = [...formElement.find("input,select,textarea")]
                .map(v => $(v).attr('id'))
                .filter(v => v);
            ids.forEach(id => {
                const value = dotwalk(purchaseOrder, mappedKeys[id]) || dotwalk(purchaseOrder, id);
                const node = formElement.find(`#${id}`);
                if(node[0].tagName === 'SELECT' && value) {
                    const label = node.attr('data-label');
                    if(label) {
                        const exractedLabels = label.match(/\[(.*?)\]/g).map(v => v.replace('[', '').replace(']', ''));
                        const extractedValues = exractedLabels.map(v => dotwalk(purchaseOrder, v));
                        const generatedLabel = exractedLabels.reduce((acc, v, i) => acc.replace(`[${v}]`, extractedValues[i]), label);
                        let hasOption = [...$(node).find('option')].find(o=>o.value==value);
                        if(!hasOption) {
                            node[0].append(new Option(generatedLabel, value));
                        }
                    }
                }
                if (value) {
                    node.val(mappedValues[id] ? mappedValues[id](value) : value);
                }
            });

            // Populate items if available
            const items = dotwalk(purchaseOrder, mappedKeys.items) || purchaseOrder.items;
            if (items && items.length > 0) {
                populateItems(items);
            }

            if(purchaseOrder.files) {
                const filesContainer = $("#filesContainer");
                filesContainer.empty();
                purchaseOrder.files.forEach(file => {
                    const fileElement = `<div class="file-item d-flex align-items-center gap-2 mb-2">
                        <a href="/storage/${file.file_path}" target="_blank" class="file-link text-black d-flex flex-column">
                            <img src="/storage/${file.file_path}" alt="${file.file_name}" class="img-thumbnail" style="max-width: 100px; max-height: 100px;">
                            <span class="d-flex align-items-center gap-2">
                                <span class="file-name text-dark">${file.file_name}</span>
                            </span>
                        </a>
                    </div>`;
                    filesContainer.append(fileElement);
                });
            } else {
                $("#filesContainer").empty();
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            
            $('#purchaseInvoiceModal').on('shown.bs.modal', function () {
                $('#vendor_invoice_no').trigger('focus');
            });

            let allowClose = false;

            $('#purchaseInvoiceModal').on('hide.bs.modal', function (e) {
                if (isFormDirty && !allowClose) {
                    e.preventDefault();
            
                    Swal.fire({
                        title: 'Unsaved Changes',
                        text: 'You have unsaved changes. What would you like to do?',
                        icon: 'warning',
                        showCancelButton: true,
                        showDenyButton: true,
                        confirmButtonText: 'Save',
                        denyButtonText: 'Discard',
                        cancelButtonText: 'Cancel',
                        reverseButtons: true
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Save (submit form)
                            $('#purchaseInvoiceForm').submit();
                        } else if (result.isDenied) {
                            // Discard (force close modal)
                            isFormDirty = false;
                            allowClose = true;
                            $('#purchaseInvoiceModal').modal('hide');
                            allowClose = false;
                        }
                        // Cancel does nothing
                    });
                }
            });

            // Edit purchase order button
            $(document).on('click', '.edit-purchase-invoice', function() {
                let id = $(this).data('id');
                let rowData = $(this).data('row');

                if (rowData) {
                    try {
                        let purchaseOrder = JSON.parse(atob(rowData));

                        // Set form data for editing
                        $('#purchaseInvoiceForm').data('edit-id', id);
                        $('#purchaseInvoiceForm').data('edit-row', rowData);
                        $('#purchaseInvoiceForm').attr('action', '{{ route('superadmin.purchase.v1.update', ['id' => ':id']) }}'.replace(':id', id));
                        fillForm(purchaseOrder, {
                            keys: {},
                            values: {
                                purchase_order_date: (v) => formatDate(new Date(v), 'yyyy-mm-dd'),
                                quotation_date: (v) => formatDate(new Date(v), 'yyyy-mm-dd'),
                            }
                        });
                        $('#modalTitle').text('Edit Purchase Invoice');
                        isFormDirty = false;
                        $('#purchaseInvoiceModal').modal('show');


                    } catch (e) {
                        console.error('Error parsing purchase order data:', e);
                        alert('Error loading purchase order data');
                    }
                } else {
                    $('#purchaseInvoiceForm').data('edit-id', null);
                    $('#purchaseInvoiceForm').data('edit-row', null);
                    $('#purchaseInvoiceForm').attr('action', '{{ route('superadmin.purchase.v1.store') }}');
                    $('#modalTitle').text('Add New Purchase Invoice');
                    $('#purchaseInvoiceModal').modal('show');
                }
            });
            // Quotation selection
            $('#purchase_order_no').change(function() {
                let selectedOption = $(this).find('option:selected');
                let rowData = JSON.parse(atob(selectedOption.data('row')));
                if (selectedOption.val()) {
                    console.log({
                        rowData
                    });
                    fillForm(rowData, {
                        keys: {
                            company_name: 'vendor.company',
                            company_address: 'address',
                            company_gstn: 'vendor.gstno',
                            company_phone: 'vendor.mobile',
                            company_email: 'vendor.email',
                            vendor_ref_no: 'vendor_reference_no',
                            bill_address: 'vendor.billing_address',
                            ship_address: 'vendor.shipping_address',
                        },
                        values: {
                            purchase_date: (v) => formatDate(new Date(v), 'yyyy-mm-dd'),
                            purchase_order_date: (v) => formatDate(new Date(v), 'yyyy-mm-dd'),
                            quotation_date: (v) => formatDate(new Date(v), 'yyyy-mm-dd'),   
                        }
                    });
                }
            });
        });
    </script>
@endpush
