@extends('layouts.dashboard.managerapp')

@section('title', 'Purchase Management System')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
@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;
        }
    </style>
    <!-- Page Heading -->
    <x-layout.page-header title="UEPL | Purchase Management System" icon="clipboard-list" iconColor="primary" />
    <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-invoice-tab" data-bs-toggle="pill"
                            data-bs-target="#pills-invoice" type="button" role="tab">Purchase Invoices</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="pills-payment-tab" data-bs-toggle="pill"
                            data-bs-target="#pills-payment" type="button" role="tab">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-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">
                    <!-- 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">
                                </div>
                                <div class="col-md-2">
                                    <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-2">
                                    <label class="form-label">Invoice No</label>
                                    <input type="text" class="form-control invoice-filter" placeholder="Invoice No">
                                </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>

                        <div class="mb-3">
                            <button class="btn btn-success btn-sm me-2" id="importDataBtn">
                                <i class="fas fa-file-import me-1"></i> Bulk Import
                            </button>
                            <button class="btn btn-info btn-sm" id="exportDataBtn">
                                <i class="fas fa-file-export me-1"></i> Export Data
                            </button>
                        </div>

                        <table id="purchaseTable" class="table table-striped table-bordered" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Invoice No</th>
                                    <th>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">
                                </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="table table-striped table-bordered" style="width:100%">
                            <thead>
                                <tr>
                                    <th>Payment ID</th>
                                    <th>Date</th>
                                    <th>Party</th>
                                    <th>Invoice No</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">
                                </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 No</th>
                                    <th>Amount</th>
                                    <th>Reason</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Data will be loaded here -->
                            </tbody>
                        </table>
                    </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>

    <!-- Add Purchase Modal -->
    <div class="modal fade" id="purchaseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Purchase</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">X</button>
                </div>
                <div class="modal-body">
                    <form id="purchaseForm">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Invoice No</label>
                                <input type="text" class="form-control" name="invoice_no" id="invoiceNo" readonly>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Date</label>
                                <input type="text" class="form-control" name="date" id="purchaseDate" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Party</label>
                                <select class="form-select" name="party_id" 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-6">
                                <label class="form-label">Payment Terms</label>
                                <select class="form-select" name="payment_terms" id="paymentTerms">
                                    <option value="0">Due on Receipt</option>
                                    <option value="7">Net 7 Days</option>
                                    <option value="15">Net 15 Days</option>
                                    <option value="30">Net 30 Days</option>
                                </select>
                            </div>
                        </div>

                        <div class="card mb-3">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <span>Items</span>
                                <button type="button" class="btn btn-sm btn-primary" id="addItemBtn">
                                    <i class="fas fa-plus me-1"></i> Add Item
                                </button>
                            </div>
                            <div class="card-body" id="itemsContainer">
                                <!-- Item row(s) -->
                                <div class="item-row row g-2 mb-2">
                                    <div class="col-md-4">
                                        <label class="form-label">Item</label>
                                        <select class="form-select item-select" name="items[0][item_id]" required>
                                            <option value="">Select Item</option>
                                            @foreach ($items as $item)
                                                <option value="{{ $item->id }}">{{ $item->item_name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Quantity</label>
                                        <input type="number" class="form-control quantity" name="items[0][quantity]"
                                            min="1" value="1" required>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">UOM</label>
                                        <select class="form-select uom" name="items[0][uom]" required>
                                            <option value="PCS">PCS</option>
                                            <option value="KG">KG</option>
                                            <option value="LTR">LTR</option>
                                            <option value="MTR">MTR</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Rate</label>
                                        <input type="number" class="form-control rate" name="items[0][rate]"
                                            min="0" step="0.01" required>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label">Discount %</label>
                                        <input type="number" class="form-control discount" name="items[0][discount]"
                                            min="0" max="100" value="0">
                                    </div>
                                    <div class="col-md-12 text-end mt-1">
                                        <button type="button" class="btn btn-outline-danger btn-sm remove-item"
                                            style="display:none;">Remove</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Additional Charges</label>
                                <input type="number" class="form-control" name="additional_charges"
                                    id="additionalCharges" min="0" step="0.01" value="0">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">TDS %</label>
                                <input type="number" class="form-control" name="tds" id="tds" min="0"
                                    max="100" value="0">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Sub Total</label>
                                <input type="text" class="form-control" id="subTotal" readonly value="0.00">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Total Amount</label>
                                <input type="text" class="form-control" id="totalAmount" readonly value="0.00">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Paid Amount</label>
                                <input type="number" class="form-control" name="paid_amount" id="paidAmount"
                                    min="0" step="0.01" value="0">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Balance Amount</label>
                                <input type="text" class="form-control" id="balanceAmount" readonly value="0.00">
                            </div>
                        </div>

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

                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" id="notes" 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="savePurchase">Save Purchase</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 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 No</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 No</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>

    @push('scripts')
        <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>
        <script>
            $('#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('manager.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('/manager/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,
                    ajax: {
                        url: '{{ route('manager.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: 'date',
                            title: 'Date'
                        },
                        {
                            data: 'party',
                            title: 'Party'
                        },
                        {
                            data: 'invoice_no',
                            title: 'Invoice No'
                        },
                        {
                            data: 'paid_amount',
                            title: 'Amount'
                        },
                        {
                            data: 'payment_mode',
                            title: 'Payment Mode'
                        },
                        {
                            data: 'reference',
                            title: 'Reference'
                        },
                        {
                            data: 'actions',
                            orderable: false,
                            searchable: false,
                            render: function(data, type, row) {
                                return data;
                            }
                        }
                    ]
                });

                // 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).on('click', '.view-payment', function() {
                var id = $(this).data('id');
                $('#viewPurchaseBody').html('Loading...');
                $.get("{{ url('/manager/purchasemanagement') }}/" + id, function(data) {
                    let html = `
            <div>
                <strong>Invoice No:</strong> ${data.invoice_no} <br>
                <strong>Date:</strong> ${data.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>Balance:</strong> ${data.balance_amount} <br>
                <strong>Status:</strong> ${data.status} <br>
                <strong>Payment Mode:</strong> ${data.payment_mode || ''} <br>
                <strong>Reference:</strong> ${data.reference || ''} <br>
                <strong>Notes:</strong> ${data.notes || ''} <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>
            </div>
        `;
                    $('#viewPurchaseBody').html(html);
                    $('#viewPurchaseModal').modal('show');
                });
            });


            $(document).ready(function() {
                $(document).on('click', '.credit-note-purchase', function() {
                    $('#creditModal').on('show.bs.modal', function() {
                        $.get("{{ url('/manager/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');
                    // Fetch existing purchase data
                    $.get("{{ url('/manager/purchasemanagement') }}/" + id + "/edit", function(data) {
                        // Reset form and fill with data
                        $('#purchaseForm')[0].reset();
                        $('#invoiceNo').val(data.invoice_no);
                        $('#purchaseDate').val(data.date);
                        $('#purchaseModal select[name="party_id"]').val(data.party_id);
                        $('#purchaseModal select[name="payment_mode"]').val(data.payment_mode);

                        // Remove old item rows except the first
                        $('#itemsContainer .item-row:not(:first)').remove();
                        let firstRow = $('#itemsContainer .item-row').first();
                        // Fill the first item
                        if (data.items.length > 0) {
                            let item = data.items[0];
                            firstRow.find('.item-select').val(item.item_id);
                            firstRow.find('.quantity').val(item.quantity);
                            firstRow.find('.uom').val(item.uom);
                            firstRow.find('.rate').val(item.rate);
                            firstRow.find('.discount').val(item.discount);
                        }
                        // Add more item rows if needed
                        for (let i = 1; i < data.items.length; i++) {
                            $('#addItemBtn').trigger('click');
                            let lastRow = $('#itemsContainer .item-row').last();
                            let item = data.items[i];
                            lastRow.find('.item-select').val(item.item_id);
                            lastRow.find('.quantity').val(item.quantity);
                            lastRow.find('.uom').val(item.uom);
                            lastRow.find('.rate').val(item.rate);
                            lastRow.find('.discount').val(item.discount);
                        }

                        $('#additionalCharges').val(data.additional_charges);
                        $('#tds').val(data.tds);
                        $('#subTotal').val(data.sub_total);
                        $('#totalAmount').val(data.total_amount);
                        $('#paidAmount').val(data.paid_amount);
                        $('#balanceAmount').val(data.balance_amount);
                        $('#notes').val(data.notes);
                        $('#paymentReference').val(data.reference);
                        $('#paymentReason').val(data.remarks);

                        // Set hidden field for edit (or track via JS variable)
                        $('#purchaseForm').data('edit-id', data.id);

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

                $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
                // Flatpickr
                flatpickr("#purchaseDate", {
                    dateFormat: "Y-m-d",
                    defaultDate: "today"
                });

                // Dynamically add/remove item rows
                let itemIdx = 1;
                $('#addItemBtn').click(function(e) {
                    e.preventDefault();
                    let html = `
        <div class="item-row row g-2 mb-2">
            <div class="col-md-4">
                <select class="form-select item-select" name="items[${itemIdx}][item_id]" required>
                    <option value="">Select Item</option>
                    @foreach ($items as $item)
                        <option value="{{ $item->id }}">{{ $item->item_name }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-2">
                <input type="number" class="form-control quantity" name="items[${itemIdx}][quantity]" min="1" value="1" required>
            </div>
            <div class="col-md-2">
                <select class="form-select uom" name="items[${itemIdx}][uom]" required>
                    <option value="PCS">PCS</option>
                    <option value="KG">KG</option>
                    <option value="LTR">LTR</option>
                    <option value="MTR">MTR</option>
                </select>
            </div>
            <div class="col-md-2">
                <input type="number" class="form-control rate" name="items[${itemIdx}][rate]" min="0" step="0.01" required>
            </div>
            <div class="col-md-2">
                <input type="number" class="form-control discount" name="items[${itemIdx}][discount]" min="0" max="100" value="0">
            </div>
            <div class="col-md-12 text-end mt-1">
                <button type="button" class="btn btn-outline-danger btn-sm remove-item">Remove</button>
            </div>
        </div>
        `;
                    $('#itemsContainer').append(html);
                    itemIdx++;
                    // Show remove button
                    $('#itemsContainer .remove-item').show();
                });

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

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

                // 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 editId = $('#purchaseForm').data('edit-id');
                        let url, method;
                        if (editId) {
                            url = '{{ url('/manager/purchasemanagement') }}/' + editId + '/update';
                            method = 'PUT';
                        } else {
                            url = '{{ route('manager.purchase.store') }}';
                            method = 'POST';
                        }

                        $.ajax({
                            url: url,
                            type: method,
                            data: data,
                            success: function(response) {
                                $('#purchaseModal').modal('hide');
                                $('#purchaseForm')[0].reset();
                                $('#purchaseForm').removeData('edit-id');
                                alert('Purchase saved successfully!');
                                $('#purchaseTable').DataTable().ajax.reload();
                            },
                            error: function(xhr) {
                                alert('Failed to save: ' + (xhr.responseJSON && xhr.responseJSON
                                    .message ? xhr.responseJSON.message : 'Validation Error'
                                ));
                            }
                        });
                    } else {
                        $('#purchaseForm')[0].reportValidity();
                    }
                });
                $('#applyFilters').click(function() {
                    $('#purchaseTable').DataTable().ajax.reload();
                });
                $('#purchaseTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: '{{ route('manager.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: 'invoice_no'
                        },
                        {
                            data: 'date'
                        },
                        {
                            data: 'party'
                        },
                        {
                            data: 'items'
                        },
                        {
                            data: 'sub_total'
                        },
                        {
                            data: 'paid_amount'
                        },
                        {
                            data: 'balance_amount'
                        },
                        {
                            data: 'status'
                        },
                        {
                            data: 'actions',
                            title: 'Actions',
                            orderable: false,
                            searchable: false
                        }
                    ]
                });
            });
            $(document).on('click', '.view-purchase', function() {
                var id = $(this).data('id');
                $('#viewPurchaseBody').html('Loading...');
                $.get("{{ url('/manager/purchasemanagement') }}/" + id, function(data) {
                    // Build the HTML string for details (customize as you wish!)
                    let html = `
            <div>
                <strong>Invoice No:</strong> ${data.invoice_no} <br>
                <strong>Date:</strong> ${data.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 || ''}
            </div>
        `;
                    $('#viewPurchaseBody').html(html);
                });
                $('#viewPurchaseModal').modal('show');
            });
            $(document).ready(function() {
                var creditTable = $('#creditTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: '{{ route('manager.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 No'
                        },
                        {
                            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('/manager/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 No:</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('manager.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('manager.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>
    @endpush

@endsection
