<?php
/**
 * Record Payment
 * LandSales Pro - Record a payment for a sale
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];
$errors = [];

// Pre-selected sale
$selectedSaleId = $_GET['sale_id'] ?? $_POST['sale_id'] ?? null;

// Get active sales with balances
$sales = db_fetch_all("SELECT s.*, b.full_name as buyer_name, b.phone as buyer_phone,
    p.plot_number, pr.name as project_name,
    (s.total_price - COALESCE((SELECT SUM(amount) FROM payments WHERE sale_id = s.id AND status = 'confirmed'), 0)) as balance
    FROM sales s
    JOIN buyers b ON s.buyer_id = b.id
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    WHERE s.user_id = ? AND s.status = 'active'
    HAVING balance > 0
    ORDER BY s.sale_date DESC", 'i', [$userId]);

// Get selected sale details
$selectedSale = null;
if ($selectedSaleId) {
    foreach ($sales as $s) {
        if ($s['id'] == $selectedSaleId) {
            $selectedSale = $s;
            break;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $saleId = intval($_POST['sale_id'] ?? 0);
    $amount = floatval($_POST['amount'] ?? 0);
    $paymentDate = $_POST['payment_date'] ?? date('Y-m-d');
    $paymentMethod = $_POST['payment_method'] ?? 'cash';
    $reference = trim($_POST['reference'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

    // Validation
    if (!$saleId) $errors[] = "Please select a sale";
    if ($amount <= 0) $errors[] = "Please enter a valid amount";

    // Get sale and verify ownership
    $sale = null;
    if ($saleId && empty($errors)) {
        $sale = db_fetch_one("SELECT s.*,
            (s.total_price - COALESCE((SELECT SUM(amount) FROM payments WHERE sale_id = s.id AND status = 'confirmed'), 0)) as balance
            FROM sales s WHERE s.id = ? AND s.user_id = ? AND s.status = 'active'", 'ii', [$saleId, $userId]);

        if (!$sale) {
            $errors[] = "Invalid sale selected";
        } elseif ($amount > $sale['balance']) {
            $errors[] = "Amount exceeds remaining balance of TZS " . number_format($sale['balance']);
        }
    }

    if (empty($errors)) {
        // Generate payment number
        $year = date('Y');
        $lastPayment = db_fetch_one("SELECT payment_number FROM payments WHERE user_id = ? AND payment_number LIKE ? ORDER BY id DESC LIMIT 1",
            'is', [$userId, "PY{$year}%"]);
        if ($lastPayment) {
            $lastNum = intval(substr($lastPayment['payment_number'], -4));
            $paymentNumber = "PY{$year}" . str_pad($lastNum + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $paymentNumber = "PY{$year}0001";
        }

        // Insert payment
        $sql = "INSERT INTO payments (user_id, sale_id, payment_number, amount, payment_date, payment_method, reference, notes, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'confirmed')";

        if (db_execute($sql, 'iisdsss', [$userId, $saleId, $paymentNumber, $amount, $paymentDate, $paymentMethod, $reference ?: null, $notes ?: null])) {
            $paymentId = db_last_id();

            // Check if sale is fully paid and mark as completed
            $newBalance = $sale['balance'] - $amount;
            if ($newBalance <= 0) {
                db_execute("UPDATE sales SET status = 'completed' WHERE id = ?", 'i', [$saleId]);
            }

            // Update payment schedule if exists
            $nextSchedule = db_fetch_one("SELECT id FROM payment_schedule WHERE sale_id = ? AND status = 'pending' ORDER BY installment_number LIMIT 1", 'i', [$saleId]);
            if ($nextSchedule) {
                db_execute("UPDATE payment_schedule SET status = 'paid', paid_date = ? WHERE id = ?", 'si', [$paymentDate, $nextSchedule['id']]);
            }

            logActivity('payment_recorded', "Recorded payment {$paymentNumber} of TZS " . number_format($amount));
            setFlashMessage('success', "Payment {$paymentNumber} recorded successfully!");
            header('Location: receipt.php?id=' . $paymentId);
            exit;
        } else {
            $errors[] = "Failed to record payment. Please try again.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Record Payment - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Record Payment</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <div class="form-container">
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <?php if (empty($sales)): ?>
                <div class="alert alert-warning">
                    <i class="fas fa-info-circle"></i>
                    <span>No active sales with pending balance found. <a href="../sales/create.php">Record a sale first</a></span>
                </div>
                <?php else: ?>

                <form method="POST" class="card" id="paymentForm">
                    <div class="card-header">
                        <h3><i class="fas fa-money-bill-wave"></i> Payment Details</h3>
                    </div>
                    <div class="card-body">
                        <!-- Sale Selection - Searchable Autocomplete -->
                        <div class="form-group">
                            <label for="sale_search">Search Sale *</label>
                            <div class="autocomplete-wrapper">
                                <input type="text" id="sale_search" class="form-control"
                                       placeholder="Type sale number, buyer name, phone, or plot..."
                                       autocomplete="off"
                                       value="<?php echo $selectedSale ? htmlspecialchars($selectedSale['sale_number'] . ' - ' . $selectedSale['buyer_name'] . ' - Plot ' . $selectedSale['plot_number']) : ''; ?>">
                                <input type="hidden" name="sale_id" id="sale_id" value="<?php echo $selectedSaleId ?? ''; ?>" required>
                                <div class="autocomplete-dropdown" id="saleDropdown"></div>
                                <?php if ($selectedSale): ?>
                                <button type="button" class="clear-selection" onclick="clearSaleSelection()" title="Clear selection">
                                    <i class="fas fa-times"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                            <small class="form-text">Search by sale number, buyer name, phone number, or plot number</small>
                        </div>

                        <!-- Sale Info Preview -->
                        <div class="sale-preview" id="salePreview" style="<?php echo $selectedSale ? '' : 'display: none;'; ?>">
                            <div class="preview-row">
                                <div class="preview-item">
                                    <span class="preview-label">Buyer</span>
                                    <span class="preview-value" id="previewBuyer"><?php echo $selectedSale ? htmlspecialchars($selectedSale['buyer_name']) : ''; ?></span>
                                </div>
                                <div class="preview-item">
                                    <span class="preview-label">Plot</span>
                                    <span class="preview-value" id="previewPlot"><?php echo $selectedSale ? htmlspecialchars($selectedSale['plot_number']) : ''; ?></span>
                                </div>
                                <div class="preview-item">
                                    <span class="preview-label">Project</span>
                                    <span class="preview-value" id="previewProject"><?php echo $selectedSale ? htmlspecialchars($selectedSale['project_name']) : ''; ?></span>
                                </div>
                            </div>
                            <div class="balance-info">
                                <div class="balance-item">
                                    <span>Total Price:</span>
                                    <span id="previewTotal">TZS <?php echo $selectedSale ? number_format($selectedSale['total_price']) : '0'; ?></span>
                                </div>
                                <div class="balance-item highlight">
                                    <span>Outstanding Balance:</span>
                                    <span id="previewBalance">TZS <?php echo $selectedSale ? number_format($selectedSale['balance']) : '0'; ?></span>
                                </div>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="amount">Payment Amount (TZS) *</label>
                                <input type="number" name="amount" id="amount" class="form-control"
                                       value="<?php echo $_POST['amount'] ?? ($selectedSale['balance'] ?? ''); ?>"
                                       placeholder="0" min="1" required>
                                <small class="form-text">
                                    <button type="button" class="link-btn" onclick="fillBalance()">Pay full balance</button>
                                </small>
                            </div>
                            <div class="form-group">
                                <label for="payment_date">Payment Date *</label>
                                <input type="date" name="payment_date" id="payment_date" class="form-control"
                                       value="<?php echo $_POST['payment_date'] ?? date('Y-m-d'); ?>" required>
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Payment Method *</label>
                            <div class="method-options">
                                <label class="method-option">
                                    <input type="radio" name="payment_method" value="cash"
                                           <?php echo ($_POST['payment_method'] ?? 'cash') === 'cash' ? 'checked' : ''; ?>>
                                    <span class="method-label">
                                        <i class="fas fa-money-bill-wave"></i>
                                        <span>Cash</span>
                                    </span>
                                </label>
                                <label class="method-option">
                                    <input type="radio" name="payment_method" value="bank"
                                           <?php echo ($_POST['payment_method'] ?? '') === 'bank' ? 'checked' : ''; ?>>
                                    <span class="method-label">
                                        <i class="fas fa-university"></i>
                                        <span>Bank Transfer</span>
                                    </span>
                                </label>
                                <label class="method-option">
                                    <input type="radio" name="payment_method" value="mobile"
                                           <?php echo ($_POST['payment_method'] ?? '') === 'mobile' ? 'checked' : ''; ?>>
                                    <span class="method-label">
                                        <i class="fas fa-mobile-alt"></i>
                                        <span>Mobile Money</span>
                                    </span>
                                </label>
                                <label class="method-option">
                                    <input type="radio" name="payment_method" value="cheque"
                                           <?php echo ($_POST['payment_method'] ?? '') === 'cheque' ? 'checked' : ''; ?>>
                                    <span class="method-label">
                                        <i class="fas fa-money-check"></i>
                                        <span>Cheque</span>
                                    </span>
                                </label>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="reference">Reference/Receipt Number</label>
                            <input type="text" name="reference" id="reference" class="form-control"
                                   value="<?php echo htmlspecialchars($_POST['reference'] ?? ''); ?>"
                                   placeholder="e.g., Bank reference, M-Pesa transaction ID">
                        </div>

                        <div class="form-group">
                            <label for="notes">Notes</label>
                            <textarea name="notes" id="notes" class="form-control" rows="2"
                                      placeholder="Additional notes..."><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                        </div>
                    </div>

                    <div class="card-footer">
                        <a href="index.php" class="btn btn-outline">Cancel</a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-check"></i> Record Payment
                        </button>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .form-container { max-width: 600px; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; align-items: flex-start; gap: 0.75rem; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
        .alert-warning { background: #fef3c7; border: 1px solid #fcd34d; color: #92400e; }
        .alert ul { margin: 0; padding-left: 1rem; }
        .alert a { color: inherit; font-weight: 500; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1.25rem 1.5rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; }
        .card-header h3 { margin: 0; font-size: 1rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .card-body { padding: 1.5rem; }
        .card-footer { padding: 1rem 1.5rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; gap: 1rem; }

        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .form-group { margin-bottom: 1.25rem; }
        .form-group:last-child { margin-bottom: 0; }
        .form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; font-size: 0.875rem; }
        .form-control { width: 100%; padding: 0.75rem 1rem; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 0.9rem; transition: all 0.2s; box-sizing: border-box; }
        .form-control:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        textarea.form-control { resize: vertical; min-height: 70px; }
        .form-text { font-size: 0.8rem; color: #94a3b8; margin-top: 0.25rem; }

        .link-btn { background: none; border: none; color: #667eea; cursor: pointer; font-size: 0.8rem; padding: 0; text-decoration: underline; }

        /* Autocomplete Styles */
        .autocomplete-wrapper {
            position: relative;
        }
        .autocomplete-wrapper .form-control {
            padding-right: 2.5rem;
        }
        .clear-selection {
            position: absolute;
            right: 0.75rem;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #94a3b8;
            cursor: pointer;
            padding: 0.25rem;
            font-size: 0.875rem;
        }
        .clear-selection:hover {
            color: #ef4444;
        }
        .autocomplete-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
            max-height: 300px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
        }
        .autocomplete-dropdown.show {
            display: block;
        }
        .autocomplete-item {
            padding: 0.75rem 1rem;
            cursor: pointer;
            border-bottom: 1px solid #f1f5f9;
            transition: background 0.15s;
        }
        .autocomplete-item:last-child {
            border-bottom: none;
        }
        .autocomplete-item:hover,
        .autocomplete-item.active {
            background: #f8fafc;
        }
        .autocomplete-item .sale-main {
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        .autocomplete-item .sale-details {
            font-size: 0.8rem;
            color: #64748b;
        }
        .autocomplete-item .sale-balance {
            float: right;
            font-weight: 600;
            color: #16a34a;
        }
        .autocomplete-no-results {
            padding: 1rem;
            text-align: center;
            color: #94a3b8;
            font-size: 0.875rem;
        }
        .autocomplete-loading {
            padding: 1rem;
            text-align: center;
            color: #64748b;
        }

        .sale-preview {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border: 1px solid #86efac;
            border-radius: 10px;
            padding: 1rem 1.25rem;
            margin-bottom: 1.25rem;
        }
        .preview-row { display: flex; gap: 1.5rem; margin-bottom: 0.75rem; flex-wrap: wrap; }
        .preview-item { }
        .preview-label { font-size: 0.7rem; color: #16a34a; display: block; text-transform: uppercase; letter-spacing: 0.5px; }
        .preview-value { font-weight: 600; color: #166534; }
        .balance-info { padding-top: 0.75rem; border-top: 1px solid #86efac; }
        .balance-item { display: flex; justify-content: space-between; font-size: 0.9rem; padding: 0.25rem 0; }
        .balance-item.highlight { font-weight: 700; color: #16a34a; font-size: 1rem; }

        .method-options { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.75rem; }
        .method-option input { display: none; }
        .method-label {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.5rem;
            padding: 1rem;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s;
            text-align: center;
        }
        .method-label i { font-size: 1.25rem; color: #64748b; }
        .method-label span { font-size: 0.75rem; color: #64748b; font-weight: 500; }
        .method-option input:checked + .method-label {
            border-color: #667eea;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
        }
        .method-option input:checked + .method-label i,
        .method-option input:checked + .method-label span { color: #667eea; }

        @media (max-width: 768px) {
            .form-row { grid-template-columns: 1fr; }
            .method-options { grid-template-columns: repeat(2, 1fr); }
        }

        @media (max-width: 576px) {
            .card-footer { flex-direction: column-reverse; }
            .card-footer .btn { width: 100%; justify-content: center; }
        }
    </style>

    <script>
        // Autocomplete state
        let searchTimeout = null;
        let selectedSaleData = <?php echo $selectedSale ? json_encode([
            'id' => $selectedSale['id'],
            'buyer_name' => $selectedSale['buyer_name'],
            'plot_number' => $selectedSale['plot_number'],
            'project_name' => $selectedSale['project_name'],
            'total_price' => $selectedSale['total_price'],
            'balance' => $selectedSale['balance']
        ]) : 'null'; ?>;

        function formatNumber(num) {
            return Math.round(num).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }

        function updateSalePreview(sale) {
            const preview = document.getElementById('salePreview');
            if (sale) {
                document.getElementById('previewBuyer').textContent = sale.buyer_name;
                document.getElementById('previewPlot').textContent = 'Plot ' + sale.plot_number;
                document.getElementById('previewProject').textContent = sale.project_name;
                document.getElementById('previewTotal').textContent = 'TZS ' + formatNumber(sale.total_price);
                document.getElementById('previewBalance').textContent = 'TZS ' + formatNumber(sale.balance);
                document.getElementById('amount').value = Math.round(sale.balance);
                preview.style.display = 'block';
            } else {
                preview.style.display = 'none';
            }
        }

        function selectSale(sale) {
            selectedSaleData = sale;
            document.getElementById('sale_id').value = sale.id;
            document.getElementById('sale_search').value = sale.sale_number + ' - ' + sale.buyer_name + ' - Plot ' + sale.plot_number;
            document.getElementById('saleDropdown').classList.remove('show');
            updateSalePreview(sale);

            // Add clear button if not exists
            const wrapper = document.querySelector('.autocomplete-wrapper');
            if (!wrapper.querySelector('.clear-selection')) {
                const clearBtn = document.createElement('button');
                clearBtn.type = 'button';
                clearBtn.className = 'clear-selection';
                clearBtn.innerHTML = '<i class="fas fa-times"></i>';
                clearBtn.onclick = clearSaleSelection;
                clearBtn.title = 'Clear selection';
                wrapper.appendChild(clearBtn);
            }
        }

        function clearSaleSelection() {
            selectedSaleData = null;
            document.getElementById('sale_id').value = '';
            document.getElementById('sale_search').value = '';
            document.getElementById('amount').value = '';
            document.getElementById('salePreview').style.display = 'none';

            const clearBtn = document.querySelector('.clear-selection');
            if (clearBtn) clearBtn.remove();

            document.getElementById('sale_search').focus();
        }

        function fillBalance() {
            if (selectedSaleData) {
                document.getElementById('amount').value = Math.round(selectedSaleData.balance);
            }
        }

        async function searchSales(query) {
            const dropdown = document.getElementById('saleDropdown');

            if (query.length < 1) {
                dropdown.classList.remove('show');
                return;
            }

            dropdown.innerHTML = '<div class="autocomplete-loading"><i class="fas fa-spinner fa-spin"></i> Searching...</div>';
            dropdown.classList.add('show');

            try {
                const response = await fetch('<?php echo SITE_URL; ?>/ajax/search-sales.php?q=' + encodeURIComponent(query) + '&with_balance=1');
                const data = await response.json();

                if (data.success && data.results.length > 0) {
                    dropdown.innerHTML = data.results.map(sale => `
                        <div class="autocomplete-item" onclick='selectSale(${JSON.stringify(sale)})'>
                            <div class="sale-main">
                                ${escapeHtml(sale.sale_number)} - ${escapeHtml(sale.buyer_name)}
                                <span class="sale-balance">TZS ${sale.balance_formatted}</span>
                            </div>
                            <div class="sale-details">
                                ${escapeHtml(sale.project_name)} - Plot ${escapeHtml(sale.plot_number)} | ${sale.buyer_phone}
                            </div>
                        </div>
                    `).join('');
                } else {
                    dropdown.innerHTML = '<div class="autocomplete-no-results">No sales found with pending balance</div>';
                }
            } catch (error) {
                console.error('Search error:', error);
                dropdown.innerHTML = '<div class="autocomplete-no-results">Error searching sales</div>';
            }
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.getElementById('sale_search');
            const dropdown = document.getElementById('saleDropdown');

            // Update preview if pre-selected
            if (selectedSaleData) {
                updateSalePreview(selectedSaleData);
            }

            // Search on input
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                const query = this.value.trim();

                // If user cleared the field, clear selection
                if (!query && selectedSaleData) {
                    clearSaleSelection();
                }

                searchTimeout = setTimeout(() => searchSales(query), 300);
            });

            // Show dropdown on focus if has value
            searchInput.addEventListener('focus', function() {
                if (this.value.trim().length >= 1 && !selectedSaleData) {
                    searchSales(this.value.trim());
                }
            });

            // Hide dropdown when clicking outside
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.autocomplete-wrapper')) {
                    dropdown.classList.remove('show');
                }
            });

            // Keyboard navigation
            searchInput.addEventListener('keydown', function(e) {
                const items = dropdown.querySelectorAll('.autocomplete-item');
                const activeItem = dropdown.querySelector('.autocomplete-item.active');
                let activeIndex = Array.from(items).indexOf(activeItem);

                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    if (activeItem) activeItem.classList.remove('active');
                    activeIndex = (activeIndex + 1) % items.length;
                    if (items[activeIndex]) items[activeIndex].classList.add('active');
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    if (activeItem) activeItem.classList.remove('active');
                    activeIndex = activeIndex <= 0 ? items.length - 1 : activeIndex - 1;
                    if (items[activeIndex]) items[activeIndex].classList.add('active');
                } else if (e.key === 'Enter' && activeItem) {
                    e.preventDefault();
                    activeItem.click();
                } else if (e.key === 'Escape') {
                    dropdown.classList.remove('show');
                }
            });
        });
    </script>
</body>
</html>
