@extends('layouts.dashboard.superadminapp')

@section('title', 'Purchase Accounts')

@section('styles')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<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" />
<style>
    .section-card {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
    }
    .section-card .card-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        font-weight: 600;
        padding: 0.75rem 1rem;
        border-radius: 0.5rem 0.5rem 0 0 !important;
    }
    .nav-pills .nav-link {
        color: #4e73df;
        font-weight: 500;
        border-radius: 0.35rem;
    }
    .nav-pills .nav-link.active {
        background-color: #4e73df;
        color: #fff;
    }
    .nav-pills .nav-link:hover:not(.active) {
        background-color: #eaecf4;
    }
    .filter-card {
        background: #f8f9fc;
        border-radius: 0.5rem;
        padding: 1rem;
        margin-bottom: 1rem;
    }
    .table th, .table td {
        font-size: 0.85rem;
        padding: 0.5rem !important;
        vertical-align: middle;
        white-space: nowrap;
    }
    .table-responsive {
        overflow-x: auto;
    }
    #purchaseTable, #paymentTable, #creditTable, #debitTable, #agingTable {
        min-width: 900px;
    }
    #itemsTable {
        min-width: 1200px;
    }
    .table-actions .btn {
        padding: 0.2rem 0.4rem;
        font-size: 0.75rem;
        margin: 0 1px;
    }
    .badge {
        font-size: 0.75rem;
    }
    .dt-buttons {
        margin-bottom: 10px;
    }
    .dt-buttons .btn {
        font-size: 0.8rem;
        padding: 0.25rem 0.5rem;
    }
    .select2-container {
        z-index: 9999 !important;
    }
    .select2-container--default .select2-selection--single {
        height: 38px;
        padding: 5px;
        border: 1px solid #d1d3e2;
        border-radius: 0.35rem;
    }
    table input.form-control {
        text-align: right;
    }
    .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;
    }
    #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;
    }
</style>
@endsection

@section('content')
    <!-- Page Heading -->
    <x-layout.page-header title="UEPL | Purchase Accounts" icon="clipboard-list" iconColor="primary" />

    <!-- Alerts -->
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <ul class="mb-0">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <!-- Main Card -->
    <div class="card section-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="fas fa-calculator mr-2"></i>Purchase Accounts</span>
            <button class="btn btn-light btn-sm" id="addPurchaseBtn">
                <i class="fas fa-plus mr-1"></i> Add New Purchase
            </button>
        </div>
        <div class="card-body">
            <!-- Nav Pills -->
            <ul class="nav nav-pills mb-4" id="pills-tab" role="tablist">
                <li class="nav-item">
                    <a class="nav-link active" id="pills-invoice-tab" data-toggle="pill"
                        href="#pills-invoice" role="tab" onclick="loadPurchaseTableAgain()">
                        <i class="fas fa-file-invoice mr-1"></i> Purchase Invoices
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="pills-payment-tab" data-toggle="pill"
                        href="#pills-payment" role="tab" onclick="loadPaymentTableAgain()">
                        <i class="fas fa-money-check-alt mr-1"></i> Vendor Payments
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="pills-credit-tab" data-toggle="pill" href="#pills-credit" role="tab">
                        <i class="fas fa-file-invoice mr-1"></i> Credit Notes
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="pills-debit-tab" data-toggle="pill" href="#pills-debit" role="tab">
                        <i class="fas fa-file-alt mr-1"></i> Debit Notes
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="pills-aging-tab" data-toggle="pill" href="#pills-aging" role="tab">
                        <i class="fas fa-chart-line mr-1"></i> Aging Report
                    </a>
                </li>
            </ul>

                <div class="tab-content" id="pills-tabContent">

                    <!-- Purchase Invoices Tab -->
                    <div class="tab-pane fade show active" id="pills-invoice" 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 date-range" placeholder="Select date range"
                                        readonly>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Party</label>
                                    <select class="form-select" id="invoice-party">
                                        <option value="">Select Party</option>
                                        @foreach ($parties as $party)
                                            <option value="{{ $party->id }}">{{ $party->company }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Invoice ID</label>
                                    <input type="text" class="form-control invoice-filter" placeholder="Invoice ID">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Payment Status</label>
                                    <select class="form-select status-filter">
                                        <option value="">All</option>
                                        <option value="paid">Paid</option>
                                        <option value="partial">Partial</option>
                                        <option value="unpaid">Unpaid</option>
                                    </select>
                                </div>
                                <div class="col-md-3 d-flex align-items-end">
                                    <button class="btn btn-primary me-2" id="applyFilters">Apply Filters</button>
                                    <a href="" class="btn btn-outline-secondary" id="resetFilters">Reset</a>
                                </div>
                            </div>
                        </div>

                        <table id="purchaseTable" class="display nowrap table table-striped" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Purchase ID</th>
                                    <th>Purchase Date</th>
                                    <th>Invoice ID</th>
                                    <th>Invoice Date</th>
                                    <th>Party</th>
                                    <th>Items</th>
                                    <th>Sub Total</th>
                                    <th>Paid Amount</th>
                                    <th>Balance</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                        </table>
                    </div>

                    <!-- Vendor Payments Tab -->
                    <div class="tab-pane fade" 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="d-flex justify-content-end mb-3">
                            <button class="btn btn-primary btn-sm" id="addCreditNoteBtn">
                                <i class="fas fa-plus me-1"></i> Add Credit Note
                            </button>
                        </div>
                        <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="aging-party">
                                        <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>

    @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="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></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-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="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></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-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" id="creditModalTitle">Create Credit Note</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">
                    <form id="creditForm">
                        <input type="hidden" id="creditEditId">
                        <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">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="creditDate" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Invoice No <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="creditInvoiceNo" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Party <span class="text-danger">*</span></label>
                                <select class="form-select" id="creditPartyId" required>
                                    <option value="">Select Party</option>
                                    @foreach ($parties as $party)
                                        <option value="{{ $party->id }}">{{ $party->company }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Amount <span class="text-danger">*</span></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 <span class="text-danger">*</span></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-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="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></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="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></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>
        <!-- Additional plugins (jQuery and Bootstrap already loaded in layout) -->
        <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/papaparse@5.3.2/papaparse.min.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>

        <!-- DataTables Responsive Extension -->
        <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>

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

        <script>
            // Initialize Select2 on all party/filter dropdowns for searchability
            $(document).ready(function() {
                $('#invoice-party, #payment-party, #credit-party, #aging-party, #creditPartyId, #debit-party, #debit_note_party').select2({
                    width: '100%',
                    placeholder: 'Select Party',
                    allowClear: true
                });
                $('#purchase_id').select2({
                    dropdownParent: $('#purchaseModal'),
                    width: '100%',
                    placeholder: 'Select Party',
                    allowClear: true
                });
            });
        </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: $('#invoice-party').val(),
                    invoice_no: $('.invoice-filter').val(),
                    status: $('.status-filter').val()
                });
                window.location = "{{ route('superadmin.purchase.export') }}?" + params;
            });

            // Add Credit Note Button Handler
            $('#addCreditNoteBtn').click(function() {
                // Reset form
                $('#creditForm')[0].reset();
                $('#creditEditId').val('');
                $('#creditModalTitle').text('Add Credit Note');
                $('#creditNoteNo').prop('readonly', true);

                // Fetch next credit note number
                $.get("{{ url('/superadmin/creditnotes/next-no') }}", function(res) {
                    $('#creditNoteNo').val(res.credit_note_no);
                });

                // Set today's date
                $('#creditDate').val(new Date().toISOString().slice(0, 10));

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

            // Edit Credit Note Handler
            $(document).on('click', '.edit-credit', function() {
                let id = $(this).data('id');

                $.get("{{ url('/superadmin/creditnotes') }}/" + id + "/edit", function(res) {
                    if (res.success) {
                        let data = res.data;
                        $('#creditEditId').val(data.id);
                        $('#creditNoteNo').val(data.credit_note_no);
                        $('#creditNoteNo').prop('readonly', true);
                        $('#creditDate').val(data.date);
                        $('#creditInvoiceNo').val(data.invoice_no);
                        $('#creditPartyId').val(data.party_id);
                        $('#creditAmount').val(data.amount);
                        $('#creditReason').val(data.reason);
                        $('#creditDescription').val(data.description || '');
                        $('#creditModalTitle').text('Edit Credit Note');

                        $('#creditModal').modal('show');
                    }
                }).fail(function(xhr) {
                    alert('Failed to load credit note: ' + (xhr.responseJSON?.message || 'Unknown error'));
                });
            });

            // Delete Credit Note Handler
            $(document).on('click', '.delete-credit', function() {
                if (!confirm('Are you sure you want to delete this credit note?')) return;

                let id = $(this).data('id');

                $.ajax({
                    url: "{{ url('/superadmin/creditnotes') }}/" + id,
                    type: 'DELETE',
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    success: function(res) {
                        if (res.success) {
                            alert('Credit Note deleted successfully');
                            $('#creditTable').DataTable().ajax.reload();
                        }
                    },
                    error: function(xhr) {
                        alert('Failed to delete: ' + (xhr.responseJSON?.message || 'Unknown error'));
                    }
                });
            });

            // Save Credit Note (Create or Update)
            $('#saveCreditNote').click(function() {
                let editId = $('#creditEditId').val();
                let isEdit = editId && editId !== '';

                let data = {
                    credit_note_no: $('#creditNoteNo').val(),
                    date: $('#creditDate').val(),
                    invoice_no: $('#creditInvoiceNo').val(),
                    party_id: $('#creditPartyId').val(),
                    amount: $('#creditAmount').val(),
                    reason: $('#creditReason').val(),
                    description: $('#creditDescription').val(),
                    _token: $('meta[name="csrf-token"]').attr('content')
                };

                let url = isEdit
                    ? "{{ url('/superadmin/creditnotes') }}/" + editId
                    : "{{ url('/superadmin/creditnotes') }}";
                let method = isEdit ? 'PUT' : 'POST';

                $.ajax({
                    url: url,
                    type: method,
                    data: data,
                    success: function(res) {
                        alert(isEdit ? 'Credit Note updated successfully!' : 'Credit Note created successfully!');
                        $('#creditModal').modal('hide');
                        $('#creditTable').DataTable().ajax.reload();
                    },
                    error: function(xhr) {
                        alert('Failed: ' + (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 = $('#invoice-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() {
                    // Reset form
                    $('#creditForm')[0].reset();
                    $('#creditEditId').val('');
                    $('#creditModalTitle').text('Create Credit Note');

                    // Fetch next credit note number
                    $.get("{{ url('/superadmin/creditnotes/next-no') }}", function(res) {
                        $('#creditNoteNo').val(res.credit_note_no);
                    });

                    // Get data from button
                    var invoiceNo = $(this).data('invoice');
                    var party = $(this).data('party');
                    var partyId = $(this).data('party_id');

                    // Set modal fields
                    $('#creditInvoiceNo').val(invoiceNo);
                    $('#creditPartyId').val(partyId);
                    if ($('#creditPartyId').hasClass('select2-hidden-accessible')) {
                        $('#creditPartyId').trigger('change');
                    }
                    $('#creditPurchaseId').val($(this).data('id'));

                    // 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 ($('#aging-party').val()) d.party_id = $('#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('');
                    $('#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 = $('#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>

        <script>
            // ==================== AUTO-FILTER: Event listeners on filter changes ====================
            $(document).ready(function() {
                // Debounce helper to avoid too many AJAX calls
                var filterTimeout;
                function debounceReload(table) {
                    clearTimeout(filterTimeout);
                    filterTimeout = setTimeout(function() {
                        if (table && table.ajax) {
                            table.ajax.reload();
                        }
                    }, 500);
                }

                // Purchase Invoice tab filters
                $('.date-range').on('apply.daterangepicker cancel.daterangepicker', function() {
                    var tbl = $('#purchaseTable').DataTable();
                    debounceReload(tbl);
                });
                $(document).on('change', '#invoice-party, .status-filter', function() {
                    var tbl = $('#purchaseTable').DataTable();
                    debounceReload(tbl);
                });
                $(document).on('input', '.invoice-filter', function() {
                    var tbl = $('#purchaseTable').DataTable();
                    debounceReload(tbl);
                });

                // Vendor Payments tab filters
                $('.payment-date-range').on('apply.daterangepicker cancel.daterangepicker', function() {
                    var tbl = $('#paymentTable').DataTable();
                    debounceReload(tbl);
                });
                $(document).on('change', '#payment-party', function() {
                    var tbl = $('#paymentTable').DataTable();
                    debounceReload(tbl);
                });
                $(document).on('input', '.min-amount, .max-amount', function() {
                    var tbl = $('#paymentTable').DataTable();
                    debounceReload(tbl);
                });

                // Credit Notes tab filters
                $('.credit-date-range').on('apply.daterangepicker cancel.daterangepicker', function() {
                    var tbl = $('#creditTable').DataTable();
                    debounceReload(tbl);
                });
                $(document).on('change', '#credit-party', function() {
                    var tbl = $('#creditTable').DataTable();
                    debounceReload(tbl);
                });
                $(document).on('input', '.credit-note-filter', function() {
                    var tbl = $('#creditTable').DataTable();
                    debounceReload(tbl);
                });

                // Debit Notes tab filters
                $('.debit-date-range').on('apply.daterangepicker cancel.daterangepicker', function() {
                    var tbl = $('#debitTable').DataTable();
                    debounceReload(tbl);
                });
                $(document).on('change', '#debit-party', function() {
                    var tbl = $('#debitTable').DataTable();
                    debounceReload(tbl);
                });
                $(document).on('input', '.debit-note-filter', function() {
                    var tbl = $('#debitTable').DataTable();
                    debounceReload(tbl);
                });

                // Aging Report tab filters
                $(document).on('change', '#aging-party', function() {
                    var tbl = $('#agingTable').DataTable();
                    debounceReload(tbl);
                    loadAgingChart();
                });
                $('.aging-date').on('change', function() {
                    var tbl = $('#agingTable').DataTable();
                    debounceReload(tbl);
                    loadAgingChart();
                });
            });
        </script>
    @endpush

@endsection
