<?php
include('includes/db.php');


// Generate invoice number
function generateInvoiceNumber($conn) {
    $year = date('Y');
    $month = date('m');
    
    // Get last invoice number for this month
    $query = "SELECT invoice_number FROM invoices 
              WHERE invoice_number LIKE 'INV-{$year}{$month}-%' 
              ORDER BY id DESC LIMIT 1";
    $result = mysqli_query($conn, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $last_number = explode('-', $row['invoice_number']);
        $sequence = intval(end($last_number)) + 1;
    } else {
        $sequence = 1001;
    }
    
    return "INV-{$year}{$month}-" . str_pad($sequence, 4, '0', STR_PAD_LEFT);
}

// Fetch customers for dropdown
$customers = [];
$customer_query = "SELECT id, name, phone, email, address, gst_no, pan_no FROM customers ORDER BY name ASC";
$customer_result = mysqli_query($conn, $customer_query);
if ($customer_result) {
    while ($row = mysqli_fetch_assoc($customer_result)) {
        $customers[] = $row;
    }
}

// Fetch products for search
$products = [];
$product_query = "SELECT id, product_name, customer_price, unit_of_measure, quantity as stock_quantity FROM products WHERE quantity > 0 ORDER BY product_name ASC";
$product_result = mysqli_query($conn, $product_query);
if ($product_result) {
    while ($row = mysqli_fetch_assoc($product_result)) {
        $products[] = $row;
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        mysqli_begin_transaction($conn);
        
        // Customer details
        $customer_id = isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0;
        $customer_name = mysqli_real_escape_string($conn, $_POST['customer_name'] ?? '');
        $customer_phone = mysqli_real_escape_string($conn, $_POST['customer_phone'] ?? '');
        $customer_email = mysqli_real_escape_string($conn, $_POST['customer_email'] ?? '');
        $customer_address = mysqli_real_escape_string($conn, $_POST['customer_address'] ?? '');
        $customer_gst = mysqli_real_escape_string($conn, $_POST['customer_gst'] ?? '');
        $customer_pan = mysqli_real_escape_string($conn, $_POST['customer_pan'] ?? '');
        
        // If new customer selected, save customer first
        if (isset($_POST['is_new_customer']) && $_POST['is_new_customer'] == '1') {
            $insert_customer = "INSERT INTO customers (name, phone, email, address, gst_no, pan_no) 
                               VALUES ('$customer_name', '$customer_phone', '$customer_email', 
                                       '$customer_address', '$customer_gst', '$customer_pan')";
            mysqli_query($conn, $insert_customer);
            $customer_id = mysqli_insert_id($conn);
        }
        
        // Invoice details
        $invoice_number = generateInvoiceNumber($conn);
        $invoice_date = date('Y-m-d');
        $due_date = date('Y-m-d', strtotime('+30 days'));
        $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method'] ?? 'cash');
        $payment_status = mysqli_real_escape_string($conn, $_POST['payment_status'] ?? 'pending');
        $notes = mysqli_real_escape_string($conn, $_POST['notes'] ?? '');
        
        // Calculate totals from items
        $subtotal = 0;
        $items = json_decode($_POST['items_json'], true);
        
        // Process each item
        foreach ($items as $item) {
            $item_total = floatval($item['quantity']) * floatval($item['price']);
            $subtotal += $item_total;
            
            // Update product stock
            $update_stock = "UPDATE products SET quantity = quantity - " . intval($item['quantity']) . 
                           " WHERE id = " . intval($item['id']);
            mysqli_query($conn, $update_stock);
        }
        
        $discount = floatval($_POST['discount'] ?? 0);
        $tax_amount = floatval($_POST['tax_amount'] ?? 0);
        $shipping_charges = floatval($_POST['shipping_charges'] ?? 0);
        $total = $subtotal - $discount + $tax_amount + $shipping_charges;
        
        // Insert invoice
        $insert_invoice = "INSERT INTO invoices 
                          (invoice_number, customer_id, customer_name, customer_phone, 
                           customer_address, customer_gst, customer_pan, subtotal, discount, 
                           tax_amount, shipping_charges, total, payment_method, payment_status, 
                           notes, invoice_date, due_date) 
                          VALUES 
                          ('$invoice_number', $customer_id, '$customer_name', '$customer_phone',
                           '$customer_address', '$customer_gst', '$customer_pan', $subtotal, $discount,
                           $tax_amount, $shipping_charges, $total, '$payment_method', '$payment_status',
                           '$notes', '$invoice_date', '$due_date')";
        
        if (!mysqli_query($conn, $insert_invoice)) {
            throw new Exception("Failed to create invoice: " . mysqli_error($conn));
        }
        
        $invoice_id = mysqli_insert_id($conn);
        
        // Insert invoice items
        foreach ($items as $item) {
            $product_id = intval($item['id']);
            $product_name = mysqli_real_escape_string($conn, $item['name']);
            $quantity = intval($item['quantity']);
            $unit_price = floatval($item['price']);
            $total_price = $quantity * $unit_price;
            $unit_of_measure = mysqli_real_escape_string($conn, $item['unit']);
            
            $insert_item = "INSERT INTO invoice_items 
                           (invoice_id, product_id, product_name, quantity, unit_price, 
                            total_price, unit_of_measure) 
                           VALUES 
                           ($invoice_id, $product_id, '$product_name', $quantity, $unit_price,
                            $total_price, '$unit_of_measure')";
            mysqli_query($conn, $insert_item);
        }
        
        mysqli_commit($conn);
        
        // Redirect to invoice print page
        header("Location: invoice_print.php?invoice_id=$invoice_id&auto=1");
        exit;
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $_SESSION['error_message'] = "Error: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Bill/Invoice</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .card {
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .section-title {
            border-bottom: 2px solid #007bff;
            padding-bottom: 8px;
            margin-bottom: 20px;
            color: #007bff;
        }
        .product-search {
            position: relative;
        }
        .product-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            max-height: 300px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
        }
        .product-item {
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        .product-item:hover {
            background-color: #f8f9fa;
        }
        .items-table {
            font-size: 14px;
        }
        .items-table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }
        .amount-display {
            background-color: #f8f9fa;
            border-radius: 4px;
            padding: 15px;
            margin-top: 20px;
        }
        .new-customer-form {
            display: none;
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-top: 10px;
        }
        .form-section {
            margin-bottom: 30px;
        }
        .required::after {
            content: " *";
            color: #dc3545;
        }
    </style>
</head>
<body>
<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <h1 class="mb-4">Create New Invoice/Bill</h1>
            
            <?php if (isset($_SESSION['error_message'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form id="billingForm" method="POST" action="billing.php">
                <div class="row">
                    <!-- Customer Section -->
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">Customer Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label required">Customer</label>
                                    <select id="customerSelect" class="form-select" onchange="toggleCustomerForm()">
                                        <option value="">-- Select Customer --</option>
                                        <option value="new">+ Add New Customer</option>
                                        <?php foreach ($customers as $customer): ?>
                                            <option value="<?php echo $customer['id']; ?>" 
                                                    data-name="<?php echo htmlspecialchars($customer['name']); ?>"
                                                    data-phone="<?php echo htmlspecialchars($customer['phone']); ?>"
                                                    data-email="<?php echo htmlspecialchars($customer['email']); ?>"
                                                    data-address="<?php echo htmlspecialchars($customer['address']); ?>"
                                                    data-gst="<?php echo htmlspecialchars($customer['gst_no']); ?>"
                                                    data-pan="<?php echo htmlspecialchars($customer['pan_no']); ?>">
                                                <?php echo htmlspecialchars($customer['name']); ?> 
                                                (<?php echo htmlspecialchars($customer['phone']); ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <input type="hidden" name="customer_id" id="customer_id" value="0">
                                    <input type="hidden" name="is_new_customer" id="is_new_customer" value="0">
                                </div>
                                
                                <div id="newCustomerForm" class="new-customer-form">
                                    <div class="mb-3">
                                        <label class="form-label required">Customer Name</label>
                                        <input type="text" class="form-control" id="customer_name" name="customer_name">
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Phone</label>
                                            <input type="text" class="form-control" id="customer_phone" name="customer_phone">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Email</label>
                                            <input type="email" class="form-control" id="customer_email" name="customer_email">
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">Address</label>
                                        <textarea class="form-control" id="customer_address" name="customer_address" rows="2"></textarea>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">GST No.</label>
                                            <input type="text" class="form-control" id="customer_gst" name="customer_gst">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">PAN No.</label>
                                            <input type="text" class="form-control" id="customer_pan" name="customer_pan">
                                        </div>
                                    </div>
                                </div>
                                
                                <div id="existingCustomerInfo" style="display: none;">
                                    <div class="alert alert-info">
                                        <strong id="selected_customer_name"></strong><br>
                                        <span id="selected_customer_phone"></span><br>
                                        <span id="selected_customer_email"></span><br>
                                        <small>GST: <span id="selected_customer_gst"></span></small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Payment Details -->
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">Payment Details</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label required">Payment Method</label>
                                        <select class="form-select" name="payment_method" required>
                                            <option value="cash" selected>Cash</option>
                                            <option value="card">Card</option>
                                            <option value="bank_transfer">Bank Transfer</option>
                                            <option value="upi">UPI</option>
                                            <option value="cheque">Cheque</option>
                                            <option value="credit">Credit</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Payment Status</label>
                                        <select class="form-select" name="payment_status">
                                            <option value="pending" selected>Pending</option>
                                            <option value="paid">Paid</option>
                                            <option value="partial">Partial</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Notes</label>
                                    <textarea class="form-control" name="notes" rows="2" placeholder="Any special instructions or notes..."></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Product Selection & Cart -->
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header bg-warning text-dark">
                                <h5 class="mb-0">Add Products</h5>
                            </div>
                            <div class="card-body">
                                <div class="product-search mb-4">
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="productSearch" 
                                               placeholder="Search products by name..." autocomplete="off">
                                        <button class="btn btn-primary" type="button" onclick="searchProducts()">
                                            <i class="fas fa-search"></i> Search
                                        </button>
                                    </div>
                                    <div id="productResults" class="product-results"></div>
                                </div>
                                
                                <!-- Selected Items Table -->
                                <div class="table-responsive">
                                    <table class="table table-bordered items-table">
                                        <thead>
                                            <tr>
                                                <th width="5%">#</th>
                                                <th width="35%">Product Name</th>
                                                <th width="10%">Unit</th>
                                                <th width="15%">Price (₹)</th>
                                                <th width="15%">Quantity</th>
                                                <th width="15%">Total (₹)</th>
                                                <th width="5%">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody id="cartItems">
                                            <tr id="emptyCart">
                                                <td colspan="7" class="text-center text-muted py-4">
                                                    No products added. Search and add products above.
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                
                                <!-- Totals Section -->
                                <div class="row mt-4">
                                    <div class="col-md-6">
                                        <div class="amount-display">
                                            <h5>Invoice Summary</h5>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Subtotal:</span>
                                                <strong id="subtotalDisplay">₹ 0.00</strong>
                                                <input type="hidden" name="subtotal" id="subtotal" value="0">
                                            </div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Discount:</span>
                                                <div class="input-group input-group-sm" style="width: 150px;">
                                                    <input type="number" class="form-control" id="discount" 
                                                           name="discount" value="0" min="0" step="0.01" onchange="calculateTotal()">
                                                    <span class="input-group-text">₹</span>
                                                </div>
                                            </div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Tax:</span>
                                                <div class="input-group input-group-sm" style="width: 150px;">
                                                    <input type="number" class="form-control" id="tax_amount" 
                                                           name="tax_amount" value="0" min="0" step="0.01" onchange="calculateTotal()">
                                                    <span class="input-group-text">₹</span>
                                                </div>
                                            </div>
                                            <div class="d-flex justify-content-between mb-2">
                                                <span>Shipping:</span>
                                                <div class="input-group input-group-sm" style="width: 150px;">
                                                    <input type="number" class="form-control" id="shipping_charges" 
                                                           name="shipping_charges" value="0" min="0" step="0.01" onchange="calculateTotal()">
                                                    <span class="input-group-text">₹</span>
                                                </div>
                                            </div>
                                            <hr>
                                            <div class="d-flex justify-content-between">
                                                <h5>Total:</h5>
                                                <h3 id="totalDisplay">₹ 0.00</h3>
                                                <input type="hidden" name="total" id="total" value="0">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="d-grid gap-2 mt-4">
                                            <button type="button" class="btn btn-danger btn-lg" onclick="clearCart()">
                                                <i class="fas fa-trash"></i> Clear All Items
                                            </button>
                                            <button type="submit" class="btn btn-success btn-lg">
                                                <i class="fas fa-file-invoice"></i> Generate Invoice
                                            </button>
                                            <input type="hidden" name="items_json" id="items_json" value="[]">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- JavaScript Libraries -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script>

<script>
// Cart items array
let cartItems = [];
let productList = <?php echo json_encode($products); ?>;

// Search products
function searchProducts() {
    const searchTerm = document.getElementById('productSearch').value.toLowerCase();
    const resultsDiv = document.getElementById('productResults');
    
    if (searchTerm.length < 2) {
        resultsDiv.style.display = 'none';
        return;
    }
    
    const filtered = productList.filter(product => 
        product.product_name.toLowerCase().includes(searchTerm)
    );
    
    if (filtered.length === 0) {
        resultsDiv.innerHTML = '<div class="product-item text-muted">No products found</div>';
        resultsDiv.style.display = 'block';
        return;
    }
    
    let html = '';
    filtered.forEach(product => {
        html += `
            <div class="product-item" onclick="addToCart(${product.id})">
                <strong>${product.product_name}</strong><br>
                <small>Price: ₹${product.customer_price} | Unit: ${product.unit_of_measure} | Stock: ${product.stock_quantity}</small>
            </div>
        `;
    });
    
    resultsDiv.innerHTML = html;
    resultsDiv.style.display = 'block';
}

// Add product to cart
function addToCart(productId) {
    const product = productList.find(p => p.id == productId);
    if (!product) return;
    
    // Check if already in cart
    const existingIndex = cartItems.findIndex(item => item.id == productId);
    if (existingIndex > -1) {
        cartItems[existingIndex].quantity += 1;
        cartItems[existingIndex].total = cartItems[existingIndex].quantity * cartItems[existingIndex].price;
    } else {
        cartItems.push({
            id: product.id,
            name: product.product_name,
            price: parseFloat(product.customer_price),
            unit: product.unit_of_measure,
            quantity: 1,
            total: parseFloat(product.customer_price)
        });
    }
    
    updateCartDisplay();
    document.getElementById('productSearch').value = '';
    document.getElementById('productResults').style.display = 'none';
    document.getElementById('productSearch').focus();
}

// Update cart quantity
function updateQuantity(index, change) {
    const newQty = cartItems[index].quantity + change;
    if (newQty < 1) {
        removeFromCart(index);
        return;
    }
    
    // Check stock availability
    const product = productList.find(p => p.id == cartItems[index].id);
    if (product && newQty > product.stock_quantity) {
        alert(`Only ${product.stock_quantity} units available in stock!`);
        return;
    }
    
    cartItems[index].quantity = newQty;
    cartItems[index].total = newQty * cartItems[index].price;
    updateCartDisplay();
}

// Remove item from cart
function removeFromCart(index) {
    cartItems.splice(index, 1);
    updateCartDisplay();
}

// Clear all items
function clearCart() {
    if (cartItems.length === 0) return;
    if (confirm('Are you sure you want to clear all items?')) {
        cartItems = [];
        updateCartDisplay();
    }
}

// Update cart display
function updateCartDisplay() {
    const cartTable = document.getElementById('cartItems');
    const emptyCart = document.getElementById('emptyCart');
    
    if (cartItems.length === 0) {
        emptyCart.style.display = '';
        cartTable.innerHTML = '<tr id="emptyCart"><td colspan="7" class="text-center text-muted py-4">No products added. Search and add products above.</td></tr>';
    } else {
        emptyCart.style.display = 'none';
        let html = '';
        cartItems.forEach((item, index) => {
            html += `
                <tr>
                    <td>${index + 1}</td>
                    <td>${item.name}</td>
                    <td>${item.unit}</td>
                    <td>₹${item.price.toFixed(2)}</td>
                    <td>
                        <div class="input-group input-group-sm">
                            <button class="btn btn-outline-secondary" type="button" onclick="updateQuantity(${index}, -1)">-</button>
                            <input type="number" class="form-control text-center" value="${item.quantity}" 
                                   min="1" onchange="cartItems[${index}].quantity = Math.max(1, parseInt(this.value)); updateCartDisplay()">
                            <button class="btn btn-outline-secondary" type="button" onclick="updateQuantity(${index}, 1)">+</button>
                        </div>
                    </td>
                    <td>₹${item.total.toFixed(2)}</td>
                    <td>
                        <button class="btn btn-sm btn-danger" onclick="removeFromCart(${index})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        cartTable.innerHTML = html;
    }
    
    calculateTotal();
    updateItemsJson();
}

// Calculate totals
function calculateTotal() {
    let subtotal = 0;
    cartItems.forEach(item => {
        subtotal += item.total;
    });
    
    const discount = parseFloat(document.getElementById('discount').value) || 0;
    const tax = parseFloat(document.getElementById('tax_amount').value) || 0;
    const shipping = parseFloat(document.getElementById('shipping_charges').value) || 0;
    const total = subtotal - discount + tax + shipping;
    
    document.getElementById('subtotal').value = subtotal.toFixed(2);
    document.getElementById('subtotalDisplay').textContent = '₹ ' + subtotal.toFixed(2);
    document.getElementById('total').value = total.toFixed(2);
    document.getElementById('totalDisplay').textContent = '₹ ' + total.toFixed(2);
}

// Update hidden JSON field
function updateItemsJson() {
    document.getElementById('items_json').value = JSON.stringify(cartItems);
}

// Toggle customer form
function toggleCustomerForm() {
    const select = document.getElementById('customerSelect');
    const newForm = document.getElementById('newCustomerForm');
    const existingInfo = document.getElementById('existingCustomerInfo');
    const isNewCustomer = select.value === 'new';
    
    newForm.style.display = isNewCustomer ? 'block' : 'none';
    existingInfo.style.display = !isNewCustomer && select.value ? 'block' : 'none';
    document.getElementById('is_new_customer').value = isNewCustomer ? '1' : '0';
    
    if (!isNewCustomer && select.value) {
        const option = select.options[select.selectedIndex];
        document.getElementById('customer_id').value = select.value;
        document.getElementById('selected_customer_name').textContent = option.dataset.name;
        document.getElementById('selected_customer_phone').textContent = option.dataset.phone;
        document.getElementById('selected_customer_email').textContent = option.dataset.email;
        document.getElementById('selected_customer_gst').textContent = option.dataset.gst || 'N/A';
        
        // Set hidden form values
        document.getElementById('customer_name').value = option.dataset.name;
        document.getElementById('customer_phone').value = option.dataset.phone;
        document.getElementById('customer_email').value = option.dataset.email;
        document.getElementById('customer_address').value = option.dataset.address;
        document.getElementById('customer_gst').value = option.dataset.gst;
        document.getElementById('customer_pan').value = option.dataset.pan;
    } else if (isNewCustomer) {
        // Clear customer ID for new customer
        document.getElementById('customer_id').value = '0';
        // Clear existing customer info fields
        ['customer_name', 'customer_phone', 'customer_email', 'customer_address', 'customer_gst', 'customer_pan'].forEach(id => {
            document.getElementById(id).value = '';
        });
    }
}

// Form validation
document.getElementById('billingForm').addEventListener('submit', function(e) {
    if (cartItems.length === 0) {
        e.preventDefault();
        alert('Please add at least one product to the invoice.');
        document.getElementById('productSearch').focus();
        return;
    }
    
    const customerSelect = document.getElementById('customerSelect');
    if (!customerSelect.value) {
        e.preventDefault();
        alert('Please select or add a customer.');
        customerSelect.focus();
        return;
    }
    
    if (customerSelect.value === 'new') {
        const customerName = document.getElementById('customer_name').value.trim();
        if (!customerName) {
            e.preventDefault();
            alert('Please enter customer name for new customer.');
            document.getElementById('customer_name').focus();
            return;
        }
    }
    
    updateItemsJson();
});

// Initialize Select2
$(document).ready(function() {
    $('#customerSelect').select2({
        placeholder: '-- Select Customer --',
        width: '100%'
    });
});

// Close search results when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.closest('.product-search')) {
        document.getElementById('productResults').style.display = 'none';
    }
});

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Focus search on Ctrl+F
    if (e.ctrlKey && e.key === 'f') {
        e.preventDefault();
        document.getElementById('productSearch').focus();
    }
    
    // Clear cart on Ctrl+D
    if (e.ctrlKey && e.key === 'd') {
        e.preventDefault();
        clearCart();
    }
});

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('productSearch').focus();
});
</script>
</body>
</html>