@extends('layouts.dashboard.superadminapp')

@section('title', 'Purchase Management System')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<!-- Bootstrap 4 CSS (already included if using AdminLTE or similar) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css">

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

@section('content')
    <style>
        button {
            width: auto;
        }

        .card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            border: none;
        }

        .card-header {
            background-color: #4e73df;
            color: white;
            border-radius: 10px 10px 0 0 !important;
            padding: 15px 20px;
        }

        .nav-pills .nav-link.active {
            background-color: #4e73df;
        }

        .nav-pills .nav-link {
            color: #4e73df;
        }

        .btn-primary {
            background-color: #4e73df;
            border-color: #4e73df;
        }

        .btn-primary:hover {
            background-color: #3a5bc7;
            border-color: #3a5bc7;
        }

        .form-control,
        .form-select {
            border-radius: 5px;
            padding: 10px;
        }

        .table th {
            background-color: #f8f9fc;

        }

        .table {
            display: inline-table;
        }

        .tab-content {
            padding: 20px;
            background-color: white;
            border-radius: 0 0 10px 10px;
        }

        .chart-container {
            height: 300px;
            margin-bottom: 30px;
        }

        .filter-section {
            background-color: #f8f9fc;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }

        .badge-paid {
            background-color: #1cc88a;
        }

        .badge-partial {
            background-color: #f6c23e;
        }

        .badge-unpaid {
            background-color: #e74a3b;
        }

        .modal-content {
            border-radius: 10px;
        }

        .item-row {
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .action-btns {
            white-space: nowrap;
        }

        #filePreview img {
            width: 100%;
            object-fit: contain;
        }

        /* Ensure modal doesn’t cut off Select2 dropdown */
        #purchaseModal .modal-dialog {
            max-height: 90vh;
        }

        #purchaseModal .modal-content {
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        #purchaseModal .modal-header,
        #purchaseModal .modal-footer {
            flex-shrink: 0;
        }

        #purchaseModal .modal-body {
            overflow-y: auto;
            flex-grow: 1;
            padding-right: 1rem;
            /* optional: helps show scrollbar */
        }


        /* Force Select2 dropdown above everything */
        .select2-container {
            z-index: 999999 !important;
        }
    </style>
    <!-- Page Heading -->
    <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL | Purchase Management System</h1>
        <div class="display-date">
            <span id="day">day</span>,
            <span id="daynum">00</span>
            <span id="month">month</span>
            <span id="year">0000</span>
        </div>
        <div class="display-time"></div>
    </div>
    <div class="container-fluid">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Purchase Management System</h5>
                <button class="btn btn-light btn-sm" id="addPurchaseBtn">
                    <i class="fas fa-plus me-1"></i> Add New Purchase
                </button>
            </div>
            <div class="card-body">
                <ul class="nav nav-pills mb-4" id="pills-tab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="pills-payment-tab" data-bs-toggle="pill"
                            data-bs-target="#pills-payment" type="button" role="tab"
                            onclick="loadPaymentTableAgain()">Vendor Payments</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-credit-tab" data-bs-toggle="pill" data-bs-target="#pills-credit"
                            type="button" role="tab">Credit Notes</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-debit-tab" data-bs-toggle="pill" data-bs-target="#pills-debit"
                            type="button" role="tab">Debit Notes</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-aging-tab" data-bs-toggle="pill" data-bs-target="#pills-aging"
                            type="button" role="tab">Aging Report</button>
                    </li>
                </ul>

                <div class="tab-content" id="pills-tabContent">
                    
                    
                    <!-- Vendor Payments Tab -->
                    <div class="tab-pane fade show active" id="pills-payment" role="tabpanel">
                        <div class="filter-section">
                            <div class="row">
                                <div class="col-md-3">
                                    <label class="form-label">Date Range</label>
                                    <input type="text" class="form-control payment-date-range"
                                        placeholder="Select date range" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Party</label>
                                    <select class="form-select" id="payment-party" required>
                                        <option value="">Select Party</option>
                                        @foreach ($parties as $party)
                                            <option value="{{ $party->id }}">{{ $party->company }}</option>
                                        @endforeach

                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Amount Range</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control min-amount" placeholder="Min">
                                        <input type="number" class="form-control max-amount" placeholder="Max">
                                    </div>
                                </div>
                                <div class="col-md-3 d-flex align-items-end">
                                    <button class="btn btn-primary me-2" id="applyPaymentFilters">Apply Filters</button>
                                    <button class="btn btn-outline-secondary" id="resetPaymentFilters">Reset</button>
                                </div>
                            </div>
                        </div>

                        <table id="paymentTable" class="display nowrap table table-striped" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Payment ID</th>
                                    <th>Invoice Date</th>
                                    <th>Purchase Date</th>
                                    <th>Party</th>
                                    <th>Invoice ID</th>
                                    <th>Purchase ID</th>
                                    <th>Amount</th>
                                    <th>Payment Mode</th>
                                    <th>Reference</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Data will be loaded here -->
                            </tbody>
                        </table>
                    </div>

                    <!-- Credit Notes Tab -->
                    <div class="tab-pane fade" id="pills-credit" role="tabpanel">
                        <div class="filter-section">
                            <div class="row">
                                <div class="col-md-3">
                                    <label class="form-label">Date Range</label>
                                    <input type="text" class="form-control credit-date-range"
                                        placeholder="Select date range" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Party</label>
                                    <select class="form-select" id="credit-party" required>
                                        <option value="">Select Party</option>
                                        @foreach ($parties as $party)
                                            <option value="{{ $party->id }}">{{ $party->company }}</option>
                                        @endforeach

                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Credit Note No</label>
                                    <input type="text" class="form-control credit-note-filter"
                                        placeholder="Credit Note No">
                                </div>
                                <div class="col-md-3 d-flex align-items-end">
                                    <button class="btn btn-primary me-2" id="applyCreditFilters">Apply Filters</button>
                                    <button class="btn btn-outline-secondary" id="resetCreditFilters">Reset</button>
                                </div>
                            </div>
                        </div>

                        <table id="creditTable" class="table table-striped table-bordered" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Credit Note No</th>
                                    <th>Date</th>
                                    <th>Party</th>
                                    <th>Invoice ID</th>
                                    <th>Amount</th>
                                    <th>Reason</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Data will be loaded here -->
                            </tbody>
                        </table>
                    </div>

                     <!-- Debit Notes Tab -->
                     <div class="tab-pane fade" id="pills-debit" role="tabpanel">
                        @include('superadmin.purchasemanagement.partials.debit-notes-tab')
                     </div>

                    <!-- Aging Report Tab -->
                    <div class="tab-pane fade" id="pills-aging" role="tabpanel">
                        <div class="chart-container">
                            <canvas id="agingChart"></canvas>
                        </div>

                        <div class="filter-section">
                            <div class="row">
                                <div class="col-md-4">
                                    <label class="form-label">As of Date</label>
                                    <input type="text" class="form-control aging-date" placeholder="Select date">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Party</label>
                                    <select class="form-select" id="party" required>
                                        <option value="">Select Party</option>
                                        @foreach ($parties as $party)
                                            <option value="{{ $party->id }}">{{ $party->company }}</option>
                                        @endforeach

                                    </select>
                                </div>
                                <div class="col-md-4 d-flex align-items-end">
                                    <button class="btn btn-primary me-2" id="applyAgingFilters">Apply Filters</button>
                                    <button class="btn btn-outline-secondary" id="resetAgingFilters">Reset</button>
                                </div>
                            </div>
                        </div>

                        <table id="agingTable" class="table table-striped table-bordered" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Party</th>
                                    <th>Current</th>
                                    <th>1-30 Days</th>
                                    <th>31-60 Days</th>
                                    <th>61-90 Days</th>
                                    <th>>90 Days</th>
                                    <th>Total Due</th>
                                </tr>
                            </thead>

                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @include('superadmin.purchasemanagement.newpurchasemodal')

    <!-- Import Data Modal -->
    <div class="modal fade" id="importModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Import Purchase Data</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="formFile" class="form-label">Select CSV file to import</label>
                        <input class="form-control" type="file" id="formFile" accept=".csv">
                    </div>
                    <div class="alert alert-info">
                        <small>CSV file should contain columns: Date, Party, Items, Quantity, UOM, Rate, Discount,
                            Additional Charges, TDS, Paid Amount</small>
                    </div>
                    <div class="progress mb-3 d-none" id="importProgress">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"
                            style="width: 0%"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="importData">Import</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Payment Modal -->
    <div class="modal fade" id="paymentModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Record Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="paymentForm">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Invoice ID</label>
                                <input type="text" class="form-control" id="paymentInvoiceNo" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Date</label>
                                <input type="text" class="form-control" id="paymentDate" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Party</label>
                                <input type="text" class="form-control" id="paymentParty" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Due Amount</label>
                                <input type="text" class="form-control" id="dueAmount" readonly>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Payment Amount</label>
                                <input type="number" class="form-control" id="paymentAmount" min="0"
                                    step="0.01" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Payment Mode</label>
                                <select class="form-select" id="paymentMode" required>
                                    <option value="Cash">Cash</option>
                                    <option value="Bank Transfer">Bank Transfer</option>
                                    <option value="Cheque">Cheque</option>
                                    <option value="Credit Card">Credit Card</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Reference</label>
                            <input type="text" class="form-control" id="paymentReference">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" id="paymentNotes" rows="2"></textarea>
                        </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="savePayment">Save Payment</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Credit Note Modal -->
    <div class="modal fade" id="creditModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Credit Note</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="creditForm">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Credit Note No</label>
                                <input type="text" class="form-control" id="creditNoteNo" readonly>
                                <input type="hidden" id="creditPurchaseId">
                                <input type="hidden" id="creditPartyId">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Date</label>
                                <input type="text" class="form-control" id="creditDate" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Invoice ID</label>
                                <input type="text" class="form-control" id="creditInvoiceNo" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Party</label>
                                <input type="text" class="form-control" id="creditParty" readonly>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Amount</label>
                                <input type="number" class="form-control" id="creditAmount" min="0"
                                    step="0.01" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Reason</label>
                                <select class="form-select" id="creditReason" required>
                                    <option value="Return">Return</option>
                                    <option value="Discount">Discount</option>
                                    <option value="Damage">Damage</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" id="creditDescription" rows="2"></textarea>
                        </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="saveCreditNote">Save Credit Note</button>
                </div>
            </div>
        </div>

    </div>

    <div class="modal fade" id="viewPurchaseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Purchase Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewPurchaseBody">
                    <!-- Details will be loaded here -->
                </div>
            </div>
        </div>
    </div>

    <!-- Credit Note View Modal -->
    <div class="modal fade" id="viewCreditNoteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Credit Note Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewCreditNoteBody">
                    <!-- Details will be loaded here -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- JS Logic for Debit Notes -->
    @push('scripts')
    <script>
        // ... (Existing Scripts) ...

        // ==================== DEBIT NOTES (PURCHASE) LOGIC ====================
        $(document).ready(function() {
            // Initialize Date Range Picker for Debit Notes
            $('.debit-date-range').daterangepicker({
                autoUpdateInput: false,
                locale: { cancelLabel: 'Clear' }
            });
            $('.debit-date-range').on('apply.daterangepicker', function(ev, picker) {
                $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
            });
            $('.debit-date-range').on('cancel.daterangepicker', function(ev, picker) {
                $(this).val('');
            });

            // Initialize Debit Notes Table
            var debitTable = $('#debitTable').DataTable({
                processing: true,
                serverSide: false, // Client side for now as controller returns all
                ajax: {
                    url: '{{ route("superadmin.purchase.debitNotes.list") }}',
                    data: function(d) {
                        let dr = $('.debit-date-range').val().split(' - ');
                        if (dr.length === 2) {
                            d.from_date = dr[0];
                            d.to_date = dr[1];
                        }
                        d.party_id = $('#debit-party').val();
                        d.debit_note_no = $('.debit-note-filter').val();
                    }
                },
                columns: [
                    { data: 'debit_note_no' },
                    { data: 'date' },
                    { data: 'party.company', defaultContent: '-' },
                    { data: 'invoice_no' },
                    { 
                        data: 'amount', 
                        className: 'text-right',
                        render: function(data) { return '₹ ' + parseFloat(data).toFixed(2); }
                    },
                    { data: 'reason' },
                    {
                        data: null,
                        className: 'text-center',
                        render: function(data, type, row) {
                            return `
                                <button class="btn btn-sm btn-info edit-debit-btn" data-id="${row.id}" data-row='${JSON.stringify(row)}'>
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger delete-debit-btn" data-id="${row.id}">
                                    <i class="fas fa-trash"></i>
                                </button>
                            `;
                        }
                    }
                ]
            });

            // Filter Buttons
            $('#applyDebitFilters').click(function() {
                debitTable.ajax.reload();
            });

            $('#resetDebitFilters').click(function() {
                $('.debit-date-range').val('');
                $('#debit-party').val('');
                $('.debit-note-filter').val('');
                debitTable.ajax.reload();
            });

            // Add Debit Note Button
            $('#addDebitNoteBtn').click(function() {
                $('#debitNoteForm')[0].reset();
                $('#debitNoteForm').data('id', null);
                $('#debitNoteModalLabel').text('Add Debit Note (Vendor)');
                
                // Fetch next number
                $.get('{{ route("superadmin.purchase.debitNotes.nextNumber") }}', function(data) {
                    $('#debit_note_no').val(data.next_number);
                });
                
                $('#debitNoteModal').modal('show');
            });

            // Edit Debit Note
            $(document).on('click', '.edit-debit-btn', function() {
                let row = $(this).data('row');
                if (typeof row === 'string') row = JSON.parse(row); // Safety

                $('#debitNoteForm').data('id', row.id);
                $('#debitNoteModalLabel').text('Edit Debit Note');
                $('#debit_note_no').val(row.debit_note_no);
                $('#debit_note_date').val(row.date);
                $('#debit_note_party').val(row.party_id);
                $('#debit_note_invoice').val(row.invoice_no);
                $('#debit_note_amount').val(row.amount);
                $('#debit_note_reason').val(row.reason);
                $('#debit_note_description').val(row.description);
                $('#debitNoteModal').modal('show');
            });

            // Delete Debit Note
            $(document).on('click', '.delete-debit-btn', function() {
                if(!confirm('Are you sure you want to delete this debit note?')) return;
                let id = $(this).data('id');
                $.ajax({
                    url: '{{ route("superadmin.purchase.debitNotes.delete", ":id") }}'.replace(':id', id),
                    type: 'DELETE',
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    success: function(res) {
                        debitTable.ajax.reload();
                    },
                    error: function(err) {
                        alert('Error deleting debit note');
                    }
                });
            });

            // Save Debit Note
            $('#debitNoteForm').submit(function(e) {
                e.preventDefault();
                let id = $(this).data('id');
                let url = id 
                    ? '{{ route("superadmin.purchase.debitNotes.update", ":id") }}'.replace(':id', id)
                    : '{{ route("superadmin.purchase.debitNotes.store") }}';
                let method = id ? 'PUT' : 'POST';

                $.ajax({
                    url: url,
                    type: method,
                    data: $(this).serialize(),
                    success: function(res) {
                        $('#debitNoteModal').modal('hide');
                        debitTable.ajax.reload();
                    },
                    error: function(xhr) {
                         alert('Error: ' + (xhr.responseJSON?.message || 'Unknown error'));
                    }
                });
            });
        });
    </script>
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/papaparse@5.3.2/papaparse.min.js"></script>

        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

        <!-- Date Range Picker -->
        <script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/min/moment.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

        <!-- ✅ Responsive Extension JS (vanilla) -->
        <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>

        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

        <script>
            /*
                    function initializeItemSelects() {
                        // Destroy only previously initialized ones to avoid breaking others
                        $('.item-select').each(function () {
                            if ($(this).hasClass("select2-hidden-accessible")) {
                                $(this).select2('destroy');
                            }
                        });
                    
                        // Re-initialize all
                        $('.item-select').select2({
                            dropdownParent: $('#purchaseModal'),
                            width: '100%',
                            placeholder: "Select Item",
                            allowClear: true
                        });
                    }
                    */

            function initializeItemSelects() {
                $('.item-select').each(function() {
                    const $this = $(this);

                    if ($this.hasClass("select2-hidden-accessible")) {
                        $this.select2('destroy');
                    }

                    $this.select2({
                        dropdownParent: $('#purchaseModal'),
                        width: '100%',
                        placeholder: "Select Item",
                        allowClear: true
                    });
                });
            }

            $('#exportDataBtn').click(function() {
                let params = $.param({
                    date_range: $('.date-range').val(),
                    party_id: $('#party').val(),
                    invoice_no: $('.invoice-filter').val(),
                    status: $('.status-filter').val()
                });
                window.location = "{{ route('superadmin.purchase.export') }}?" + params;
            });

            $('#saveCreditNote').click(function() {
                // Get data from form fields
                let data = {
                    credit_note_no: $('#creditNoteNo').val(),
                    date: $('#creditDate').val(),
                    invoice_no: $('#creditInvoiceNo').val(),
                    party_id: $('#creditPartyId').val(), // make sure this is party_id, not purchase_id!
                    amount: $('#creditAmount').val(),
                    reason: $('#creditReason').val(),
                    description: $('#creditDescription').val(),
                    _token: $('meta[name="csrf-token"]').attr('content')
                };

                // In your modal you have <input type="hidden" id="creditPurchaseId"> 
                // If that's actually the purchase ID, you'll need to find party_id via AJAX or pass party_id directly.
                // For now, let's suppose you store party_id in data-party attribute as well:
                // <button ... data-party_id="4">
                // And in modal: $('#creditPartyId').val()

                // If you set hidden input for party_id:
                // data.party_id = $('#creditPartyId').val();

                $.post('{{ url('/superadmin/creditnotes') }}', data)
                    .done(function(res) {
                        alert('Credit Note saved!');
                        $('#creditModal').modal('hide');
                        // Optionally reload credit notes table if you have it
                    })
                    .fail(function(xhr) {
                        alert('Failed: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON
                            .message : 'Validation Error'));
                    });
            });

            $('#applyPaymentFilters').click(function() {
                $('#paymentTable').DataTable().ajax.reload();
            });

            $('#resetPaymentFilters').click(function() {
                $('.payment-date-range').val('');
                $('#paymentParty').val('');
                $('.min-amount, .max-amount').val('');
                $('#paymentTable').DataTable().ajax.reload();
            });

            $(document).ready(function() {
                // Vendor Payment Table
                var paymentTable = $('#paymentTable').DataTable({
                    processing: true,
                    serverSide: true,
                    responsive: {
                        details: {
                            type: 'inline',
                            target: 'tr',
                            renderer: responsiveRenderer
                        }
                    },
                    ajax: {
                        url: '{{ route('superadmin.purchase.payments') }}',
                        data: function(d) {
                            d.date_range = $('.payment-date-range').val();
                            d.party_id = $('#payment-party').val();
                            d.min_amount = $('.min-amount').val();
                            d.max_amount = $('.max-amount').val();
                        }
                    },
                    columns: [{
                            data: 'id',
                            title: 'Payment ID'
                        },
                        {
                            data: 'invoice_date',
                            title: 'Invoice Date'
                        },
                        {
                            data: 'purchase_date',
                            title: 'Purchase Date'
                        },
                        {
                            data: 'party',
                            title: 'Party'
                        },
                        {
                            data: 'invoice_no',
                            title: 'Invoice ID'
                        },
                        {
                            data: 'purchase_id',
                            title: 'Purchase ID'
                        },
                        {
                            data: 'paid_amount',
                            title: 'Amount'
                        },
                        {
                            data: 'payment_mode',
                            title: 'Payment Mode'
                        },
                        {
                            data: 'reference',
                            title: 'Reference'
                        },
                        {
                            data: 'actions',
                            orderable: false,
                            searchable: false,
                            render: function(data) {
                                return data;
                            }
                        }
                    ],
                    columnDefs: [{
                            responsivePriority: 1,
                            targets: 0
                        },
                        {
                            responsivePriority: 2,
                            targets: 1
                        },
                        {
                            responsivePriority: 3,
                            targets: 2
                        },
                        {
                            responsivePriority: 4,
                            targets: 3
                        },
                        {
                            responsivePriority: 5,
                            targets: 4
                        },
                        {
                            responsivePriority: 6,
                            targets: 5
                        },
                        {
                            responsivePriority: 7,
                            targets: 6
                        },
                        {
                            responsivePriority: 8,
                            targets: 7
                        },
                        {
                            responsivePriority: 9,
                            targets: 8
                        },
                        {
                            responsivePriority: 10,
                            targets: 9
                        }
                    ],
                    pageLength: 50
                });

                // ✅ Final fix: manually trigger layout adjust
                setTimeout(() => {
                    console.log('testing');
                    paymentTable.columns.adjust().responsive.recalc();
                }, 300);

                // Apply Filters
                $('#applyPaymentFilters').click(function() {
                    paymentTable.ajax.reload();
                });

                // Reset Filters
                $('#resetPaymentFilters').click(function() {
                    $('.payment-date-range').val('');
                    $('#payment-party').val('');
                    $('.min-amount, .max-amount').val('');
                    paymentTable.ajax.reload();
                });
            });

            $(document).ready(function() {

                var purchaseTable = $('#purchaseTable').DataTable({
                    processing: true,
                    serverSide: true,
                    responsive: {
                        details: {
                            type: 'inline',
                            target: 'tr',
                            renderer: responsiveRenderer
                        }
                    },
                    ajax: {
                        url: '{{ route('superadmin.purchase.index') }}',
                        data: function(d) {
                            d.date_range = $('.date-range').val();
                            d.party_id = $('#party').val();
                            d.invoice_no = $('.invoice-filter').val();
                            d.status = $('.status-filter').val();
                        }
                    },
                    columns: [{
                            data: 'purchase_id'
                        },
                        {
                            data: 'purchase_date'
                        },
                        {
                            data: 'invoice_no'
                        },
                        {
                            data: 'invoice_date'
                        },
                        {
                            data: 'party'
                        },
                        {
                            data: 'items'
                        },
                        {
                            data: 'sub_total'
                        },
                        {
                            data: 'paid_amount'
                        },
                        {
                            data: 'balance_amount'
                        },
                        {
                            data: 'status'
                        },
                        {
                            data: 'actions',
                            orderable: false,
                            searchable: false
                        }
                    ],
                    columnDefs: [{
                            responsivePriority: 1,
                            targets: 0
                        },
                        {
                            responsivePriority: 2,
                            targets: 1
                        },
                        {
                            responsivePriority: 3,
                            targets: 2
                        },
                        {
                            responsivePriority: 4,
                            targets: 3
                        },
                        {
                            responsivePriority: 5,
                            targets: 4
                        },
                        {
                            responsivePriority: 10001,
                            targets: [5, 6, 7, 8, 9, 10]
                        }
                    ],
                    pageLength: 50
                });

                $(document).on('click', '.credit-note-purchase', function() {
                    $('#creditModal').on('show.bs.modal', function() {
                        $.get("{{ url('/superadmin/creditnotes/next-no') }}", function(res) {
                            $('#creditNoteNo').val(res.credit_note_no);
                        });
                    });
                    $('#creditPartyId').val($(this).data('party_id'));
                    // Get data from button
                    var invoiceNo = $(this).data('invoice');
                    var party = $(this).data('party');
                    // If you want more, like purchase id, you have data-id

                    // Set modal fields
                    $('#creditInvoiceNo').val(invoiceNo);
                    $('#creditPartyId').val($(this).data('party_id'));
                    $('#creditPurchaseId').val($(this).data('id'));

                    $('#creditParty').val(party);

                    // Optional: auto-generate credit note no (you may have ajax for this)
                    // $('#creditNoteNo').val(...);

                    // Clear rest
                    $('#creditAmount').val('');
                    $('#creditReason').val('Return');
                    $('#creditDescription').val('');
                    $('#creditDate').val((new Date()).toISOString().slice(0, 10)); // today

                    // Show modal
                    $('#creditModal').modal('show');
                });

                $(document).on('click', '.edit-purchase', function() {
                    var id = $(this).data('id');
                    var row = $(this).data('row');
                    $('#purchaseForm').data('edit-id', id);
                    $('#purchaseForm').data('edit-row', row);
                    $('#purchaseModal').modal('show');
                    console.log({id});
                });
                
                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });

                // Flatpickr
                flatpickr("#purchaseDate", {
                    dateFormat: "Y-m-d",
                    defaultDate: "today"
                });

                flatpickr("#invoiceDate", {
                    dateFormat: "Y-m-d",
                    defaultDate: "today"
                });

                // Dynamically add/remove item rows
                let itemIdx = 1;

                document.addEventListener('DOMContentLoaded', function() {
                    $(document).on('click', '.remove-item', function() {
                        $(this).closest('.item-row').remove();
                    });
                });

                // Example: Auto-generate invoice number on modal open
                $('#addPurchaseBtn').click(function() {
                    $.get("{{ url('superadmin/purchase/next-invoice-no') }}", function(res) {
                        $('#purchaseForm')[0].reset();
                        $('#invoiceNo').val(res.invoice_no);
                        $('#itemsContainer .item-row:not(:first)').remove();
                        $('#itemsContainer .remove-item').hide();

                        if ($('#purchaseForm').data('edit-id') !== undefined) {
                            $('#purchaseForm').removeData('edit-id');
                        }

                        //Clear file input and preview on modal open
                        $('#purchaseFiles').val('');
                        $('#filePreview').html('');
                        $('#existingFile').empty();

                        $('#purchaseModal').modal('show');
                        initializeItemSelects(); // Important
                    });
                });

                $('#purchaseModal').on('hidden.bs.modal', function() {
                    $('#purchaseFiles').val('');
                    $('#filePreview').html('');
                    $('#existingFile').empty();
                });

                // Recalculate totals when quantity, rate, discount, charges, tds, paid changes
                $(document).on('input', '.quantity, .rate, .discount, #additionalCharges, #tds, #paidAmount',
                    function() {
                        calculateTotals();
                    });

                function calculateTotals() {
                    let subTotal = 0;
                    $('#itemsContainer .item-row').each(function() {
                        let qty = parseFloat($(this).find('.quantity').val()) || 0;
                        let rate = parseFloat($(this).find('.rate').val()) || 0;
                        let disc = parseFloat($(this).find('.discount').val()) || 0;
                        let total = qty * rate;
                        let discountAmount = total * (disc / 100);
                        subTotal += (total - discountAmount);
                    });
                    $('#subTotal').val(subTotal.toFixed(2));
                    let additionalCharges = parseFloat($('#additionalCharges').val()) || 0;
                    let tds = parseFloat($('#tds').val()) || 0;
                    let paid = parseFloat($('#paidAmount').val()) || 0;
                    let totalBeforeTDS = subTotal + additionalCharges;
                    let tdsAmount = totalBeforeTDS * (tds / 100);
                    let totalAmount = totalBeforeTDS - tdsAmount;
                    $('#totalAmount').val(totalAmount.toFixed(2));
                    $('#balanceAmount').val((totalAmount - paid).toFixed(2));
                }

                // Save Purchase (AJAX POST)
                $('#savePurchase').click(function() {
                    if ($('#purchaseForm')[0].checkValidity()) {
                        //let data = $('#purchaseForm').serialize();

                        let formData = new FormData($('#purchaseForm')[0]);

                        let editId = $('#purchaseForm').data('edit-id');
                        let url, method;
                        if (editId) {
                            url = '{{ url('/superadmin/purchasemanagement') }}/' + editId + '/update';
                            method = 'POST';
                        } else {
                            url = '{{ route('superadmin.purchase.store') }}';
                            method = 'POST';
                        }

                        $.ajax({
                            url: url,
                            type: method,
                            data: formData,
                            processData: false,
                            contentType: false,
                            success: function(response) {
                                $('#purchaseModal').modal('hide');
                                $('#purchaseForm')[0].reset();
                                $('#purchaseForm').removeData('edit-id');
                                alert('Purchase saved successfully!');
                                purchaseTable.ajax.reload();
                            },
                            error: function(xhr) {
                                alert('Failed to save: ' + (xhr.responseJSON?.message ||
                                    'Validation Error'));
                            }
                        });

                    } else {
                        $('#purchaseForm')[0].reportValidity();
                    }
                });

                $('#applyFilters').click(function() {
                    purchaseTable.ajax.reload();
                });

                $(document).on('click', '.remove-file', function() {
                    let fileId = $(this).data('id');

                    if (confirm('Are you sure you want to delete this file?')) {
                        let deleteUrl = `{{ route('purchase.deletefile', ':id') }}`.replace(':id', fileId);

                        $.ajax({
                            url: deleteUrl,
                            type: 'DELETE',
                            data: {
                                _token: '{{ csrf_token() }}'
                            },
                            success: function(response) {
                                if (response.success) {
                                    $(`.file-box[data-file-id="${fileId}"]`).remove();
                                } else {
                                    alert('Failed to delete file.');
                                }
                            },
                            error: function() {
                                alert('An error occurred while deleting the file.');
                            }
                        });
                    }
                });
            });

            $(document).on('click', '.view-purchase', function() {
                let id = $(this).data('id');
                $('#viewPurchaseBody').html('Loading...');

                $.get("{{ url('/superadmin/purchasemanagement') }}/" + id, function(data) {
                    let html = `
                        <div>
                            <strong>Purchase ID:</strong> ${data.purchase_id} <br>
                            <strong>Purchase Date:</strong> ${data.purchase_date} <br>
                            <strong>Invoice ID:</strong> ${data.invoice_no} <br>
                            <strong>Invoice Date:</strong> ${data.invoice_date} <br>
                            <strong>Party:</strong> ${data.party?.company || ''} <br>
                            <strong>Total Amount:</strong> ${data.total_amount} <br>
                            <strong>Paid:</strong> ${data.paid_amount} <br>
                            <strong>Status:</strong> ${data.status} <br>
                            <hr>
            
                            <h6>Items</h6>
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Item</th>
                                        <th>Qty</th>
                                        <th>UOM</th>
                                        <th>Rate</th>
                                        <th>Discount %</th>
                                    </tr>
                                </thead>
                                <tbody>
                    `;

                    data.items.forEach(function(item) {
                        html += `<tr>
                            <td>${item.item ? item.item.item_name : ''}</td>
                            <td>${item.quantity}</td>
                            <td>${item.uom}</td>
                            <td>${item.rate}</td>
                            <td>${item.discount}</td>
                        </tr>`;
                    });

                    html += `
                                </tbody>
                            </table>
                            <hr>
                            <strong>Notes:</strong> ${data.notes || ''}<br>
                            <hr>
                    `;

                    // Append files if available
                    if (data.files && data.files.length > 0) {
                        html += `<h6>Attached Files</h6><div class="row g-2">`;

                        data.files.forEach(function(file) {
                            const fileUrl = `/induspro/public/storage/${file.file_path}`;
                            const fileName = file.file_name;

                            html += `
                                <div class="col-md-4">
                                    <a href="${fileUrl}" target="_blank" class="btn btn-sm btn-outline-secondary w-100 mb-1">
                                        ${fileName}
                                    </a>
                                </div>
                            `;
                        });

                        html += `</div>`;
                    }

                    html += `</div>`;
                    $('#viewPurchaseBody').html(html);
                });

                $('#viewPurchaseModal').modal('show');
            });

            $(document).ready(function() {
                var creditTable = $('#creditTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: '{{ route('superadmin.creditnotes.data') }}',
                        data: function(d) {
                            d.date_range = $('.credit-date-range').val();
                            d.party_id = $('#credit-party').val();
                            d.credit_note_no = $('.credit-note-filter').val();
                        }
                    },
                    columns: [{
                            data: 'credit_note_no',
                            title: 'Credit Note No'
                        },
                        {
                            data: 'date',
                            title: 'Date'
                        },
                        {
                            data: 'party',
                            title: 'Party'
                        },
                        {
                            data: 'invoice_no',
                            title: 'Invoice ID'
                        },
                        {
                            data: 'amount',
                            title: 'Amount'
                        },
                        {
                            data: 'reason',
                            title: 'Reason'
                        },
                        {
                            data: 'actions',
                            orderable: false,
                            searchable: false
                        }
                    ]
                });

                $('#applyCreditFilters').click(function() {
                    creditTable.ajax.reload();
                });
                $('#resetCreditFilters').click(function() {
                    $('.credit-date-range').val('');
                    $('#credit-party').val('');
                    $('.credit-note-filter').val('');
                    creditTable.ajax.reload();
                });

                // Optional: Show details in popup
                $(document).on('click', '.view-credit', function() {
                    var id = $(this).data('id');
                    $('#viewPurchaseBody').html('Loading...');
                    $.get("{{ url('/superadmin/creditnotes') }}/" + id, function(data) {
                        let html = `
                <div>
                    <strong>Credit Note No:</strong> ${data.credit_note_no}<br>
                    <strong>Date:</strong> ${data.date}<br>
                    <strong>Party:</strong> ${data.party.company}<br>
                    <strong>Invoice ID:</strong> ${data.invoice_no}<br>
                    <strong>Amount:</strong> ${data.amount}<br>
                    <strong>Reason:</strong> ${data.reason}<br>
                    <strong>Description:</strong> ${data.description || ''}<br>
                </div>
            `;
                        $('#viewPurchaseBody').html(html);
                        $('#viewPurchaseModal').modal('show');
                    });
                });
            });

            $(document).ready(function() {
                // Initialize DataTable for aging report
                var agingTable = $('#agingTable').DataTable({
                    processing: true,
                    serverSide: false,
                    ajax: {
                        url: "{{ route('superadmin.purchase.aging') }}",
                        data: function(d) {
                            if ($('.aging-date').val()) d.as_of_date = $('.aging-date').val();
                            if ($('#pills-aging #party').val()) d.party_id = $('#pills-aging #party').val();
                        }
                    },
                    columns: [{
                            data: 'party',
                            title: 'Party'
                        },
                        {
                            data: 'current',
                            title: 'Current',
                            render: $.fn.dataTable.render.number(',', '.', 2)
                        },
                        {
                            data: '1_30',
                            title: '1-30 Days',
                            render: $.fn.dataTable.render.number(',', '.', 2)
                        },
                        {
                            data: '31_60',
                            title: '31-60 Days',
                            render: $.fn.dataTable.render.number(',', '.', 2)
                        },
                        {
                            data: '61_90',
                            title: '61-90 Days',
                            render: $.fn.dataTable.render.number(',', '.', 2)
                        },
                        {
                            data: 'over_90',
                            title: '>90 Days',
                            render: $.fn.dataTable.render.number(',', '.', 2)
                        },
                        {
                            data: 'total_due',
                            title: 'Total Due',
                            render: $.fn.dataTable.render.number(',', '.', 2)
                        }
                    ]
                });

                $('#applyAgingFilters').click(function() {
                    agingTable.ajax.reload();
                });

                $('#resetAgingFilters').click(function() {
                    $('.aging-date').val('');
                    $('#pills-aging #party').val('');
                    agingTable.ajax.reload();
                });

                // Optionally, set today's date as default
                flatpickr(".aging-date", {
                    dateFormat: "Y-m-d",
                    defaultDate: "today"
                });
            });

            let agingChart; // For keeping chart instance and destroying it before redraw

            function loadAgingChart() {
                // Get filters
                let asOfDate = $('.aging-date').val();
                let partyId = $('#pills-aging #party').val();

                $.get("{{ route('superadmin.purchase.aging') }}", {
                    as_of_date: asOfDate,
                    party_id: partyId
                }, function(response) {
                    // Calculate totals for each bucket across all parties
                    let totalBuckets = {
                        current: 0,
                        '1_30': 0,
                        '31_60': 0,
                        '61_90': 0,
                        over_90: 0
                    };

                    response.data.forEach(row => {
                        totalBuckets.current += Number(row.current);
                        totalBuckets['1_30'] += Number(row['1_30']);
                        totalBuckets['31_60'] += Number(row['31_60']);
                        totalBuckets['61_90'] += Number(row['61_90']);
                        totalBuckets.over_90 += Number(row['over_90']);
                    });

                    // Chart.js
                    const ctx = document.getElementById('agingChart').getContext('2d');
                    // Destroy old chart if present
                    if (agingChart) {
                        agingChart.destroy();
                    }

                    agingChart = new Chart(ctx, {
                        type: 'bar',
                        data: {
                            labels: [
                                'Current', '1-30 Days', '31-60 Days', '61-90 Days', '>90 Days'
                            ],
                            datasets: [{
                                label: 'Pending Amount',
                                data: [
                                    totalBuckets.current,
                                    totalBuckets['1_30'],
                                    totalBuckets['31_60'],
                                    totalBuckets['61_90'],
                                    totalBuckets.over_90
                                ]
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    display: false
                                },
                                title: {
                                    display: true,
                                    text: 'Aging Report - Pending Amounts'
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true
                                }
                            }
                        }
                    });
                });
            }

            // Load on tab show, and when filters change:
            $('#applyAgingFilters').click(loadAgingChart);
            $('.aging-date, #pills-aging #party').on('change', loadAgingChart);
            // Optionally, auto-load on page/tab load:
            $(document).ready(function() {
                loadAgingChart();
            });
        </script>

        <script>
            $(document).ready(function() {
                $('.credit-date-range').daterangepicker({
                    locale: {
                        format: 'YYYY-MM-DD'
                    },
                    autoUpdateInput: false
                });

                $('.credit-date-range').on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' to ' + picker.endDate.format(
                        'YYYY-MM-DD'));
                });

                $('.credit-date-range').on('cancel.daterangepicker', function(ev, picker) {
                    $(this).val('');
                });
            });

            $(document).ready(function() {
                $('.payment-date-range').daterangepicker({
                    locale: {
                        format: 'YYYY-MM-DD'
                    },
                    autoUpdateInput: false
                });

                $('.payment-date-range').on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' to ' + picker.endDate.format(
                        'YYYY-MM-DD'));
                });

                $('.payment-date-range').on('cancel.daterangepicker', function(ev, picker) {
                    $(this).val('');
                });
            });

            $(document).ready(function() {
                $('.date-range').daterangepicker({
                    locale: {
                        format: 'YYYY-MM-DD'
                    },
                    autoUpdateInput: false
                });

                $('.date-range').on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' to ' + picker.endDate.format(
                        'YYYY-MM-DD'));
                });

                $('.date-range').on('cancel.daterangepicker', function(ev, picker) {
                    $(this).val('');
                });
            });
        </script>

        <script>
            $(document).on('click', '.delete-purchase', function() {
                const purchaseId = $(this).data('id');

                if (!confirm('Are you sure you want to delete this purchase?')) return;

                const deleteUrl = '{{ route('superadmin.purchase.destroy', ':id') }}'.replace(':id', purchaseId);

                $.ajax({
                    url: deleteUrl,
                    type: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        alert('Purchase deleted successfully.');
                        location.reload(); // Or remove the row without reloading
                        //purchaseTable.ajax.reload();
                    },
                    error: function(xhr) {
                        console.error(xhr.responseText);
                        alert('Failed to delete. Please try again.');
                    }
                });
            });

            function responsiveRenderer(api, rowIdx, columns) {
                var data = $.map(columns, function(col) {
                    return col.hidden ?
                        '<tr data-dt-row="' + col.rowIndex + '" data-dt-column="' + col.columnIndex + '">' +
                        '<td><strong>' + col.title + ':</strong></td>' +
                        '<td>' + col.data + '</td>' +
                        '</tr>' :
                        '';
                }).join('');

                return data ? $('<table class="table table-bordered"/>').append(data) : false;
            }

            function loadPurchaseTableAgain() {

                console.log('testing 2');
                $('#purchaseTable').DataTable().columns.adjust().responsive.recalc();
                $('#paymentTable').DataTable().columns.adjust().responsive.recalc();
            }

            function loadPaymentTableAgain() {

                console.log('testing 2');
                $('#purchaseTable').DataTable().columns.adjust().responsive.recalc();
                $('#paymentTable').DataTable().columns.adjust().responsive.recalc();
            }
            document.addEventListener('DOMContentLoaded', function() {
                document.getElementById('purchaseFiles').addEventListener('change', function(event) {
                    const files = event.target.files;
                    const previewContainer = document.getElementById('filePreview');
                    previewContainer.innerHTML = ''; // Clear old previews

                    Array.from(files).forEach(file => {
                        const fileType = file.type;
                        const fileURL = URL.createObjectURL(file);

                        const previewWrapper = document.createElement('div');
                        previewWrapper.className = 'col-md-3 mb-2';

                        if (fileType.startsWith('image/')) {
                            // Image preview using blob URL
                            previewWrapper.innerHTML = `
                                <div class="border p-2 rounded text-center">
                                    <a href="${fileURL}" target="_blank" title="${file.name}">
                                        <img src="${fileURL}" class="img-fluid" style="max-height: 150px;" alt="${file.name}">
                                    </a>
                                    <small class="d-block text-truncate mt-1">${file.name}</small>
                                </div>
                            `;
                        } else {
                            // Other file types
                            previewWrapper.innerHTML = `
                                <div class="border p-2 rounded text-center">
                                    <a href="${fileURL}" target="_blank" title="${file.name}">
                                        <i class="fas fa-file-alt fa-2x text-muted"></i>
                                    </a>
                                    <small class="d-block text-truncate mt-1">${file.name}</small>
                                </div>
                            `;
                        }

                        previewContainer.appendChild(previewWrapper);
                    });
                });
            });
        </script>
    @endpush

@endsection
