<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e($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: <?php echo e($themeColor); ?>;
            --primary-light: <?php echo e($themeLight); ?>;
            --primary-dark: <?php echo e($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(74, 109, 167, 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(74, 109, 167, 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-purchase_order {
            --primary-color: #4a6da7;
            --primary-light: #6a8bc7;
            --primary-dark: #2a4d87;
        }

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

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

        .theme-returns_debit {
            --primary-color: #ff6b6b;
            --primary-light: #ff9b9b;
            --primary-dark: #e53b3b;
        }

        .theme-credit_supplier {
            --primary-color: #17a2b8;
            --primary-light: #5bc0de;
            --primary-dark: #117a8b;
        }

        .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-<?php echo e(str_replace(' ', '_', strtolower($documentTitle))); ?>">
    <div class="container-fluid py-3">
         <a href="<?php echo e(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 <?php echo e($documentTitle); ?></h4>
                <div class="text-light mt-1 fw-light" style="font-size: 0.85rem;">
                    Document #: <?php echo e($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="<?php echo e(route('supplier.documents.store', $type)); ?>" id="documentForm">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="document_number" value="<?php echo e($documentNumber); ?>">
                    <input type="hidden" name="pricing_type" id="pricingType" value="<?php echo e($pricingType); ?>">

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

                            <div class="mb-2">
                                <label class="form-label">Supplier <span class="text-danger">*</span></label>
                                <select name="supplier_account_id" class="form-select" id="supplierSelect" required>
                                    <option value="">Select Supplier</option>
                                    <?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $supplier): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($supplier->id); ?>"
                                                data-contact="<?php echo e($supplier->contact_person); ?>"
                                                data-address="<?php echo e($supplier->address); ?>"
                                                data-phone="<?php echo e($supplier->contact_1); ?>"
                                                data-email="<?php echo e($supplier->email); ?>"
                                                data-vat="<?php echo e($supplier->vat); ?>"
                                                data-tin="<?php echo e($supplier->tin); ?>"
                                                data-city="<?php echo e($supplier->city); ?>"
                                                data-province="<?php echo e($supplier->province); ?>">
                                            <?php echo e($supplier->supplier_code); ?> - <?php echo e($supplier->supplier_account); ?>

                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </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="supplierAddress" class="form-control" readonly>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">Telephone</label>
                                    <input type="text" id="supplierPhone" class="form-control" readonly>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">Email</label>
                                    <input type="text" id="supplierEmail" class="form-control" readonly>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label class="form-label">VAT No</label>
                                    <input type="text" id="supplierVat" 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="supplierTin" 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="<?php echo e(old('order_number')); ?>">
                                </div>
                            </div>

                            <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="<?php echo e(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="<?php echo e(old('delivery_date', now()->format('Y-m-d'))); ?>">
                                </div>
                            </div>

                            <div class="mb-2">
                                <label class="form-label">Notes</label>
                                <textarea name="special_instructions" class="form-control" rows="2"><?php echo e(old('special_instructions')); ?> Please ensure items are properly packaged.</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="<?php echo e($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>
                                    <?php $__currentLoopData = $projects; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $project): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($project->id); ?>"><?php echo e($project->code); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </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">
                                        <?php $__currentLoopData = $currencies; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $currency): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($currency->code); ?>"
                                                <?php echo e($currency->code === 'USD' ? 'selected' : ''); ?>>
                                                <?php echo e($currency->code); ?> - <?php echo e($currency->name); ?>

                                            </option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                            </div>

                            <?php 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>
                            <?php 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 (<?php echo e($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="<?php echo e(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="<?php echo e(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="<?php echo e(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" <?php echo e($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" <?php echo e($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>

    <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       = <?php echo json_encode($items, 15, 512) ?>;
    const accounts    = <?php echo json_encode($accounts, 15, 512) ?>;
    const taxes       = <?php echo json_encode($taxes, 15, 512) ?>;
    const uoms        = <?php echo json_encode($uoms, 15, 512) ?>;
    const pricingType = "<?php echo e($pricingType); ?>";

    // Supplier Information Population
    document.getElementById('supplierSelect').addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        document.getElementById('contactPerson').value = selectedOption.dataset.contact || '';
        document.getElementById('supplierAddress').value = selectedOption.dataset.address || '';
        document.getElementById('supplierPhone').value = selectedOption.dataset.phone || '';
        document.getElementById('supplierEmail').value = selectedOption.dataset.email || '';
        document.getElementById('supplierVat').value = selectedOption.dataset.vat || '';
        document.getElementById('supplierTin').value = selectedOption.dataset.tin || '';
    });

    // 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>
            </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>
                    <?php $__currentLoopData = $warehouses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $w): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($w->id); ?>"><?php echo e($w->description); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </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">
                <?php $__currentLoopData = $taxes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tax): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                  <option value="<?php echo e($tax->id); ?>" data-rate="<?php echo e($tax->rate); ?>"><?php echo e($tax->description); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
              </select>
            </td>
            <td><input type="text" readonly class="form-control form-control-sm tax-rate" value="<?php echo e($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';
        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}" data-available="${i.available}">${i.code} - ${i.description1}</option>`)
                    .join('');
    }

    function generateAccountOptions() {
        return accounts.sort((a,b)=>a.code.localeCompare(b.code))
                       .flatMap(acc=>acc.subAccounts?.length
                         ? acc.subAccounts.map(sa=>`<option value="${sa.id}" data-desc="${sa.sub_name}">${acc.code}>${sa.code} - ${sa.sub_name}</option>`)
                         : `<option value="${acc.id}" data-desc="${acc.account_name}">${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);
    }

    function updateAccount(sel, row) {
        const desc = sel.selectedOptions[0].dataset.desc;
        row.querySelector('.item-description').value = 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);
    }

    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
    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)}`;
}

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("<?php echo e(route('supplier.settings.update-document')); ?>", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
        },
        body: JSON.stringify({
            prefix: prefix,
            start_number: startNum,
            pricing_type: pricingType,
            document_type: "<?php echo e($type); ?>"
        })
    })
    .then(response => response.json())
    .then(data => {
        if(data.success) {
            location.reload();
        }
    });
});

// Initialize
document.querySelector('.add-line-btn').addEventListener('click', addLine);
addLine();
});
</script>

</body>
</html><?php /**PATH H:\systems\Quanta\demo\resources\views/maintanance/suppliers/create_supplier.blade.php ENDPATH**/ ?>