<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ $documentTitle }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <style>
        :root {
            --primary-color: {{ $themeColor }};
            --primary-light: {{ $themeLight }};
            --primary-dark: {{ $themeDark }};
            --secondary-color: #f8f9fa;
            --border-color: #dee2e6;
            --success-color: #28a745;
            --danger-color: #dc3545;
        }

        body {
            background-color: #f5f7fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 0.92rem;
        }

        .bg-primary-custom {
            background-color: var(--primary-color) !important;
        }

        .btn-primary-custom {
            background-color: var(--primary-color);
            border-color: var(--primary-dark);
            color: white;
        }

        .btn-primary-custom:hover {
            background-color: var(--primary-dark);
            border-color: var(--primary-dark);
            color: white;
        }

        .header-card {
            border-top: 3px solid var(--primary-color);
            border-radius: 0.75rem;
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .card-header-custom {
            border-radius: 0.75rem 0.75rem 0 0 !important;
            padding: 1rem;
            background: linear-gradient(to right, var(--primary-color), var(--primary-light));
        }

        .table-header {
            background-color: var(--primary-light);
            color: white;
        }

        .totals-panel {
            background-color: var(--secondary-color);
            border: 1px solid var(--border-color);
            border-radius: 0.5rem;
            padding: 12px;
        }

        .back-link {
            display: inline-block;
            margin-bottom: 15px;
            color: var(--primary-color);
            font-weight: 600;
        }

        .form-label {
            font-weight: 600;
            margin-bottom: 0.4rem;
            color: #495057;
            font-size: 0.9rem;
        }

        .form-control, .form-select {
            border-radius: 0.4rem;
            padding: 0.65rem;
            border: 1px solid var(--border-color);
            font-size: 0.9rem;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(1, 140, 163, 0.25);
        }

        .section-header {
            font-weight: bold;
            font-size: 1.05rem;
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 0.6rem;
            margin-bottom: 1.2rem;
            color: var(--primary-color);
        }

        .action-icon {
            color: var(--danger-color);
            cursor: pointer;
            font-size: 1.1rem;
            transition: all 0.2s;
        }

        .action-icon:hover {
            color: #bd2130;
            transform: scale(1.1);
        }

        .compact-table th, .compact-table td {
            padding: 0.6rem 0.4rem;
            vertical-align: middle;
            font-size: 0.88rem;
        }

        .compact-table thead th {
            background-color: var(--primary-light);
            color: white;
            font-weight: 600;
            position: sticky;
            top: 0;
            font-size: 0.9rem;
        }

        .add-line-btn {
            margin-top: 0.8rem;
            padding: 0.4rem 0.8rem;
            font-size: 0.9rem;
        }

        .table-hover tbody tr:hover {
            background-color: rgba(1, 140, 163, 0.05);
        }

        .alert-container {
            position: fixed;
            top: 140px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1050;
            width: 100%;
            max-width: 550px;
            padding: 0 12px;
        }

        .scrollable-section {
            max-height: 450px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 0.4rem;
            padding: 12px;
            background: white;
            margin-bottom: 15px;
        }

        .line-item-row td {
            padding: 8px 6px;
        }

        .form-control-sm {
            padding: 0.45rem;
            font-size: 0.85rem;
        }

        .form-select-sm {
            padding: 0.45rem 2rem 0.45rem 0.65rem;
            font-size: 0.85rem;
        }

        .fixed-header {
            position: sticky;
            top: 0;
            background: white;
            z-index: 10;
            padding-bottom: 12px;
            margin-bottom: 8px;
        }

        .table-wrapper {
            overflow-x: auto;
        }

        .settings-icon {
            position: absolute;
            top: 18px;
            right: 18px;
            font-size: 1.1rem;
            color: white;
            cursor: pointer;
            z-index: 100;
        }

        .theme-quotation {
            --primary-color: #018ca3;
            --primary-light: #5ab8cc;
            --primary-dark: #006175;
        }

        .theme-sales_order {
            --primary-color: #28a745;
            --primary-light: #5cb85c;
            --primary-dark: #1e7e34;
        }

        .theme-invoice {
            --primary-color: #001f3f;
            --primary-light: #5D8AA8;
            --primary-dark: #001a33;
        }

        .theme-credit_note {
            --primary-color: #dc3545;
            --primary-light: #e4606d;
            --primary-dark: #bd2130;
        }

        .theme-debit_note {
            --primary-color: #87CEEB;
            --primary-light: #b3e0ff;
            --primary-dark: #5bc0de;
        }

        .theme-receipt {
            --primary-color: #6f42c1;
            --primary-light: #9d7bd9;
            --primary-dark: #563d7c;
        }

        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: var(--primary-color);
        }

        .select2-container--default .select2-results__option[aria-selected=true] {
            background-color: var(--primary-light);
        }

        /* Compact textareas */
        .compact-table textarea.form-control-sm {
            height: 36px;
            resize: vertical;
            min-height: 36px;
        }

        /* Smaller number inputs */
        input[type="number"].form-control-sm {
            padding: 0.4rem;
        }

        /* Updated column widths */
        .compact-table th:nth-child(1), .compact-table td:nth-child(1) { width: 3%; }        /* # */
        .compact-table th:nth-child(2), .compact-table td:nth-child(2) { width: 6%; }        /* Module */
        .compact-table th:nth-child(3), .compact-table td:nth-child(3) { width: 6%; }        /* HS Code */
        .compact-table th:nth-child(4), .compact-table td:nth-child(4) { width: 8%; }        /* Account */
        .compact-table th:nth-child(5), .compact-table td:nth-child(5) { width: 8%; }        /* Acc Description */
        .compact-table th:nth-child(6), .compact-table td:nth-child(6) { width: 11%; }       /* Description */
        .compact-table th:nth-child(7), .compact-table td:nth-child(7) { width: 7%; }        /* Warehouse */
        .compact-table th:nth-child(8), .compact-table td:nth-child(8) { width: 4%; }        /* Available */
        .compact-table th:nth-child(9), .compact-table td:nth-child(9) { width: 6%; }        /* Quantity */
        .compact-table th:nth-child(10), .compact-table td:nth-child(10) { width: 7.5%; }      /* UOM */
        .compact-table th:nth-child(11), .compact-table td:nth-child(11) { width: 5%; }      /* Confirm Qty */
        .compact-table th:nth-child(12), .compact-table td:nth-child(12) { width: 7%; }      /* Price */
        .compact-table th:nth-child(13), .compact-table td:nth-child(13) { width: 7%; }      /* Tax Type */
        .compact-table th:nth-child(14), .compact-table td:nth-child(14) { width: 5%; }      /* Tax Rate */
        .compact-table th:nth-child(15), .compact-table td:nth-child(15) { width: 5%; }      /* Disc % */
        .compact-table th:nth-child(16), .compact-table td:nth-child(16) { width: 6%; }      /* Line Tax */
        .compact-table th:nth-child(17), .compact-table td:nth-child(17) { width: 7%; }      /* Line Total */
        .compact-table th:nth-child(18), .compact-table td:nth-child(18) { width: 3%; }      /* Action */

        /* Responsive adjustments */
        @media (max-width: 1700px) {
            .compact-table th:nth-child(6), .compact-table td:nth-child(6) { width: 10%; }   /* Description */
        }
    </style>
</head>
<body class="theme-{{ str_replace(' ', '_', strtolower($documentTitle)) }}">
    <div class="container-fluid py-3">
         <a href="{{ route('home') }}" class="back-link">
            <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
        </a>

        <div class="card header-card">
            <div class="card-header bg-primary-custom text-white card-header-custom">
                <h4 class="mb-0"><i class="fas fa-file-invoice me-2"></i> New {{ $documentTitle }}</h4>
                <div class="text-light mt-1 fw-light" style="font-size: 0.85rem;">
                    Document #: {{ $documentNumber }}
                </div>
                <i class="fas fa-cog settings-icon" data-bs-toggle="modal" data-bs-target="#settingsModal"></i>
            </div>

            <div class="card-body">
                <form method="POST" action="{{ route('documents.store', $type) }}" id="documentForm">
                    @csrf
                    <input type="hidden" name="document_number" value="{{ $documentNumber }}">
                    <input type="hidden" name="pricing_type" id="pricingType" value="{{ $pricingType }}">

                    <div class="row mb-3">
                        <!-- Customer Information -->
                        <div class="col-md-6">
                            <div class="section-header mb-3">
                                <i class="fas fa-user me-2"></i> Customer Information
                            </div>

                            <div class="mb-2">
                                <label class="form-label">Customer <span class="text-danger">*</span></label>
                                <select name="customer_account_id" class="form-select" id="customerSelect" required>
                                    <option value="">Select Customer</option>
                                    @foreach($customers as $customer)
                                        <option value="{{ $customer->id }}"
                                                data-contact="{{ $customer->contact_person }}"
                                                data-address="{{ $customer->address }}"
                                                data-phone="{{ $customer->contact_1 }}"
                                                data-vat="{{ $customer->vat }}"
                                                data-email="{{ $customer->email }}"
                                                data-tin="{{ $customer->tin }}"
                                                data-city="{{ $customer->city }}"
                                                data-province="{{ $customer->province }}">
                                            {{ $customer->customer_code }} - {{ $customer->customer_account }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="mb-2">
                                <label class="form-label">Contact Person</label>
                                <input type="text" name="contact_person" id="contactPerson" class="form-control" readonly>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">Address</label>
                                    <input type="text" id="customerAddress" class="form-control" readonly>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">Telephone</label>
                                    <input type="text" id="customerPhone" class="form-control" readonly>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">VAT No</label>
                                    <input type="text" id="customerVat" class="form-control" readonly>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">Email</label>
                                    <input type="text" id="customerEmail" class="form-control" readonly>
                                </div>

                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">TIN No</label>
                                    <input type="text" id="customerTin" class="form-control" readonly>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">Order Number</label>
                                    <input type="text" name="order_number" class="form-control" value="{{ old('order_number') }}">
                                </div>
                            </div>

                            <!-- Add this in the customer information section -->
                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <label class="form-label">Order Date <span class="text-danger">*</span></label>
                                        <input type="date" name="document_date" class="form-control"
                                            value="{{ old('document_date', now()->format('Y-m-d')) }}" required>
                                    </div>
                                    <div class="col-md-6 mb-2">
                                        <label class="form-label">Delivery Date</label>
                                        <input type="date" name="delivery_date" class="form-control"
                                            value="{{ old('delivery_date', now()->format('Y-m-d')) }}">
                                    </div>
                                </div>

                                @if($type === 'invoice')
                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <label class="form-label">Due Date <span class="text-danger">*</span></label>
                                        <input type="date" name="due_date" class="form-control"
                                            value="{{ old('due_date', now()->addDays(30)->format('Y-m-d')) }}" required>
                                    </div>
                                </div>
                                 @endif

                                 @if($type === 'credit_note')
                                 <div class="row">
                                     <div class="col-md-12 mb-2">
                                         <label class="form-label">Apply to Invoice (optional)</label>
                                         <select name="apply_invoice_id" class="form-select" id="applyInvoiceSelect">
                                             <option value="">Select Invoice</option>
                                         </select>
                                         <div class="form-text">This reduces the invoice outstanding balance without editing the invoice.</div>
                                     </div>
                                 </div>
                                 @endif

                            <div class="mb-2">
                                <label class="form-label">Terms & Conditions</label>
                                <textarea name="special_instructions" class="form-control" rows="2">{{ old('special_instructions') }} Please package items carefully and include invoice in package.</textarea>
                            </div>
                        </div>

                        <!-- Document Information -->
                        <div class="col-md-6">
                            <div class="section-header mb-3">
                                <i class="fas fa-info-circle me-2"></i> Document Information
                            </div>

                            <div class="mb-2">
                                <label class="form-label">Document Number</label>
                                <input type="text" class="form-control" value="{{ $documentNumber }}" readonly>
                            </div>

                            <div class="mb-2">
                                <label class="form-label">Project</label>
                                <select name="project_id" class="form-select">
                                    <option value="">Select Project</option>
                                    @foreach($projects as $project)
                                        <option value="{{ $project->id }}">{{ $project->code }}</option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">Currency</label>
                                    <select name="currency_code" class="form-select">
                                        @foreach($currencies as $currency)
                                            <option value="{{ $currency->code }}"
                                                {{ $currency->code === 'USD' ? 'selected' : '' }}>
                                                {{ $currency->code }} - {{ $currency->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">Sales Representative</label>
                                    <select name="sales_representative_id" class="form-select">
                                        @foreach($salesReps as $rep)
                                            <option value="{{ $rep->id }}">{{ $rep->code }} - {{ $rep->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            @if($showNegativeOption)
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" name="allow_negative"
                                           id="allowNegative" value="1">
                                    <label class="form-check-label" for="allowNegative">
                                        Allow Negative Stock
                                    </label>
                                </div>
                            @endif
                        </div>
                    </div>

                    <!-- Line Items -->
                    <div class="scrollable-section">
                        <div class="fixed-header">
                            <div class="section-header d-flex justify-content-between align-items-center">
                                <div>
                                    <i class="fas fa-list me-2"></i> Line Items
                                </div>
                                <button type="button" class="btn btn-primary-custom btn-sm add-line-btn">
                                    <i class="fas fa-plus me-1"></i> Add Line
                                </button>
                            </div>
                        </div>

                        <div class="table-wrapper">
                            <table class="table table-bordered compact-table table-hover" id="lineItemsTable">
                                <thead class="table-header">
                                    <tr>
                                        <th width="3%">#</th>
                                        <th width="8%">Module</th>
                                        <th width="8%">HS Code</th>
                                        <th width="12%" id="itemAccountHeader">Item</th>
                                        <th width="10%" id="descriptionHeader">Item Description</th>
                                        <th width="10%">Description</th>
                                        <th width="8%">Warehouse</th>
                                        <th width="6%">Available</th>
                                        <th width="6%">Quantity</th>
                                        <th width="5%">UOM</th>
                                        <th width="5%">Confirm Qty</th>
                                        <th width="7%" id="priceHeader">Price ({{ $pricingType === 'inclusive' ? 'incl' : 'excl' }})</th>
                                        <th width="7%">Tax Type</th>
                                        <th width="5%">Tax Rate</th>
                                        <th width="5%">Disc %</th>
                                        <th width="6%">Line Tax</th>
                                        <th width="7%">Line Total</th>
                                        <th width="3%"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Lines will be added dynamically -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Totals Panel -->
                    <div class="row justify-content-end mt-3">
                        <div class="col-md-5">
                            <div class="totals-panel">
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Exclusive Total:</span>
                                    <span id="exclTotal" class="fw-bold">$0.00</span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Tax:</span>
                                    <span id="taxTotal" class="fw-bold">$0.00</span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Discount:</span>
                                    <span id="discountTotal" class="fw-bold">$0.00</span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span>Inclusive Total:</span>
                                    <span id="inclTotal" class="fw-bold">$0.00</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="d-flex justify-content-between mt-3 pt-3 border-top">
                        <a href="{{ route('home') }}" class="btn btn-outline-secondary">
                            <i class="fas fa-times me-2"></i> Cancel
                        </a>
                        <button type="submit" class="btn btn-success" id="processBtn">
                            <i class="fas fa-cogs me-2"></i> Process
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Settings Modal -->
    <div class="modal fade" id="settingsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary-custom text-white">
                    <h5 class="modal-title"><i class="fas fa-cog me-2"></i> Document Settings</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Document Prefix</label>
                        <input type="text" id="docPrefix" class="form-control" value="{{ substr($documentNumber, 0, strspn($documentNumber, 'A-Z')) }}">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Starting Number</label>
                        <input type="number" id="startNumber" class="form-control" value="{{ substr($documentNumber, strspn($documentNumber, 'A-Z')) }}" min="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Pricing Type</label>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="pricingType" id="pricingExclusive" value="exclusive" {{ $pricingType === 'exclusive' ? 'checked' : '' }}>
                            <label class="form-check-label" for="pricingExclusive">
                                Exclusive Pricing
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="pricingType" id="pricingInclusive" value="inclusive" {{ $pricingType === 'inclusive' ? 'checked' : '' }}>
                            <label class="form-check-label" for="pricingInclusive">
                                Inclusive Pricing
                            </label>
                        </div>
                    </div>
                </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-custom" id="saveSettings">Save Settings</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Print Options Modal -->
        <div class="modal fade" id="printOptionsModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-primary-custom text-white">
                        <h5 class="modal-title"><i class="fas fa-print me-2"></i> Print Options</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Print Document</label>
                            <div class="form-check">
        <input class="form-check-input" type="checkbox" id="printDeliveryNote" checked>
        <label class="form-check-label" for="printDeliveryNote">
            Print Delivery Note
        </label>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="checkbox" id="printInvoice" checked>
            <label class="form-check-label" for="printInvoice">
                Print Invoice
            </label>
        </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-custom" id="confirmPrint">Continue</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

   <script>
 document.addEventListener('DOMContentLoaded', function() {
     const items       = @json($items);
     const accounts    = @json($accounts);
     const taxes       = @json($taxes);
     const uoms        = @json($uoms);
     const pricingType = "{{ $pricingType }}";
     const docType     = "{{ $type }}";

    // Customer Information Population
     document.getElementById('customerSelect').addEventListener('change', function() {
         const selectedOption = this.options[this.selectedIndex];
         document.getElementById('contactPerson').value = selectedOption.dataset.contact || '';
         document.getElementById('customerAddress').value = selectedOption.dataset.address || '';
         document.getElementById('customerPhone').value = selectedOption.dataset.phone || '';
         document.getElementById('customerEmail').value = selectedOption.dataset.email || '';
         document.getElementById('customerVat').value = selectedOption.dataset.vat || '';
         document.getElementById('customerTin').value = selectedOption.dataset.tin || '';

         if (docType === 'credit_note') {
             const sel = document.getElementById('applyInvoiceSelect');
             if (sel && this.value) {
                 fetch(`/api/customers/${this.value}/invoices`, { headers: { 'Accept': 'application/json' } })
                     .then(r => r.json())
                     .then(data => {
                         const invoices = (data || []).filter(x => x.status === 'processed' || x.status === 'partially_paid');
                         sel.innerHTML = `<option value="">Select Invoice</option>` + invoices.map(inv =>
                             `<option value="${inv.id}">${inv.document_number} - Balance: $${Number(inv.balance_due || 0).toFixed(2)}</option>`
                         ).join('');
                     });
             }
         }
     });

    // Add Line Functionality
    function addLine() {
        const tbody = document.querySelector('#lineItemsTable tbody');
        const idx   = tbody.children.length;
        const row   = document.createElement('tr');
        row.className = 'line-item-row';
        row.innerHTML = `
            <td>${idx+1}</td>
            <td>
              <select name="lines[${idx}][module]" class="form-select form-select-sm module-select">
                <option value="ST" selected>ST</option>
                <option value="GL">GL</option>
              </select>
            </td>
            <td><input type="text" name="lines[${idx}][hs_code]" class="form-control form-control-sm"></td>
            <td>
              <select name="lines[${idx}][item_id]" class="form-select form-select-sm item-select">
                <option value="">Select Item</option>
                ${generateItemOptions()}
              </select>
              <select name="lines[${idx}][account_id]" class="form-select form-select-sm account-select" style="display:none">
                <option value="">Select Account</option>
                ${generateAccountOptions()}
              </select>
              <input type="hidden" name="lines[${idx}][account_type]" class="account-type" value="main_accounts">
            </td>
            <td><input type="text" readonly class="form-control form-control-sm item-description"></td>
            <td><textarea name="lines[${idx}][description]" class="form-control form-control-sm" rows="1"></textarea></td>
            <td>
              <select name="lines[${idx}][warehouse_id]" class="form-select form-select-sm warehouse-select">
                    <option value="">Select Warehouse</option>
                    @foreach($warehouses as $w)
                        <option value="{{ $w->id }}">{{ $w->description }}</option>
                    @endforeach
                </select>
            </td>
            <td><input type="number" readonly class="form-control form-control-sm available-qty" value="0"></td>
            <td><input type="number" name="lines[${idx}][quantity]" class="form-control form-control-sm quantity" value="1" min="0.01" step="0.01"></td>
            <td>
              <select name="lines[${idx}][uom_id]" class="form-select form-select-sm uom-select">
                <option value="">Select UOM</option>
                ${generateUomOptions()}
              </select>
            </td>
            <td><input type="number" name="lines[${idx}][confirmed_quantity]" class="form-control form-control-sm confirmed-qty" value="1" min="0.01" step="0.01"></td>
            <td><input type="number" name="lines[${idx}][price]" class="form-control form-control-sm price" value="0.00" min="0" step="0.01"></td>
            <td>
              <select name="lines[${idx}][tax_id]" class="form-select form-select-sm tax-select">
                @foreach($taxes as $tax)
                  <option value="{{ $tax->id }}" data-rate="{{ $tax->rate }}">{{ $tax->description }}</option>
                @endforeach
              </select>
            </td>
            <td><input type="text" readonly class="form-control form-control-sm tax-rate" value="{{ $taxes[0]->rate }}%"></td>
            <td><input type="number" name="lines[${idx}][discount_percent]" class="form-control form-control-sm discount" value="0" min="0" max="100" step="0.01"></td>
            <td><span class="fw-bold line-tax">$0.00</span></td>
            <td><span class="fw-bold line-total">$0.00</span></td>
            <td class="text-center"><i class="fas fa-trash-alt action-icon"></i></td>
        `;
        tbody.appendChild(row);

        // Event Listeners
        row.querySelector('.module-select').addEventListener('change', e => toggleModule(e.target, row));
        toggleModule(row.querySelector('.module-select'), row);
        row.querySelector('.item-select').addEventListener('change', e => updateItem(e.target, row));
        row.querySelector('.account-select').addEventListener('change', e => updateAccount(e.target, row));
        row.querySelector('.tax-select').addEventListener('change', e => updateTax(e.target, row));
        ['quantity','confirmed-qty','price','discount'].forEach(c => {
            const el = row.querySelector(`.${c}`);
            if (el) el.addEventListener('input', () => calculateLine(row));
        });
        row.querySelector('.action-icon').addEventListener('click', () => {
            row.remove(); renumber(); updateTotals();
        });
    }

    function toggleModule(sel, row) {
        const isGL = sel.value === 'GL';
        row.querySelector('.item-select').style.display    = isGL ? 'none' : '';
        row.querySelector('.account-select').style.display = isGL ? '' : 'none';
        if (isGL) row.querySelector('.account-type').value = 'App\\\\Models\\\\GeneralLedger';
        row.querySelector('.warehouse-select').disabled    = isGL;
        row.querySelector('.available-qty').disabled       = isGL;
        row.querySelector('.available-qty').value          = isGL ? 0 : row.querySelector('.available-qty').value;
        document.getElementById('itemAccountHeader').textContent = isGL ? 'Account' : 'Item';
        document.getElementById('descriptionHeader').textContent = isGL ? 'Acc Description' : 'Item Description';
    }

    function generateItemOptions() {
        return items.sort((a,b)=>a.code.localeCompare(b.code))
                    .map(i=>`<option value="${i.id}" data-desc="${i.description1}" data-wh="${i.warehouse_id}" data-uom="${i.uom}" data-cost="${i.cost}">${i.code} - ${i.description1}</option>`)
                    .join('');
    }

    function generateAccountOptions() {
        return accounts.sort((a,b)=>String(a.code).localeCompare(String(b.code)))
                       .flatMap(acc => acc.subAccounts?.length
                            ? acc.subAccounts.map(sa => `<option value="${sa.id}" data-desc="${sa.sub_name || ''}" data-sub-table="${sa.sub_table || 'sub_accounts'}">${acc.code || ''} - ${sa.account_code || ''} - ${sa.sub_name || ''}</option>`)
                            : [`<option value="${acc.id}" data-desc="${acc.account_name || ''}" data-sub-table="main_accounts">${acc.code || ''} - ${acc.account_name || ''}</option>`])
                       .join('');
    }

    function generateUomOptions() {
        return uoms.map(u => `<option value="${u.id}">${u.description}</option>`).join('');
    }

    function updateItem(sel, row) {
        const i = items.find(x=>x.id==sel.value);
        if (!i) return;
        row.querySelector('.item-description').value = i.description1;
        row.querySelector('.warehouse-select').value  = i.warehouse_id;
        row.querySelector('.uom-select').value        = i.uom;
        row.querySelector('.price').value             = i.cost;
        row.querySelector('.available-qty').value     = i.available || 0;
        calculateLine(row);
    }

    async function updateAccount(sel, row) {
        const hiddenType = row.querySelector('.account-type');
        const selected = sel.selectedOptions[0];
        hiddenType.value = selected?.dataset?.subTable || 'main_accounts';
        row.querySelector('.item-description').value = selected?.dataset?.desc || '';
        row.querySelector('.price').value = 0;
        row.querySelector('.available-qty').value = 0;
        calculateLine(row);
    }

    function updateTax(sel, row) {
        const tr = sel.selectedOptions[0].dataset.rate;
        row.querySelector('.tax-rate').value = tr + '%';
        calculateLine(row);
    }

    // --- Calculation logic pulled exactly from your working view ---
    function calculateLine(row) {
        const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
        const confirmedQty = parseFloat(row.querySelector('.confirmed-qty').value) || 0;
        let price = parseFloat(row.querySelector('.price').value) || 0;
        const discount = parseFloat(row.querySelector('.discount').value) || 0;
        const taxRate = parseFloat(row.querySelector('.tax-select').selectedOptions[0].dataset.rate) || 0;

        // Determine exclusive unit price and per‑unit tax if pricing is inclusive
        let unitPriceExcl = price;
        let unitTax = 0;
        if (pricingType === 'inclusive') {
            unitPriceExcl = price / (1 + (taxRate / 100));
            unitTax = price - unitPriceExcl;
        }

        // Calculate confirmed line amounts
        const confExcl = confirmedQty * (pricingType === 'inclusive' ? unitPriceExcl : price);
        const confDisc = confExcl * (discount / 100);
        const confTaxable = confExcl - confDisc;
        const confTax = confTaxable * (taxRate / 100);
        const confTotal = confTaxable;

        // Update per‑line tax & total display
        if (pricingType === 'inclusive') {
            row.querySelector('.line-tax').textContent = `$${(confirmedQty * unitTax).toFixed(2)}`;
        } else {
            row.querySelector('.line-tax').textContent = `$${confTax.toFixed(2)}`;
        }
        row.querySelector('.line-total').textContent = `$${confTotal.toFixed(2)}`;

        updateTotals();
    }

    function updateTotals() {
        let confExclTotal = 0;
        let confTaxTotal = 0;
        let confDiscTotal = 0;

        document.querySelectorAll('.line-item-row').forEach(row => {
            const confirmedQty = parseFloat(row.querySelector('.confirmed-qty').value) || 0;
            let price = parseFloat(row.querySelector('.price').value) || 0;
            const discount = parseFloat(row.querySelector('.discount').value) || 0;
            const taxRate = parseFloat(row.querySelector('.tax-select').selectedOptions[0].dataset.rate) || 0;

            let unitPriceExcl = price;
            if (pricingType === 'inclusive') {
                unitPriceExcl = price / (1 + (taxRate / 100));
            }

            const confExcl = confirmedQty * unitPriceExcl;
            const confDisc = confExcl * (discount / 100);
            const confTaxable = confExcl - confDisc;
            const confTax = confTaxable * (taxRate / 100);

            confExclTotal += confTaxable;
            confTaxTotal += confTax;
            confDiscTotal += confDisc;
        });

        const confInclTotal = confExclTotal + confTaxTotal;

        // Display grand totals exactly as in your working view
        document.getElementById('exclTotal').textContent    = `$${confExclTotal.toFixed(2)}`;
        document.getElementById('taxTotal').textContent     = `$${confTaxTotal.toFixed(2)}`;
        document.getElementById('discountTotal').textContent= `$${confDiscTotal.toFixed(2)}`;
        document.getElementById('inclTotal').textContent    = `$${confInclTotal.toFixed(2)}`;
    }
    // --- End of pulled calculation logic ---

    function renumber() {
        document.querySelectorAll('#lineItemsTable tbody tr').forEach((r,i)=>{
            r.querySelector('td').textContent = i+1;
        });
    }

    // Settings Modal Logic
    document.getElementById('saveSettings').addEventListener('click', function() {
        const prefix = document.getElementById('docPrefix').value;
        const startNum = document.getElementById('startNumber').value;
        const pricingType = document.querySelector('input[name="pricingType"]:checked').value;

        fetch("{{ route('settings.update-document') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                prefix: prefix,
                start_number: startNum,
                pricing_type: pricingType,
                document_type: "{{ $type }}"
            })
        })
        .then(response => response.json())
        .then(data => {
            if(data.success) {
                location.reload();
            }
        });
    });

    // Print Options Logic
document.getElementById('confirmPrint').addEventListener('click', function() {
    const printDeliveryNote = document.getElementById('printDeliveryNote').checked;
    const printInvoice = document.getElementById('printInvoice').checked;

    if(printDeliveryNote) {
        window.open(
            "{{ route('documents.delivery-note', 'DOC_ID') }}".replace('DOC_ID', {{ session('processed_document_id') }}),
            '_blank'
        );
    }

    if(printInvoice) {
        window.open(
            "{{ route('documents.invoice', 'DOC_ID') }}".replace('DOC_ID', {{ session('processed_document_id') }}),
            '_blank'
        );
    }

    $('#printOptionsModal').modal('hide');
    location.reload();
});
    // Initialize
    document.querySelector('.add-line-btn').addEventListener('click', addLine);
    addLine();

    @if (session('processed_document_id'))
        $(document).ready(function() {
            $('#printOptionsModal').modal('show');
        });
    @endif
});


</script>

</body>
</html>
