<script src="<?= APP_URL ?>/assets/js/html5-qrcode.min.js"></script>

<div class="page-header" style="margin-bottom: 16px;">
    <div>
        <a href="<?= APP_URL ?>/sales" class="btn btn-ghost btn-sm mb-2" style="padding-left:0; padding: 6px 12px; font-size: 0.85rem;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
            Back to Sales
        </a>
        <h1 style="font-size: 1.4rem; margin-bottom: 4px;">Create Sale Invoice</h1>
        <div class="page-subtitle" style="font-size: 0.85rem;">Create a new sale invoice for credit sales or detailed billing.</div>
    </div>
</div>

<div class="invoice-form-container">
    <div class="card" style="padding: 16px;">
        <div class="card-header" style="margin-bottom: 16px; padding-bottom: 12px;">
            <h3 class="card-title" style="font-size: 1rem;">Invoice Details</h3>
        </div>
        <form action="<?= APP_URL ?>/invoices/store" method="POST" id="invoiceForm">
            <?= Security::csrfField() ?>
            <input type="hidden" name="subtotal" value="0">
            <input type="hidden" name="tax_amount" value="0">
            <input type="hidden" name="total" value="0">
            
            <!-- Customer and Location Selection -->
            <div class="form-row" style="margin-bottom: 16px;">
                <div>
                    <label class="form-label" style="font-size: 0.85rem; margin-bottom: 4px;">Customer</label>
                    <div style="display:flex; gap:6px;">
                        <select name="customer_id" class="form-control" style="flex:1; padding: 6px 8px; font-size: 0.85rem;">
                            <option value="">Walk-in Customer</option>
                            <?php foreach ($customers as $c): 
                                if (trim(strtolower($c['name'])) === 'walk-in customer') continue;
                            ?>
                                <option value="<?= $c['id'] ?>" data-balance="<?= $c['balance'] ?? 0 ?>" <?= ($settings['default_customer_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= e($c['name']) ?> (<?= e($c['phone'] ?? '') ?>)</option>
                            <?php endforeach; ?>
                        </select>
                        <a href="<?= APP_URL ?>/customers" class="btn btn-ghost" title="Add Customer" style="padding: 6px 10px;">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width: 16px; height: 16px;"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                        </a>
                    </div>
                    <div id="customerBalance" style="font-size:0.75rem; color:var(--text-muted); margin-top:4px;"></div>
                </div>
                
                <div>
                    <label class="form-label" style="font-size: 0.85rem; margin-bottom: 4px;">Location <span class="required">*</span></label>
                    <select name="location_id" class="form-control" required onchange="loadStockForLocation()" style="padding: 6px 8px; font-size: 0.85rem;">
                        <option value="">Select Location...</option>
                        <?php foreach ($locations as $l): ?>
                            <option value="<?= $l['id'] ?>" <?= ($settings['default_location_id'] ?? '') == $l['id'] || !empty($l['is_default']) ? 'selected' : '' ?>><?= e($l['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            
            <!-- Products Table -->
            <div class="form-group" style="margin-bottom: 16px;">
                <label class="form-label" style="font-size: 0.85rem; margin-bottom: 4px;">Products <span class="required">*</span></label>
                <div class="search-box" style="margin-bottom:10px; position:relative;">
                    <div style="position:relative; display:flex; gap:8px;">
                        <div style="position:relative; flex:1;">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="position:absolute; left:10px; top:50%; transform:translateY(-50%); color:var(--text-muted); width:14px; height:14px; display: none;">
                                <circle cx="11" cy="11" r="8"></circle>
                                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                            </svg>
                            <input type="text"
                                   id="productSearchInput"
                                   class="form-control"
                                   placeholder="Search product by name, SKU, or barcode..."
                                   autocomplete="off"
                                   oninput="searchInvoiceProducts(this.value)"
                                   onkeydown="handleInvoiceSearchKeydown(event)"
                                   style="padding-left:20px; padding: 14px 20px; font-size: 1rem; min-height: 48px; min-width: 600px; width: 100%;">
                        </div>
                        <button type="button" id="scan-button" onclick="openBarcodeScanner()" style="padding: 6px 12px; border: 1px solid var(--border); background: var(--bg-elevated, #fff); border-radius: 6px; font-size: 0.85rem; cursor: pointer; display: flex; align-items: center; gap: 4px;">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display: none;"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
                            Scan
                        </button>
                    </div>
                    <div id="productSearchResults" class="hidden" style="position:absolute; left:0; right:0; top:calc(100% + 4px); background:var(--bg-elevated, #fff); border:1px solid var(--border); border-radius:8px; max-height:280px; overflow:auto; z-index:50;"></div>
                </div>
                <div style="display:none;">
                    <select id="productSelect" class="form-control" onchange="addProductToInvoice()">
                        <option value="">Add Product...</option>
                        <?php foreach ($products as $p): ?>
                            <option value="<?= $p['id'] ?>"
                                    data-price="<?= $p['selling_price'] ?>"
                                    data-stock="<?= $p['total_stock'] ?>"
                                    data-sku="<?= e($p['sku'] ?? '') ?>"
                                    data-barcode="<?= e($p['barcode'] ?? '') ?>"
                                    data-unit="<?= $p['unit'] ?? '' ?>"
                                    data-batch-tracking="<?= $p['batch_tracking'] ?? 0 ?>">
                                <?= e($p['name']) ?> (<?= e($p['sku']) ?>) - Stock: <?= number_format($p['total_stock'], 2) ?> - <?= money($p['selling_price']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div id="invoiceItems" style="border:1px solid var(--border); border-radius:8px; overflow:hidden;">
                    <div style="padding:8px 10px; background:var(--bg-raised); border-bottom:1px solid var(--border); display:grid; grid-template-columns: 3fr 1fr 1fr 1fr 1fr auto; gap:6px; font-weight:600; font-size:0.75rem;">
                        <span>Product</span>
                        <span>Quantity</span>
                        <span>Unit Price</span>
                        <span>Discount</span>
                        <span>Total</span>
                        <span></span>
                    </div>
                    <div id="itemsContainer">
                        <div style="padding:24px 10px; text-align:center; color:var(--text-muted); font-size: 0.85rem;">
                            No items added yet
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Totals -->
            <div style="padding:12px; background:var(--bg-raised); border-radius:8px; border:1px solid var(--border); margin-bottom: 16px;">
                <div style="display:flex; justify-content:space-between; margin-bottom:6px; font-size: 0.85rem;">
                    <span>Subtotal:</span>
                    <span id="subtotal">0.00</span>
                </div>
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px; font-size: 0.85rem;">
                    <span>Discount:</span>
                    <div style="display:flex; align-items:center; gap:6px;">
                        <input type="number" step="0.01" name="discount_amount" class="form-control" style="width:80px; padding:4px 6px; font-size: 0.85rem;" value="0" onchange="calculateTotals()">
                    </div>
                </div>
                <?php if ($taxEnabled): ?>
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:6px; font-size: 0.85rem;">
                    <span>Tax (<?= $taxRate ?>%):</span>
                    <span id="taxAmount">0.00</span>
                </div>
                <?php endif; ?>
                <div style="display:flex; justify-content:space-between; font-weight:700; font-size:1rem; padding-top:6px; border-top:1px solid var(--border);">
                    <span>Total:</span>
                    <span id="totalAmount" style="color:var(--primary);">0.00</span>
                </div>
            </div>
            
            <!-- Payment Details -->
            <div class="form-group" style="margin-bottom: 16px;">
                <label class="form-label" style="font-size: 0.85rem; margin-bottom: 4px;">Payment Details</label>
                <div class="form-row">
                    <div>
                        <label style="font-size:0.8rem; color:var(--text-muted); margin-bottom: 4px;">Payment Method</label>
                        <select name="payment_method" class="form-control" style="padding: 6px 8px; font-size: 0.85rem;">
                            <?php
                            // Force Cash to always be available and default
                            $defaultMethods = ['cash' => 'Cash', 'card' => 'Card', 'transfer' => 'Bank Transfer', 'cheque' => 'Cheque', 'credit' => 'Credit', 'momo' => 'Momo Pay', 'mobile_money' => 'Mobile Money', 'other' => 'Other'];
                            
                            // Always output Cash first
                            echo '<option value="cash" selected>Cash</option>';
                            
                            // Add configured methods (excluding cash)
                            $configuredMethods = json_decode($settings['payment_methods'] ?? '[]', true) ?: [];
                            $paymentMethodLabels = json_decode($settings['payment_method_labels'] ?? '{}', true) ?: [];
                            
                            foreach ($configuredMethods as $method) {
                                if ($method !== 'cash') {
                                    $label = $paymentMethodLabels[$method] ?? ($defaultMethods[$method] ?? ucfirst($method));
                                    echo '<option value="' . e($method) . '">' . e($label) . '</option>';
                                }
                            }
                            ?>
                        </select>
                    </div>
                    <div>
                        <label style="font-size:0.8rem; color:var(--text-muted); margin-bottom: 4px;">Amount Paid</label>
                        <input type="number" step="0.01" name="paid_amount" class="form-control" value="0" onchange="calculateTotals()" style="padding: 6px 8px; font-size: 0.85rem;">
                    </div>
                </div>
                <div id="dueAmount" style="font-size:0.8rem; color:var(--text-muted); margin-top:4px;"></div>
            </div>

            <!-- Payment Status -->
            <div class="form-group" style="margin-bottom: 16px;">
                <label class="form-label" style="font-size: 0.85rem; margin-bottom: 4px;">Payment Status</label>
                <select name="payment_status" class="form-control" style="padding: 6px 8px; font-size: 0.85rem;">
                    <option value="paid">Paid in Full</option>
                    <option value="partial">Partial Payment</option>
                    <option value="due" selected>Due</option>
                    <option value="credit">Credit</option>
                </select>
            </div>

            <!-- Notes -->
            <div class="form-group" style="margin-bottom: 16px;">
                <label class="form-label" style="font-size: 0.85rem; margin-bottom: 4px;">Notes (Optional)</label>
                <textarea name="notes" class="form-control" rows="2" placeholder="Add any notes about this invoice..." style="padding: 6px 8px; font-size: 0.85rem;"></textarea>
            </div>
        
            <div class="flex justify-end gap-2" style="margin-top: 16px;">
                <a href="<?= APP_URL ?>/sales" class="btn btn-ghost" style="padding: 8px 16px; font-size: 0.85rem;">Cancel</a>
                <button type="submit" class="btn btn-primary" style="padding: 8px 16px; font-size: 0.85rem;">Create Invoice</button>
            </div>
        </form>
    </div>
</div>

<!-- Barcode Scanner Modal -->
<div class="modal-overlay" id="barcodeScannerModal" style="position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.5) !important; align-items: center !important; justify-content: center !important; z-index: 99999 !important;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 500px; max-width: 95%; max-height: 90vh; box-shadow: 0 4px 12px rgba(0,0,0,0.15); display: flex; flex-direction: column;">
        <div class="modal-header" style="padding: 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1.1rem; font-weight: 700;">Scan Barcode</h3>
            <button class="modal-close" onclick="closeBarcodeScanner()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>
        <div class="modal-body" style="padding: 16px; flex: 1; overflow-y: auto; display: flex; flex-direction: column; align-items: center;">
            <div id="scanner-container" style="width: 100%; height: 300px; background: #000; border-radius: 8px; overflow: hidden; position: relative;"></div>
            <div id="scanner-status" style="margin-top: 12px; font-size: 0.9rem; color: #666;">Initializing camera...</div>
            <div id="scanned-result" style="margin-top: 8px; font-size: 1rem; font-weight: 600; color: #28a745; display: none;"></div>
        </div>
        <div class="modal-footer" style="padding: 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <button type="button" onclick="closeBarcodeScanner()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Cancel</button>
            <button type="button" id="btn-manual-barcode" onclick="showManualBarcodeInput()" style="padding: 8px 16px; border: 1px solid #007bff; background: #fff; color: #007bff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Enter Manually</button>
        </div>
    </div>
</div>

<!-- Manual Barcode Input Modal -->
<div class="modal-overlay" id="manualBarcodeModal" style="position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; height: 100% !important; background: rgba(0,0,0,0.5) !important; align-items: center !important; justify-content: center !important; z-index: 100000 !important;">
    <div class="modal" style="background: #fff; border-radius: 8px; width: 400px; max-width: 90%; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
        <div class="modal-header" style="padding: 16px; border-bottom: 1px solid #e5e5e5; display: flex; justify-content: space-between; align-items: center;">
            <h3 class="modal-title" style="margin: 0; font-size: 1.1rem; font-weight: 700;">Enter Barcode</h3>
            <button class="modal-close" onclick="hideManualBarcodeInput()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="width:16px;">
                    <line x1="18" y1="6" x2="6" y2="18"></line>
                    <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </button>
        </div>
        <div class="modal-body" style="padding: 16px;">
            <div class="form-group" style="margin-bottom: 12px;">
                <label class="form-label" style="display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600;">Barcode / SKU</label>
                <input type="text" id="manual-barcode-input" class="form-control" placeholder="Enter barcode or SKU..." style="width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.9rem;" autofocus>
            </div>
        </div>
        <div class="modal-footer" style="padding: 16px; border-top: 1px solid #e5e5e5; display: flex; justify-content: flex-end; gap: 8px;">
            <button type="button" onclick="hideManualBarcodeInput()" style="padding: 8px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Cancel</button>
            <button type="button" onclick="submitManualBarcode()" style="padding: 8px 16px; border: none; background: #28a745; color: #fff; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">Add Product</button>
        </div>
    </div>
</div>

<style>
.modal-overlay {
    display: none !important;
}

.modal-overlay.show {
    display: flex !important;
}

.modal-overlay button:hover {
    opacity: 0.8;
}

.modal-overlay button:disabled {
    opacity: 0.5 !important;
    cursor: not-allowed;
}
</style>

<script>
// Barcode Scanner Functions
let html5QrCode = null;
let isScanning = false;

function openBarcodeScanner() {
    console.log('openBarcodeScanner called');
    const modal = document.getElementById('barcodeScannerModal');
    if (modal) {
        modal.classList.add('show');
        document.getElementById('scanned-result').style.display = 'none';
        console.log('Starting scanner...');
        startCamera();
    } else {
        console.error('Scanner modal not found');
        alert('Scanner modal not found');
    }
}

function closeBarcodeScanner() {
    console.log('closeBarcodeScanner called');
    if (html5QrCode && isScanning) {
        html5QrCode.stop().then(() => {
            isScanning = false;
            document.getElementById('barcodeScannerModal').classList.remove('show');
        }).catch(err => {
            console.error('Failed to stop scanner:', err);
            document.getElementById('barcodeScannerModal').classList.remove('show');
        });
    } else {
        document.getElementById('barcodeScannerModal').classList.remove('show');
    }
}

function showManualBarcodeInput() {
    closeBarcodeScanner();
    const modal = document.getElementById('manualBarcodeModal');
    modal.classList.add('show');
    setTimeout(() => document.getElementById('manual-barcode-input').focus(), 100);
}

function hideManualBarcodeInput() {
    const modal = document.getElementById('manualBarcodeModal');
    modal.classList.remove('show');
    document.getElementById('manual-barcode-input').value = '';
}

function submitManualBarcode() {
    const barcode = document.getElementById('manual-barcode-input').value.trim();
    if (barcode) {
        handleScannedBarcode(barcode);
        hideManualBarcodeInput();
    }
}

async function startCamera() {
    console.log('startCamera called, isScanning:', isScanning);
    if (isScanning) return;

    function checkLibrary(retryCount = 0) {
        console.log('Checking for Html5Qrcode, attempt:', retryCount + 1);
        if (typeof Html5Qrcode !== 'undefined') {
            console.log('Html5Qrcode is available, starting scanner');
            html5QrCode = new Html5Qrcode("scanner-container");

            console.log('Html5QrcodeSupportedFormats available:', typeof Html5QrcodeSupportedFormats !== 'undefined');

            const config = {
                fps: 10,
                qrbox: { width: 250, height: 150 },
                aspectRatio: 1.777,
                disableFlip: false,
                experimentalFeatures: {
                    useBarCodeDetectorIfSupported: true
                }
            };

            if (typeof Html5QrcodeSupportedFormats !== 'undefined') {
                config.formatsToSupport = [
                    Html5QrcodeSupportedFormats.CODE_128,
                    Html5QrcodeSupportedFormats.EAN_13,
                    Html5QrcodeSupportedFormats.EAN_8,
                    Html5QrcodeSupportedFormats.CODE_39,
                    Html5QrcodeSupportedFormats.UPC_A,
                    Html5QrcodeSupportedFormats.UPC_E
                ];
                console.log('Barcode formats enabled');
            } else {
                console.log('Html5QrcodeSupportedFormats not available, using default formats');
            }

            console.log('Scanner config:', config);

            const startCameraWithConfig = () => {
                Html5Qrcode.getCameras().then(devices => {
                    if (devices && devices.length > 0) {
                        console.log('Available cameras:', devices);
                        const rearCamera = devices.find(device =>
                            device.label && device.label.toLowerCase().includes('back') ||
                            device.label && device.label.toLowerCase().includes('rear') ||
                            device.label && device.label.toLowerCase().includes('environment')
                        );

                        const cameraId = rearCamera ? rearCamera.id : devices[0].id;
                        console.log('Using camera:', rearCamera ? rearCamera.label : devices[0].label);

                        html5QrCode.start(
                            cameraId,
                            config,
                            onScanSuccess,
                            onScanFailure
                        ).then(() => {
                            isScanning = true;
                            console.log('Scanner started successfully with camera ID:', cameraId);
                            document.getElementById('scanner-status').textContent = 'Camera active - Point at a barcode';
                            document.getElementById('scanner-status').style.color = '#666';
                        }).catch(err => {
                            console.error('Failed to start scanner with enumerated camera:', err);
                            console.log('Falling back to facingMode...');
                            html5QrCode.start(
                                { facingMode: "environment" },
                                config,
                                onScanSuccess,
                                onScanFailure
                            ).then(() => {
                                isScanning = true;
                                console.log('Scanner started successfully with environment camera');
                                document.getElementById('scanner-status').textContent = 'Camera active - Point at a barcode';
                                document.getElementById('scanner-status').style.color = '#666';
                            }).catch(err2 => {
                                console.error('Failed to start scanner:', err2);
                                document.getElementById('scanner-status').textContent = 'Camera access denied or not available. Use manual entry.';
                                document.getElementById('scanner-status').style.color = '#dc3545';
                            });
                        });
                    } else {
                        console.log('No cameras enumerated, trying facingMode...');
                        html5QrCode.start(
                            { facingMode: "environment" },
                            config,
                            onScanSuccess,
                            onScanFailure
                        ).then(() => {
                            isScanning = true;
                            console.log('Scanner started successfully with environment camera');
                            document.getElementById('scanner-status').textContent = 'Camera active - Point at a barcode';
                            document.getElementById('scanner-status').style.color = '#666';
                        }).catch(err => {
                            console.error('Failed to start scanner:', err);
                            document.getElementById('scanner-status').textContent = 'Camera access denied or not available. Use manual entry.';
                            document.getElementById('scanner-status').style.color = '#dc3545';
                        });
                    }
                }).catch(err => {
                    console.error('Failed to enumerate cameras:', err);
                    console.log('Falling back to facingMode...');
                    html5QrCode.start(
                        { facingMode: "environment" },
                        config,
                        onScanSuccess,
                        onScanFailure
                    ).then(() => {
                        isScanning = true;
                        console.log('Scanner started successfully with environment camera');
                        document.getElementById('scanner-status').textContent = 'Camera active - Point at a barcode';
                        document.getElementById('scanner-status').style.color = '#666';
                    }).catch(err2 => {
                        console.error('Failed to start scanner:', err2);
                        document.getElementById('scanner-status').textContent = 'Camera access denied or not available. Use manual entry.';
                        document.getElementById('scanner-status').style.color = '#dc3545';
                    });
                });
            };

            setTimeout(() => startCameraWithConfig(), 300);
        } else if (retryCount < 10) {
            console.log('Html5Qrcode not yet available, retrying in 500ms...');
            setTimeout(() => checkLibrary(retryCount + 1), 500);
        } else {
            console.error('Html5Qrcode failed to load after 10 attempts');
            document.getElementById('scanner-status').textContent = 'html5-qrcode library not loaded. Please check your internet connection and refresh the page.';
            document.getElementById('scanner-status').style.color = '#dc3545';
        }
    }

    checkLibrary();
}

function onScanSuccess(decodedText, decodedResult) {
    console.log("SCANNED:", decodedText);
    alert("Scanned: " + decodedText);

    if (html5QrCode && isScanning) {
        html5QrCode.stop().then(() => {
            isScanning = false;
        }).catch(err => {
            console.error('Failed to stop scanner:', err);
        });
    }

    const resultDiv = document.getElementById('scanned-result');
    const status = document.getElementById('scanner-status');
    resultDiv.style.display = 'block';
    resultDiv.style.background = '#d4edda';
    resultDiv.style.border = '2px solid #28a745';
    resultDiv.style.padding = '12px';
    resultDiv.style.borderRadius = '6px';
    resultDiv.textContent = decodedText;
    resultDiv.style.color = '#155724';
    resultDiv.style.fontSize = '1.1rem';
    resultDiv.style.fontWeight = '700';
    status.textContent = 'Barcode found!';
    status.style.color = '#28a745';

    setTimeout(() => {
        handleScannedBarcode(decodedText);
        closeBarcodeScanner();
    }, 500);
}

function onScanFailure(error) {
    // This is normal during scanning - ignore
}

function handleScannedBarcode(barcode) {
    // Search for product by barcode
    const searchInput = document.getElementById('productSearchInput');
    searchInput.value = barcode;
    // Trigger the search
    searchInput.dispatchEvent(new Event('input'));
}

async function loadStockForLocation() {
    const locationSelect = document.querySelector('select[name="location_id"]');
    const locationId = locationSelect.value;
    if (!locationId) return;

    try {
        const response = await fetch(`<?= APP_URL ?>/api/location-stock?location_id=${locationId}`);
        const data = await response.json();
        const stockMap = data.stock_map;

        const select = document.getElementById('productSelect');
        const options = select.querySelectorAll('option');

        options.forEach(option => {
            if (!option.value) return;
            const productId = option.value;
            const stock = stockMap[productId] || 0;
            
            // Update data attribute
            option.setAttribute('data-stock', stock);
            
            // Update visible text
            // Format: Name (SKU) - Stock: XX.XX - Price
            const currentText = option.textContent;
            const stockPattern = / - Stock: [\d,.]+/;
            option.textContent = currentText.replace(stockPattern, ` - Stock: ${parseFloat(stock).toFixed(2)}`);
        });

        // Update existing invoice items stock values
        invoiceItems.forEach(item => {
            if (stockMap[item.productId] !== undefined) {
                item.stock = parseFloat(stockMap[item.productId]);
            } else {
                item.stock = 0;
            }
        });
        renderInvoiceItems();

    } catch (error) {
        console.error('Error loading stock map:', error);
    }
}

let invoiceItems = [];
let taxRate = <?= $taxRate ?? 0 ?>;
let taxEnabled = <?= $taxEnabled ?? 0 ?>;
let invoiceProductSearchResults = [];
let invoiceProductActiveIndex = -1;
const invoiceDraftStorageKey = 'tellerpro_invoice_draft';

function saveInvoiceDraft() {
    const draft = {
        items: invoiceItems,
        customer_id: document.querySelector('select[name="customer_id"]')?.value || '',
        location_id: document.querySelector('select[name="location_id"]')?.value || '',
        discount_amount: document.querySelector('input[name="discount_amount"]')?.value || '0',
        paid_amount: document.querySelector('input[name="paid_amount"]')?.value || '0',
        payment_method: document.querySelector('select[name="payment_method"]')?.value || '',
        payment_status: document.querySelector('select[name="payment_status"]')?.value || 'paid',
        notes: document.querySelector('textarea[name="notes"]')?.value || ''
    };
    localStorage.setItem(invoiceDraftStorageKey, JSON.stringify(draft));
}

function restoreInvoiceDraft() {
    // Check if there's a success flash message (indicating fresh page after submission)
    const successMessage = document.querySelector('.alert-success, .flash-success');
    if (successMessage) {
        clearInvoiceDraft();
        return;
    }

    const raw = localStorage.getItem(invoiceDraftStorageKey);
    if (!raw) return;

    try {
        const draft = JSON.parse(raw);
        if (Array.isArray(draft.items)) {
            invoiceItems = draft.items;
        }

        if (draft.customer_id !== undefined) {
            const customer = document.querySelector('select[name="customer_id"]');
            if (customer) {
                customer.value = draft.customer_id;
                customer.dispatchEvent(new Event('change'));
            }
        }
        if (draft.location_id !== undefined) {
            const location = document.querySelector('select[name="location_id"]');
            if (location) location.value = draft.location_id;
        }
        if (draft.discount_amount !== undefined) {
            const discount = document.querySelector('input[name="discount_amount"]');
            if (discount) discount.value = draft.discount_amount;
        }
        if (draft.paid_amount !== undefined) {
            const paid = document.querySelector('input[name="paid_amount"]');
            if (paid) paid.value = draft.paid_amount;
        }
        if (draft.payment_method !== undefined) {
            const method = document.querySelector('select[name="payment_method"]');
            if (method) method.value = draft.payment_method;
        }
        if (draft.payment_status !== undefined) {
            const status = document.querySelector('select[name="payment_status"]');
            if (status) status.value = draft.payment_status;
        }
        if (draft.notes !== undefined) {
            const notes = document.querySelector('textarea[name="notes"]');
            if (notes) notes.value = draft.notes;
        }

        renderInvoiceItems();
        calculateTotals();
    } catch (error) {
        console.error('Failed to restore invoice draft:', error);
    }
}

function clearInvoiceDraft() {
    localStorage.removeItem(invoiceDraftStorageKey);
}

function addProductToInvoice() {
    const select = document.getElementById('productSelect');
    const option = select.options[select.selectedIndex];
    
    if (!option.value) return;
    
    const productId = parseInt(option.value);
    const productName = option.text.split(' - ')[0];
    const price = parseFloat(option.getAttribute('data-price'));
    const stock = parseFloat(option.getAttribute('data-stock'));
    const unit = option.getAttribute('data-unit');
    const batchTracking = option.getAttribute('data-batch-tracking');
    
    if (stock <= 0) {
        alert('Insufficient stock');
        select.value = '';
        return;
    }

    // Check if product already in invoice
    const existingIndex = invoiceItems.findIndex(item => item.productId === productId);
    if (existingIndex > -1) {
        const item = invoiceItems[existingIndex];
        if (item.quantity >= stock) {
            alert('Insufficient stock');
            select.value = '';
            return;
        }
        item.quantity += 1;
        item.total = item.quantity * item.unitPrice - item.discount;
        // Move to top
        invoiceItems.splice(existingIndex, 1);
        invoiceItems.unshift(item);
    } else {
        // Add new item to top
        invoiceItems.unshift({
            productId: productId,
            productName: productName,
            quantity: 1,
            unitPrice: price,
            discount: 0,
            total: price,
            unit: unit,
            stock: stock,
            batchTracking: batchTracking,
            batchId: null
        });
    }
    
    select.value = '';
    renderInvoiceItems();
    calculateTotals();
    saveInvoiceDraft();
}

function getInvoiceProductList() {
    const select = document.getElementById('productSelect');
    return Array.from(select.options)
        .filter(opt => opt.value)
        .map(opt => ({
            id: parseInt(opt.value),
            label: opt.text,
            name: opt.text.split(' - ')[0],
            sku: (opt.getAttribute('data-sku') || '').toLowerCase(),
            barcode: (opt.getAttribute('data-barcode') || '').toLowerCase()
        }));
}

function searchInvoiceProducts(query) {
    const resultsBox = document.getElementById('productSearchResults');
    const normalizedQuery = query.trim().toLowerCase();

    invoiceProductActiveIndex = -1;
    if (normalizedQuery.length < 1) {
        resultsBox.innerHTML = '';
        resultsBox.classList.add('hidden');
        invoiceProductSearchResults = [];
        return;
    }

    const products = getInvoiceProductList();
    invoiceProductSearchResults = products
        .filter(p =>
            p.name.toLowerCase().includes(normalizedQuery) ||
            p.sku.includes(normalizedQuery) ||
            p.barcode.includes(normalizedQuery)
        )
        .slice(0, 12);

    if (invoiceProductSearchResults.length === 0) {
        resultsBox.innerHTML = '<div style="padding:10px 12px; color:var(--text-muted); font-size:0.85rem;">No matching products found</div>';
        resultsBox.classList.remove('hidden');
        return;
    }

    resultsBox.innerHTML = invoiceProductSearchResults.map((item, index) => `
        <button type="button"
                data-index="${index}"
                onclick="selectInvoiceProduct(${item.id})"
                style="display:block; width:100%; text-align:left; border:none; border-bottom:1px solid var(--border); background:transparent; padding:10px 12px; cursor:pointer;">
            <span style="font-size:0.9rem; color:var(--text);">${item.label}</span>
        </button>
    `).join('');

    resultsBox.classList.remove('hidden');
}

function handleInvoiceSearchKeydown(event) {
    if (!invoiceProductSearchResults.length) return;

    const resultsBox = document.getElementById('productSearchResults');
    if (event.key === 'ArrowDown') {
        event.preventDefault();
        invoiceProductActiveIndex = Math.min(invoiceProductActiveIndex + 1, invoiceProductSearchResults.length - 1);
        highlightInvoiceSearchResult(resultsBox);
    } else if (event.key === 'ArrowUp') {
        event.preventDefault();
        invoiceProductActiveIndex = Math.max(invoiceProductActiveIndex - 1, 0);
        highlightInvoiceSearchResult(resultsBox);
    } else if (event.key === 'Enter') {
        event.preventDefault();
        const selected = invoiceProductSearchResults[invoiceProductActiveIndex] || invoiceProductSearchResults[0];
        if (selected) {
            selectInvoiceProduct(selected.id);
        }
    } else if (event.key === 'Escape') {
        resultsBox.classList.add('hidden');
    }
}

function highlightInvoiceSearchResult(resultsBox) {
    const buttons = resultsBox.querySelectorAll('button[data-index]');
    buttons.forEach((btn, idx) => {
        btn.style.background = idx === invoiceProductActiveIndex ? 'var(--bg-raised)' : 'transparent';
    });
}

function selectInvoiceProduct(productId) {
    const select = document.getElementById('productSelect');
    const input = document.getElementById('productSearchInput');
    const resultsBox = document.getElementById('productSearchResults');

    select.value = String(productId);
    addProductToInvoice();

    input.value = '';
    invoiceProductSearchResults = [];
    invoiceProductActiveIndex = -1;
    resultsBox.innerHTML = '';
    resultsBox.classList.add('hidden');
    input.focus();
}

function renderInvoiceItems() {
    const container = document.getElementById('itemsContainer');
    
    if (invoiceItems.length === 0) {
        container.innerHTML = '<div style="padding:32px; text-align:center; color:var(--text-muted);">No items added yet</div>';
        return;
    }
    
    container.innerHTML = invoiceItems.map((item, index) => `
        <div style="padding:8px 10px; border-bottom:1px solid var(--border); display:grid; grid-template-columns: 3fr 1fr 1fr 1fr 1fr auto; gap:6px; align-items:center;">
            <div>
                <div style="font-weight:500; font-size:0.85rem;">${item.productName}</div>
                <div style="font-size:0.7rem; color:var(--text-muted);">Stock: ${parseFloat(item.stock).toFixed(2)} ${item.unit || ''}</div>
            </div>
            <input type="number" step="0.01" class="form-control" style="padding:4px 6px; font-size: 0.85rem;" value="${item.quantity}" 
                   min="0.01" max="${item.stock}" onchange="updateItemQuantity(${index}, this.value)">
            <input type="number" step="0.01" class="form-control" style="padding:4px 6px; font-size: 0.85rem;" value="${item.unitPrice}" 
                   onchange="updateItemPrice(${index}, this.value)">
            <input type="number" step="0.01" class="form-control" style="padding:4px 6px; font-size: 0.85rem;" value="${item.discount}" 
                   onchange="updateItemDiscount(${index}, this.value)">
            <span style="font-weight:600; font-size: 0.85rem;">${item.total.toFixed(2)}</span>
            <button type="button" class="btn btn-ghost btn-icon" onclick="removeItem(${index})">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
            <input type="hidden" name="items[product_id][]" value="${item.productId}">
            <input type="hidden" name="items[quantity][]" value="${item.quantity}">
            <input type="hidden" name="items[unit_price][]" value="${item.unitPrice}">
            <input type="hidden" name="items[discount][]" value="${item.discount}">
        </div>
    `).join('');
}

function updateItemQuantity(index, value) {
    const quantity = parseFloat(value);
    if (isNaN(quantity) || quantity <= 0) {
        alert('Invalid quantity');
        renderInvoiceItems();
        return;
    }
    if (quantity > invoiceItems[index].stock) {
        alert('Insufficient stock');
        renderInvoiceItems();
        return;
    }
    invoiceItems[index].quantity = quantity;
    invoiceItems[index].total = quantity * invoiceItems[index].unitPrice - invoiceItems[index].discount;
    renderInvoiceItems();
    calculateTotals();
    saveInvoiceDraft();
}

function updateItemPrice(index, value) {
    const price = parseFloat(value);
    invoiceItems[index].unitPrice = price;
    invoiceItems[index].total = invoiceItems[index].quantity * price - invoiceItems[index].discount;
    renderInvoiceItems();
    calculateTotals();
    saveInvoiceDraft();
}

function updateItemDiscount(index, value) {
    const discount = parseFloat(value) || 0;
    invoiceItems[index].discount = discount;
    invoiceItems[index].total = invoiceItems[index].quantity * invoiceItems[index].unitPrice - discount;
    renderInvoiceItems();
    calculateTotals();
    saveInvoiceDraft();
}

function removeItem(index) {
    invoiceItems.splice(index, 1);
    renderInvoiceItems();
    calculateTotals();
    saveInvoiceDraft();
}

function calculateTotals() {
    const subtotal = invoiceItems.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0);
    const discountAmount = parseFloat(document.querySelector('input[name="discount_amount"]').value) || 0;
    
    // Inclusive tax calculation: Total remains subtotal - discount
    const total = subtotal - discountAmount;
    const taxAmount = taxEnabled ? (total - (total / (1 + (taxRate / 100)))) : 0;
    
    const paidAmount = parseFloat(document.querySelector('input[name="paid_amount"]').value) || 0;
    const dueAmount = total - paidAmount;
    const paymentStatusSelect = document.querySelector('select[name="payment_status"]');
    
    document.getElementById('subtotal').textContent = subtotal.toFixed(2);
    if (taxEnabled) {
        document.getElementById('taxAmount').textContent = taxAmount.toFixed(2);
    }
    document.getElementById('totalAmount').textContent = total.toFixed(2);
    document.getElementById('dueAmount').textContent = dueAmount > 0 ? `Due: ${dueAmount.toFixed(2)}` : 'Fully Paid';

    // Auto-default to due when paid amount is 0, partial when paid amount is greater than 0 but less than total
    if (paidAmount === 0 && paymentStatusSelect) {
        paymentStatusSelect.value = 'due';
    } else if (paidAmount > 0 && paidAmount < total && paymentStatusSelect) {
        paymentStatusSelect.value = 'partial';
    } else if (paidAmount >= total && paymentStatusSelect) {
        paymentStatusSelect.value = 'paid';
    }
    
    // Update hidden fields
    document.querySelector('input[name="subtotal"]').value = subtotal;
    document.querySelector('input[name="tax_amount"]').value = taxAmount;
    document.querySelector('input[name="total"]').value = total;
    saveInvoiceDraft();
}

function clearInvoice() {
    if (confirm('Are you sure you want to clear the invoice?')) {
        invoiceItems = [];
        renderInvoiceItems();
        calculateTotals();
        document.querySelector('input[name="discount_amount"]').value = 0;
        document.querySelector('input[name="paid_amount"]').value = 0;
        document.querySelector('select[name="customer_id"]').value = '';
        document.getElementById('customerBalance').textContent = '';
        clearInvoiceDraft();
    }
}

function loadRecentSale() {
    fetch('<?= APP_URL ?>/api/recent-sale')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert(data.error);
                return;
            }
            
            // Load customer
            if (data.customer_id) {
                document.querySelector('select[name="customer_id"]').value = data.customer_id;
                document.querySelector('select[name="customer_id"]').dispatchEvent(new Event('change'));
            }
            
            // Load location
            if (data.location_id) {
                document.querySelector('select[name="location_id"]').value = data.location_id;
            }
            
            // Load items
            invoiceItems = [];
            data.items.forEach(item => {
                invoiceItems.push({
                    productId: item.product_id,
                    productName: item.product_name,
                    quantity: item.quantity,
                    unitPrice: item.unit_price,
                    discount: item.discount,
                    total: item.quantity * item.unit_price - item.discount,
                    unit: item.unit,
                    stock: 999, // Assume available for recent sale
                    batchTracking: 0,
                    batchId: item.batch_id
                });
            });
            
            renderInvoiceItems();
            
            // Load discount
            if (data.discount_amount) {
                document.querySelector('input[name="discount_amount"]').value = data.discount_amount;
            }
            
            // Load payment method
            if (data.payment_method) {
                document.querySelector('select[name="payment_method"]').value = data.payment_method;
            }
            
            // Load notes
            if (data.notes) {
                document.querySelector('textarea[name="notes"]').value = data.notes;
            }
            
            calculateTotals();
        })
        .catch(error => {
            console.error('Error loading recent sale:', error);
            alert('Failed to load recent sale');
        });
}

// Customer balance display
document.querySelector('select[name="customer_id"]').addEventListener('change', function() {
    const option = this.options[this.selectedIndex];
    const balance = parseFloat(option.getAttribute('data-balance')) || 0;
    document.getElementById('customerBalance').textContent = balance > 0 ? `Outstanding Balance: ${balance.toFixed(2)}` : '';
    saveInvoiceDraft();
});

document.querySelector('select[name="location_id"]').addEventListener('change', saveInvoiceDraft);
document.querySelector('input[name="discount_amount"]').addEventListener('input', saveInvoiceDraft);
document.querySelector('input[name="paid_amount"]').addEventListener('input', saveInvoiceDraft);
document.querySelector('select[name="payment_method"]').addEventListener('change', saveInvoiceDraft);
document.querySelector('select[name="payment_status"]').addEventListener('change', saveInvoiceDraft);
document.querySelector('textarea[name="notes"]').addEventListener('input', saveInvoiceDraft);

// Restore immediately for pages rendered after DOM is already ready.
restoreInvoiceDraft();
// Keep compatibility with standard full-page load flow.
document.addEventListener('DOMContentLoaded', () => {
    restoreInvoiceDraft();
    loadStockForLocation();
});
// Ensure current edits are persisted when user refreshes/leaves.
window.addEventListener('beforeunload', saveInvoiceDraft);

document.addEventListener('click', function(event) {
    if (!event.target.closest('.search-box')) {
        const resultsBox = document.getElementById('productSearchResults');
        resultsBox.classList.add('hidden');
    }
});

// Form submission
document.getElementById('invoiceForm').addEventListener('submit', function(e) {
    if (invoiceItems.length === 0) {
        e.preventDefault();
        alert('Please add at least one item to the invoice');
        return;
    }

    const locationId = document.querySelector('select[name="location_id"]').value;
    if (!locationId) {
        e.preventDefault();
        alert('Please select a location');
        return;
    }

    // Clear draft on successful submission
    clearInvoiceDraft();
});
</script>
