<?php
/**
 * Add Purchase Form - Plain PHP version
 * Uses $suppliers and $locations from PurchaseController::create()
 */
?>
<div class="page-header">
    <div>
        <a href="<?php echo APP_URL; ?>/purchases" class="btn btn-ghost btn-sm mb-4" style="padding-left:0;">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>
            Back to Purchases
        </a>
    </div>
    <h1>Add Purchase</h1>
    <div class="page-subtitle">Add new inventory stock from a supplier.</div>
</div>

<div class="grid-2 mb-6">
    <div class="card">
        <div class="card-header"><h3 class="card-title">Order Details</h3></div>

        <div class="grid-2 gap-4 mb-6">
            <div class="form-group">
                <label class="form-label">Supplier <span class="required">*</span></label>
                <select id="supplier_id" class="form-control" required>
                    <option value="">Select Supplier...</option>
                    <?php foreach ($suppliers as $s): ?>
                    <option value="<?php echo $s['id']; ?>"><?= e($s['name']); ?></option>
                    <?php endforeach; ?>
                </select>
                <a href="<?php echo APP_URL; ?>/suppliers" class="text-xs text-primary mt-1 inline-block">+ Add Supplier</a>
            </div>

            <div class="form-group">
                <label class="form-label">Delivery Location <span class="required">*</span></label>
                <select id="location_id" class="form-control" required>
                    <option value="">Select Location...</option>
                    <?php foreach ($locations as $l): ?>
                        <option value="<?php echo $l['id']; ?>" <?php echo (($settings['default_location_id'] ?? '') == $l['id'] || !empty($l['is_default'])) ? 'selected' : ''; ?>><?= e($l['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <div class="search-box mb-6 w-full">
            <div style="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: 12px; top: 50%; transform: translateY(-50%); color: #999;"><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="product-search" class="form-control" placeholder="Search by name, SKU, or barcode to add items..." autocomplete="off" oninput="searchProducts(this.value)" style="padding-left: 40px;">
                </div>
                <button type="button" id="btn-scan-barcode" onclick="openBarcodeScanner()" style="padding: 10px 16px; border: 1px solid #ddd; background: #fff; border-radius: 6px; font-size: 0.9rem; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; gap: 6px; color: #007bff;">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 3v18h18"/><path d="M7 7h10"/><path d="M7 12h10"/><path d="M7 17h10"/></svg>
                    Scan
                </button>
            </div>
            <div id="search-results" class="search-dropdown hidden" style="padding: 8px;"></div>
        </div>

        <div class="table-wrapper mb-6">
            <table id="purchase-items">
                <thead>
                    <tr>
                        <th>Product</th>
                        <th class="text-right" style="width: 120px;">SKU</th>
                        <th class="text-right" style="width: 120px;">Unit Cost</th>
                        <th class="text-center" style="width: 80px;">Qty</th>
                        <th style="width: 120px;">Batch No</th>
                        <th style="width: 120px;">Expiry Date</th>
                        <th class="text-right" style="width: 120px;">Total</th>
                        <th style="width: 60px;">Actions</th>
                    </tr>
                </thead>
                <tbody id="item-list">
                    <!-- Items added dynamically by JS -->
                </tbody>
                <tfoot>
                    <tr style="background: var(--bg-raised);">
                        <td colspan="3" class="text-right font-bold py-4">Subtotal:</td>
                        <td class="text-right font-bold py-4" id="table-subtotal"><?= $currencySymbol ?>0.00</td>
                        <td colspan="2"></td>
                    </tr>
                </tfoot>
            </table>
        </div>

        <div class="form-group">
            <label class="form-label text-xs">Notes / Remarks</label>
            <textarea id="notes" class="form-control" rows="2" placeholder="e.g. Terms of payment, Delivery instructions..."></textarea>
        </div>
    </div>

    <div class="card">
        <div class="card-header"><h3 class="card-title">Summary &amp; Payment</h3></div>
        <div class="flex justify-between py-2 border-b border-soft">
            <span class="text-muted">Item Count</span>
            <span id="summary-count">0</span>
        </div>

        <div class="form-group mt-4">
            <label class="form-label text-xs">Discount Amount</label>
            <div class="input-group">
                <span class="input-group-text"><?= $currencySymbol ?></span>
                <input type="number" id="discount" class="form-control" value="0.00" onchange="calculateTotals()">
            </div>
        </div>

        <div class="form-group mt-2">
            <label class="form-label text-xs">Tax Amount</label>
            <div class="input-group">
                <span class="input-group-text"><?= $currencySymbol ?></span>
                <input type="number" id="tax" class="form-control" value="0.00" onchange="calculateTotals()">
            </div>
        </div>

        <div class="flex justify-between py-4 mt-4 border-t-2 border-primary" style="font-size: 1.4rem; font-weight: 800;">
            <span>Total</span>
            <span id="summary-total"><?= $currencySymbol ?>0.00</span>
        </div>

        <div class="form-group mt-4">
            <label class="form-label text-xs">Payment Method</label>
            <select id="payment_method" class="form-control">
                <?php
                $paymentMethods = json_decode($settings['payment_methods'] ?? '["cash","card","transfer","cheque","credit","other"]', true) ?: ['cash', 'card', 'transfer', 'cheque', 'credit', 'other'];
                $paymentMethodLabels = json_decode($settings['payment_method_labels'] ?? '{}', true) ?: [];
                $defaultPaymentMethod = $settings['default_payment_method'] ?? 'cash';
                $defaultMethods = ['cash' => 'Cash', 'card' => 'Card', 'transfer' => 'Bank Transfer', 'cheque' => 'Cheque', 'credit' => 'Credit', 'other' => 'Other'];
                foreach ($paymentMethods as $method):
                    $label = $paymentMethodLabels[$method] ?? ($defaultMethods[$method] ?? ucfirst($method));
                ?>
                <option value="<?= $method ?>" <?= $method === $defaultPaymentMethod ? 'selected' : '' ?>><?= e($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group mt-4">
            <label class="form-label text-xs">Payment Status</label>
            <select id="payment_status" class="form-control" readonly>
                <option value="paid">Paid in Full</option>
                <option value="partial">Partial Payment</option>
                <option value="due">Due</option>
                <option value="credit">Credit</option>
            </select>
            <div class="form-hint">Payment status is calculated automatically based on amount paid vs total</div>
        </div>

        <div class="form-group mt-4">
            <label class="form-label text-xs">Amount Paid</label>
            <div class="input-group">
                <span class="input-group-text"><?= $currencySymbol ?></span>
                <input type="number" id="paid_amount" class="form-control" value="0.00" onchange="updatePaymentStatus()">
            </div>
        </div>

        <button class="btn btn-primary w-full mt-6 py-4 font-bold" onclick="submitPurchase()">Save Purchase</button>
    </div>
</div>

<!-- HTML5-QRCode Library for barcode scanning -->
<script src="<?= APP_URL ?>/assets/js/html5-qrcode.min.js"></script>

<!-- 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; display: none; 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; display: none; 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;
}

/* Search dropdown styling */
.search-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #ddd;
    border-radius: 6px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    max-height: 300px;
    overflow-y: auto;
    z-index: 9999;
    pointer-events: auto;
}

.search-dropdown.hidden {
    display: none;
}

.search-result-item {
    padding: 10px 12px;
    cursor: pointer;
    border-bottom: 1px solid #eee;
    transition: background 0.2s;
    pointer-events: auto;
    user-select: none;
}

.search-result-item:hover {
    background: #f5f5f5;
}

.search-result-item:last-child {
    border-bottom: none;
}

.search-result-name {
    font-weight: 600;
    color: #333;
    pointer-events: none;
}

.search-result-details {
    display: flex;
    gap: 12px;
    margin-top: 4px;
    pointer-events: none;
}

.search-box {
    position: relative;
}

/* Responsive Design */
@media (max-width: 1024px) {
    .grid-2 {
        grid-template-columns: 1fr;
        gap: 1.5rem;
    }

    .card {
        margin-bottom: 1rem;
    }

    #purchase-items {
        font-size: 0.85rem;
    }

    #purchase-items th,
    #purchase-items td {
        padding: 8px 6px;
    }
}

@media (max-width: 768px) {
    .grid-2 {
        grid-template-columns: 1fr;
    }

    .grid-2 > .card {
        margin-bottom: 1rem;
    }

    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 1rem;
    }

    .page-header .flex {
        width: 100%;
        justify-content: flex-start;
    }

    #purchase-items {
        font-size: 0.75rem;
    }

    #purchase-items thead {
        display: none;
    }

    #purchase-items,
    #purchase-items tbody,
    #purchase-items tr,
    #purchase-items td {
        display: block;
        width: 100%;
    }

    #purchase-items tbody tr {
        border-bottom: 1px solid #ddd;
        padding: 12px 0;
        margin-bottom: 8px;
    }

    #purchase-items td {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 0;
        border: none;
        text-align: right;
    }

    #purchase-items td::before {
        content: attr(data-label);
        font-weight: 600;
        text-align: left;
        color: #666;
        flex: 1;
    }

    #purchase-items td input,
    #purchase-items td button {
        flex: 0 0 auto;
        margin-left: 12px;
    }

    .search-box .flex {
        flex-direction: column;
        gap: 8px;
    }

    .search-box input {
        width: 100% !important;
    }

    #btn-scan-barcode {
        width: 100%;
        justify-content: center;
    }

    .modal {
        width: 95% !important;
        max-height: 90vh !important;
    }

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

@media (max-width: 480px) {
    .grid-2 > .card {
        padding: 1rem;
    }

    .form-group {
        margin-bottom: 1rem;
    }

    .form-control {
        font-size: 14px;
        padding: 8px 12px;
    }

    .btn {
        padding: 8px 16px;
        font-size: 0.85rem;
    }

    .card-header {
        padding: 1rem;
    }

    .card-title {
        font-size: 1rem;
    }
}
</style>

<script>
let products = <?php echo json_encode($products ?? []); ?>;
let items = [];
let paymentMethods = <?php echo json_encode($paymentMethods ?? ['cash', 'card', 'transfer', 'cheque', 'credit', 'other']); ?>;
let paymentMethodLabels = <?php echo json_encode($paymentMethodLabels ?? []); ?>;
let defaultPaymentMethod = <?php echo json_encode($defaultPaymentMethod ?? 'cash'); ?>;
let currencySymbol = '<?= $currencySymbol ?>';

// 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) {
    const searchInput = document.getElementById('product-search');
    searchInput.value = barcode;
    searchProducts(barcode);
}

function searchProducts(query) {
    const results = document.getElementById('search-results');
    results.innerHTML = '';

    if (query.length < 2) {
        results.classList.add('hidden');
        return;
    }

    const filtered = products.filter(p =>
        p.name.toLowerCase().includes(query.toLowerCase()) ||
        p.sku.toLowerCase().includes(query.toLowerCase()) ||
        (p.barcode && p.barcode.toLowerCase().includes(query.toLowerCase()))
    );

    if (filtered.length > 0) {
        results.innerHTML = filtered.map(p => `
            <div class="search-result-item" data-id="${p.id}" data-name="${p.name.replace(/'/g, "\\'")}" data-cost="${p.cost_price}" data-sku="${p.sku}" data-batch-tracking="${p.batch_tracking ? 1 : 0}" data-serial-tracking="${p.serial_tracking ? 1 : 0}" data-batch-no="${p.batch_no || ''}" data-expiry-date="${p.expiry_date || ''}">
                <div class="search-result-info">
                    <div class="search-result-name">${p.name}</div>
                    <div class="search-result-details">
                        <div class="text-xs text-muted">SKU: ${p.sku || '-'}</div>
                        <div class="text-xs text-muted">Cost: ${currencySymbol}${p.cost_price}</div>
                        ${p.batch_tracking ? `<div class="text-xs text-info">Batch: ${p.batch_no || '-'}</div>` : ''}
                        ${p.expiry_date ? `<div class="text-xs text-warning">Expiry: ${p.expiry_date}</div>` : ''}
                    </div>
                </div>
            </div>
        `).join('');
        results.classList.remove('hidden');
    } else {
        results.classList.add('hidden');
    }
}

function selectProduct(id, name, cost, sku, batchTracking, serialTracking, batchNo, expiryDate) {
    const existingItemIndex = items.findIndex(item => item.product_id === id);
    if (existingItemIndex > -1) {
        // Increment quantity and move to top
        const item = items[existingItemIndex];
        item.quantity += 1;
        item.total = item.quantity * item.cost_price;
        items.splice(existingItemIndex, 1);
        items.unshift(item);
    } else {
        // Add new item to top
        items.unshift({
            id: items.length + 1,
            product_id: id,
            name: name,
            sku: sku,
            cost_price: cost,
            quantity: 1,
            batch_tracking: batchTracking,
            serial_tracking: serialTracking,
            batch_no: batchNo || '',
            expiry_date: expiryDate || '',
            total: cost
        });
    }
    renderItems();
    calculateTotals();
    document.getElementById('product-search').value = '';
    document.getElementById('search-results').classList.add('hidden');
}

function renderItems() {
    const tbody = document.getElementById('item-list');
    tbody.innerHTML = items.map((item, index) => `
        <tr>
            <td>
                <div class="font-bold">${item.name}</div>
            </td>
            <td class="text-right">${item.sku || '-'}</td>
            <td class="text-right">${currencySymbol}<input type="number" class="form-control text-right" style="width:100px" value="${item.cost_price.toFixed(2)}" onchange="items[${index}].cost_price = parseFloat(this.value); items[${index}].total = items[${index}].quantity * items[${index}].cost_price; renderItems(); calculateTotals();"></td>
            <td class="text-center"><input type="number" class="form-control text-center" style="width:60px" value="${item.quantity}" onchange="items[${index}].quantity = parseInt(this.value); items[${index}].total = items[${index}].quantity * items[${index}].cost_price; renderItems(); calculateTotals();"></td>
            <td><input type="text" class="form-control" style="width:100px" value="${item.batch_no}" onchange="items[${index}].batch_no = this.value"></td>
            <td><input type="date" class="form-control" value="${item.expiry_date}" onchange="items[${index}].expiry_date = this.value"></td>
            <td class="text-right">${currencySymbol}${item.total.toFixed(2)}</td>
            <td><button class="text-danger" onclick="items.splice(${index},1); renderItems(); calculateTotals();">×</button></td>
        </tr>
    `).join('');
    document.getElementById('summary-count').textContent = items.length;
}

function calculateTotals() {
    const subtotal = items.reduce((sum, item) => sum + (item.cost_price * item.quantity), 0);
    const discount = parseFloat(document.getElementById('discount').value) || 0;
    const tax = parseFloat(document.getElementById('tax').value) || 0;
    const total = subtotal - discount + tax;

    document.getElementById('summary-count').textContent = items.length;
    document.getElementById('table-subtotal').textContent = currencySymbol + subtotal.toFixed(2);
    document.getElementById('discount').value = discount.toFixed(2);
    document.getElementById('tax').value = tax.toFixed(2);
    document.getElementById('summary-total').textContent = currencySymbol + total.toFixed(2);
    
    // Update payment status based on amount paid
    updatePaymentStatus();
}

function updatePaymentStatus() {
    const amountPaid = parseFloat(document.getElementById('paid_amount').value) || 0;
    const total = parseFloat(document.getElementById('summary-total').textContent.replace(currencySymbol,''));
    const paymentStatusSelect = document.getElementById('payment_status');
    
    let paymentStatus = 'due';
    if (amountPaid >= total) {
        paymentStatus = 'paid';
    } else if (amountPaid > 0) {
        paymentStatus = 'partial';
    }
    
    paymentStatusSelect.value = paymentStatus;
}

async function submitPurchase() {
    if (items.length === 0) {
        alert('Add at least one item');
        return;
    }
    if (!document.getElementById('supplier_id').value || !document.getElementById('location_id').value) {
        alert('Please select supplier and location');
        return;
    }
    
    const amountPaid = parseFloat(document.getElementById('paid_amount').value) || 0;
    const total = parseFloat(document.getElementById('summary-total').textContent.replace(currencySymbol,''));
    
    // Calculate payment status based on amount paid
    let paymentStatus = 'due';
    if (amountPaid >= total) {
        paymentStatus = 'paid';
    } else if (amountPaid > 0) {
        paymentStatus = 'partial';
    }
    
    const data = {
        supplier_id: document.getElementById('supplier_id').value,
        location_id: document.getElementById('location_id').value,
        items: items,
        subtotal: items.reduce((sum, item) => sum + item.total, 0),
        discount_amount: parseFloat(document.getElementById('discount').value) || 0,
        tax_amount: parseFloat(document.getElementById('tax').value) || 0,
        total: total,
        amount_paid: amountPaid,
        payment_method: document.getElementById('payment_method').value,
        payment_status: paymentStatus,
        notes: document.getElementById('notes').value
    };
    
    try {
        const response = await fetch('', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo Security::generateCsrfToken(); ?>'
            },
            body: JSON.stringify(data)
        });
        const result = await response.json();
        if (result.success) {
            window.location = `<?php echo APP_URL; ?>/purchases`;
        } else {
            alert('Error: ' + (result.error || 'Unknown error'));
        }
    } catch (e) {
        alert('Error submitting purchase');
    }
}

document.addEventListener('click', (e) => {
    // Handle search result item clicks
    const searchResultItem = e.target.closest('.search-result-item');
    if (searchResultItem) {
        const id = parseInt(searchResultItem.dataset.id);
        const name = searchResultItem.dataset.name;
        const cost = parseFloat(searchResultItem.dataset.cost);
        const sku = searchResultItem.dataset.sku;
        const batchTracking = parseInt(searchResultItem.dataset.batchTracking);
        const serialTracking = parseInt(searchResultItem.dataset.serialTracking);
        const batchNo = searchResultItem.dataset.batchNo;
        const expiryDate = searchResultItem.dataset.expiryDate;

        selectProduct(id, name, cost, sku, batchTracking, serialTracking, batchNo, expiryDate);
        return;
    }

    // Hide search results when clicking outside search box
    if (!e.target.closest('.search-box')) {
        document.getElementById('search-results').classList.add('hidden');
    }
});
</script>
