<?php
session_start();
if(!isset($_SESSION['username']) && !isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$success_message = "";
$error_message = "";
$cart_items = isset($_SESSION['lube_sale_cart']) ? $_SESSION['lube_sale_cart'] : [];

// ============================================
// CREATE MISSING TABLES IF NOT EXISTS
// ============================================

// Check and create lube_products table
$table_check = "SHOW TABLES LIKE 'lube_products'";
$table_result = mysqli_query($conn, $table_check);
if(mysqli_num_rows($table_result) == 0) {
    $create_products = "CREATE TABLE IF NOT EXISTS `lube_products` (
        `id` int NOT NULL AUTO_INCREMENT,
        `product_code` varchar(50) NOT NULL,
        `product_name` varchar(200) NOT NULL,
        `brand` varchar(100) DEFAULT NULL,
        `pack_size` varchar(50) DEFAULT NULL,
        `category` varchar(100) DEFAULT NULL,
        `purchase_price` decimal(10,2) NOT NULL DEFAULT '0.00',
        `sale_price` decimal(10,2) NOT NULL DEFAULT '0.00',
        `current_stock` decimal(10,2) NOT NULL DEFAULT '0.00',
        `minimum_stock` decimal(10,2) DEFAULT '0.00',
        `barcode` varchar(100) DEFAULT NULL,
        `status` enum('active','inactive') DEFAULT 'active',
        `created_at` varchar(50) NOT NULL,
        PRIMARY KEY (`id`),
        UNIQUE KEY `product_code` (`product_code`)
    )";
    mysqli_query($conn, $create_products);
    
    // Insert sample product
    mysqli_query($conn, "INSERT INTO lube_products (product_code, product_name, sale_price, current_stock, status, created_at) 
                         VALUES ('LUBE-001', 'Engine Oil 3L', 2000, 100, 'active', NOW())");
    mysqli_query($conn, "INSERT INTO lube_products (product_code, product_name, sale_price, current_stock, status, created_at) 
                         VALUES ('LUBE-002', 'Gear Oil 2L', 1500, 50, 'active', NOW())");
}

// Check and create lube_sales table
$sales_table_check = "SHOW TABLES LIKE 'lube_sales'";
$sales_table_result = mysqli_query($conn, $sales_table_check);
if(mysqli_num_rows($sales_table_result) == 0) {
    $create_sales = "CREATE TABLE IF NOT EXISTS `lube_sales` (
        `id` int NOT NULL AUTO_INCREMENT,
        `sale_invoice` varchar(100) NOT NULL,
        `sale_date` varchar(50) NOT NULL,
        `customer_type` enum('walkin','credit_customer') NOT NULL DEFAULT 'walkin',
        `customer_id` int DEFAULT NULL,
        `subtotal` decimal(10,2) NOT NULL DEFAULT '0.00',
        `discount` decimal(10,2) DEFAULT '0.00',
        `total_amount` decimal(10,2) NOT NULL DEFAULT '0.00',
        `payment_method` varchar(50) DEFAULT 'cash',
        `advance_used` decimal(10,2) DEFAULT '0.00',
        `cash_received` decimal(10,2) DEFAULT '0.00',
        `status` varchar(20) DEFAULT 'completed',
        `created_by` varchar(50) DEFAULT NULL,
        `created_at` varchar(50) NOT NULL,
        PRIMARY KEY (`id`),
        UNIQUE KEY `sale_invoice` (`sale_invoice`)
    )";
    mysqli_query($conn, $create_sales);
}

// Check and create lube_sale_items table
$items_table_check = "SHOW TABLES LIKE 'lube_sale_items'";
$items_table_result = mysqli_query($conn, $items_table_check);
if(mysqli_num_rows($items_table_result) == 0) {
    $create_items = "CREATE TABLE IF NOT EXISTS `lube_sale_items` (
        `id` int NOT NULL AUTO_INCREMENT,
        `sale_id` int NOT NULL,
        `product_id` int NOT NULL,
        `quantity` decimal(10,2) NOT NULL,
        `sale_price` decimal(10,2) NOT NULL,
        `total` decimal(10,2) NOT NULL,
        PRIMARY KEY (`id`),
        KEY `sale_id` (`sale_id`),
        KEY `product_id` (`product_id`)
    )";
    mysqli_query($conn, $create_items);
}

// Check and create stock_movements table if not exists
$movement_check = "SHOW TABLES LIKE 'stock_movements'";
$movement_result = mysqli_query($conn, $movement_check);
if(mysqli_num_rows($movement_result) == 0) {
    $create_movement = "CREATE TABLE IF NOT EXISTS `stock_movements` (
        `id` int NOT NULL AUTO_INCREMENT,
        `product_id` int NOT NULL,
        `movement_type` enum('purchase','sale','adjustment') NOT NULL,
        `reference_no` varchar(100) DEFAULT NULL,
        `quantity_in` decimal(10,2) DEFAULT '0.00',
        `quantity_out` decimal(10,2) DEFAULT '0.00',
        `balance_stock` decimal(10,2) NOT NULL,
        `date_time` varchar(50) NOT NULL,
        `user_name` varchar(50) DEFAULT NULL,
        PRIMARY KEY (`id`)
    )";
    mysqli_query($conn, $create_movement);
}

// ============================================
// GET DATA FOR DROPDOWNS
// ============================================

// Get customers for dropdown
$customers_sql = "SELECT id, name, phone, balance, advance_balance FROM customers ORDER BY name";
$customers_result = mysqli_query($conn, $customers_sql);

// Get products for POS
$products_sql = "SELECT id, product_code, product_name, sale_price, current_stock FROM lube_products WHERE status='active' ORDER BY product_name";
$products_result = mysqli_query($conn, $products_sql);

// Get bank accounts for dropdown
$bank_accounts_sql = "SELECT id, bank_name, account_title, balance FROM bank_accounts ORDER BY bank_name";
$bank_accounts_result = mysqli_query($conn, $bank_accounts_sql);

// ============================================
// CART OPERATIONS
// ============================================

// Add to cart
if(isset($_POST['add_to_cart'])) {
    $product_id = intval($_POST['product_id']);
    $quantity = floatval($_POST['quantity']);
    $sale_price = floatval($_POST['sale_price']);
    
    if($product_id > 0 && $quantity > 0) {
        $prod_sql = "SELECT product_code, product_name, current_stock FROM lube_products WHERE id=$product_id";
        $prod_result = mysqli_query($conn, $prod_sql);
        $product = mysqli_fetch_assoc($prod_result);
        
        if($product) {
            if($quantity > $product['current_stock']) {
                $error_message = "Insufficient stock! Available: " . $product['current_stock'];
            } else {
                $found = false;
                foreach($cart_items as $key => &$item) {
                    if($item['product_id'] == $product_id) {
                        $new_qty = $item['quantity'] + $quantity;
                        if($new_qty > $product['current_stock']) {
                            $error_message = "Total quantity exceeds stock! Available: " . $product['current_stock'];
                            $found = true;
                            break;
                        }
                        $cart_items[$key]['quantity'] = $new_qty;
                        $cart_items[$key]['total'] = $cart_items[$key]['quantity'] * $cart_items[$key]['sale_price'];
                        $found = true;
                        $success_message = "Product quantity updated!";
                        break;
                    }
                }
                if(!$found) {
                    $cart_items[] = [
                        'product_id' => $product_id,
                        'product_code' => $product['product_code'],
                        'product_name' => $product['product_name'],
                        'quantity' => $quantity,
                        'sale_price' => $sale_price,
                        'total' => $quantity * $sale_price
                    ];
                    $success_message = "Product added to cart!";
                }
                $_SESSION['lube_sale_cart'] = $cart_items;
                header("Location: lube_sales.php");
                exit();
            }
        } else {
            $error_message = "Product not found!";
        }
    } else {
        $error_message = "Please enter valid quantity!";
    }
}

// Update cart quantity
if(isset($_POST['update_cart']) && isset($_POST['qty'])) {
    foreach($_POST['qty'] as $index => $qty) {
        if(isset($cart_items[$index]) && $qty > 0) {
            $prod_sql = "SELECT current_stock FROM lube_products WHERE id={$cart_items[$index]['product_id']}";
            $prod_result = mysqli_query($conn, $prod_sql);
            $product = mysqli_fetch_assoc($prod_result);
            if($product && floatval($qty) <= $product['current_stock']) {
                $cart_items[$index]['quantity'] = floatval($qty);
                $cart_items[$index]['total'] = $cart_items[$index]['quantity'] * $cart_items[$index]['sale_price'];
            } else {
                $error_message = "Stock insufficient for " . $cart_items[$index]['product_name'];
            }
        }
    }
    $_SESSION['lube_sale_cart'] = $cart_items;
    header("Location: lube_sales.php");
    exit();
}

// Remove from cart
if(isset($_GET['remove'])) {
    $index = intval($_GET['remove']);
    if(isset($cart_items[$index])) {
        unset($cart_items[$index]);
        $_SESSION['lube_sale_cart'] = array_values($cart_items);
        header("Location: lube_sales.php");
        exit();
    }
}

// Clear cart
if(isset($_GET['clear_cart'])) {
    $_SESSION['lube_sale_cart'] = [];
    header("Location: lube_sales.php");
    exit();
}

// ============================================
// CALCULATE TOTALS
// ============================================

$subtotal = 0;
foreach($cart_items as $item) {
    $subtotal += $item['total'];
}

$discount_percent = isset($_POST['discount_percent']) ? floatval($_POST['discount_percent']) : 0;
$discount_amount = ($subtotal * $discount_percent) / 100;
$total_amount = $subtotal - $discount_amount;

// ============================================
// SAVE SALE
// ============================================

if(isset($_POST['save_sale'])) {
    $customer_type = mysqli_real_escape_string($conn, $_POST['customer_type']);
    $customer_id = ($customer_type == 'credit_customer' && !empty($_POST['customer_id'])) ? intval($_POST['customer_id']) : 'NULL';
    $sale_invoice = mysqli_real_escape_string($conn, $_POST['sale_invoice']);
    $sale_date = mysqli_real_escape_string($conn, $_POST['sale_date']);
    $discount_percent = floatval($_POST['discount_percent']);
    $discount_amount = ($subtotal * $discount_percent) / 100;
    $total_amount = $subtotal - $discount_amount;
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $bank_id = isset($_POST['bank_id']) ? intval($_POST['bank_id']) : 0;
    $cash_received = isset($_POST['cash_received']) ? floatval($_POST['cash_received']) : 0;
    $created_by = $_SESSION['username'] ?? ($_SESSION['user_id'] ?? 'admin');
    $created_at = date('Y-m-d H:i:s');
    
    if(empty($cart_items)) {
        $error_message = "Please add at least one product to cart!";
    } elseif($customer_type == 'credit_customer' && ($customer_id == 'NULL' || $customer_id == 0)) {
        $error_message = "Please select a customer for credit sale!";
    } elseif($customer_type == 'walkin' && $payment_method == 'bank' && empty($bank_id)) {
        $error_message = "Please select a bank account for bank payment!";
    } else {
        mysqli_begin_transaction($conn);
        try {
            // Insert sale record
            $sale_sql = "INSERT INTO lube_sales (sale_invoice, sale_date, customer_type, customer_id, subtotal, discount, total_amount, payment_method, advance_used, cash_received, created_by, created_at) 
                        VALUES ('$sale_invoice', '$sale_date', '$customer_type', $customer_id, $subtotal, $discount_amount, $total_amount, '$payment_method', 0, $cash_received, '$created_by', '$created_at')";
            
            if(!mysqli_query($conn, $sale_sql)) {
                throw new Exception("Failed to save sale: " . mysqli_error($conn));
            }
            $sale_id = mysqli_insert_id($conn);
            
            // Insert sale items and update stock
            foreach($cart_items as $item) {
                $item_sql = "INSERT INTO lube_sale_items (sale_id, product_id, quantity, sale_price, total) 
                            VALUES ($sale_id, {$item['product_id']}, {$item['quantity']}, {$item['sale_price']}, {$item['total']})";
                if(!mysqli_query($conn, $item_sql)) {
                    throw new Exception("Failed to save sale items: " . mysqli_error($conn));
                }
                
                $update_stock = "UPDATE lube_products SET current_stock = current_stock - {$item['quantity']} WHERE id = {$item['product_id']}";
                if(!mysqli_query($conn, $update_stock)) {
                    throw new Exception("Failed to update stock: " . mysqli_error($conn));
                }
            }
            
            // Handle payment scenarios for walk-in customers only
            if($customer_type == 'walkin') {
                if($payment_method == 'cash' && $cash_received > 0) {
                    // Cash payment - entry in cash_book as income
                    $cash_book_sql = "INSERT INTO cash_book (entry_type, amount, description, reference_no, reference_table, reference_id, date_time, user_name) 
                                      VALUES ('income', $total_amount, 'Lube Sale - Invoice: $sale_invoice (Walk-in Customer)', '$sale_invoice', 'lube_sales', $sale_id, '$created_at', '$created_by')";
                    mysqli_query($conn, $cash_book_sql);
                    
                } elseif($payment_method == 'bank' && $bank_id > 0) {
                    // Bank transfer payment - update bank account
                    $update_bank = "UPDATE bank_accounts SET balance = balance + $total_amount WHERE id = $bank_id";
                    mysqli_query($conn, $update_bank);
                    
                    // Insert into bank book as deposit
                    $bank_book_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                                      VALUES ($bank_id, 'Deposit', $total_amount, 'Lube Sale - Invoice: $sale_invoice (Walk-in Customer)', '$sale_invoice', '$created_at')";
                    mysqli_query($conn, $bank_book_sql);
                }
            } elseif($customer_type == 'credit_customer' && $customer_id != 'NULL') {
                // CREDIT CUSTOMER - Add to customer balance
                $update_customer = "UPDATE customers SET balance = balance + $total_amount WHERE id = $customer_id";
                mysqli_query($conn, $update_customer);
                
                // Record credit sale in customer_payments
                $payment_sql = "INSERT INTO customer_payments (customer_id, amount, payment_type, transaction_type, notes, date_time) 
                                VALUES ($customer_id, $total_amount, 'credit_sale', 'credit_sale', 'Lube Sale Invoice: $sale_invoice', '$created_at')";
                mysqli_query($conn, $payment_sql);
            }
            
            mysqli_commit($conn);
            $_SESSION['lube_sale_cart'] = [];
            
            // Redirect to invoice page
            ?>
            <script>
                alert("Sale completed successfully! Invoice #: <?php echo $sale_invoice; ?>");
                window.location.href = "lube_sale_invoice.php?id=<?php echo $sale_id; ?>&print=thermal";
            </script>
            <?php
            exit();
            
        } catch(Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="lube-sales-container">
    <!-- Page Header -->
    <div class="page-header">
        <div>
            <h2><i class="fas fa-cash-register"></i> Lube POS</h2>
            <p>Quick lubricant sales - Cash, Bank & Credit options</p>
        </div>
        <div class="stats-badge"><i class="fas fa-shopping-cart"></i> Point of Sale</div>
    </div>

    <?php if($success_message): ?>
        <div class="alert-custom alert-success"><i class="fas fa-check-circle"></i> <?php echo $success_message; ?><button class="close-alert" onclick="this.parentElement.remove();">&times;</button></div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger"><i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?><button class="close-alert" onclick="this.parentElement.remove();">&times;</button></div>
    <?php endif; ?>

    <div class="pos-grid">
        <!-- Left Side - Products Grid -->
        <div class="products-grid-card">
            <div class="card-header-custom">
                <i class="fas fa-boxes"></i>
                <h4>Products</h4>
                <div class="product-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="productSearch" placeholder="Search..." class="search-input-pos">
                </div>
            </div>
            <div class="card-body-custom">
                <div class="products-grid" id="productsGrid">
                    <?php 
                    if(mysqli_num_rows($products_result) > 0):
                        while($prod = mysqli_fetch_assoc($products_result)): 
                    ?>
                        <div class="product-card" data-id="<?php echo $prod['id']; ?>">
                            <div class="product-info">
                                <div class="product-name"><?php echo htmlspecialchars($prod['product_name']); ?></div>
                                <div class="product-code"><?php echo $prod['product_code']; ?></div>
                                <div class="product-price">Rs <?php echo number_format($prod['sale_price'], 2); ?></div>
                                <div class="product-stock">Stock: <?php echo number_format($prod['current_stock'], 2); ?></div>
                            </div>
                            <button type="button" class="btn-quick-add" onclick="openAddToCartModal(<?php echo $prod['id']; ?>, '<?php echo addslashes($prod['product_name']); ?>', <?php echo $prod['sale_price']; ?>)">
                                <i class="fas fa-cart-plus"></i>
                            </button>
                        </div>
                    <?php 
                        endwhile;
                    else:
                    ?>
                        <div class="empty-cart"><i class="fas fa-box-open"></i><p>No products available</p><small>Add products first in Inventory</small></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Right Side - Cart -->
        <div class="cart-card">
            <div class="card-header-custom">
                <i class="fas fa-shopping-cart"></i>
                <h4>Sale Cart</h4>
                <?php if(count($cart_items) > 0): ?>
                    <a href="?clear_cart=1" class="btn-clear" onclick="return confirm('Clear entire cart?')"><i class="fas fa-trash-alt"></i> Clear</a>
                <?php endif; ?>
            </div>
            <div class="card-body-custom">
                <?php if(count($cart_items) > 0): ?>
                    <form method="POST" action="" id="cartForm">
                        <div class="cart-table-container">
                            <table class="cart-table">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th width="12%">Qty</th>
                                        <th width="12%">Price</th>
                                        <th width="12%">Total</th>
                                        <th width="8%"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($cart_items as $index => $item): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['product_name']); ?><br><small><?php echo $item['product_code']; ?></small></td>
                                            <td><input type="number" step="0.01" name="qty[<?php echo $index; ?>]" value="<?php echo $item['quantity']; ?>" class="cart-qty"></td>
                                            <td>Rs <?php echo number_format($item['sale_price'], 2); ?></td>
                                            <td><strong>Rs <?php echo number_format($item['total'], 2); ?></strong></td>
                                            <td><a href="?remove=<?php echo $index; ?>" class="btn-remove" onclick="return confirm('Remove item?')"><i class="fas fa-times"></i></a></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr class="subtotal-row"><td colspan="3"><strong>Subtotal:</strong></td><td colspan="2"><strong>Rs <?php echo number_format($subtotal, 2); ?></strong></td></tr>
                                </tfoot>
                            </table>
                        </div>
                        <button type="submit" name="update_cart" class="btn-update-cart"><i class="fas fa-sync-alt"></i> Update Cart</button>
                    </form>
                    
                    <form method="POST" action="" class="sale-form" id="saleForm">
                        <div class="sale-type-selector">
                            <div class="sale-type-option">
                                <input type="radio" name="customer_type" id="walkin" value="walkin" checked onchange="toggleCustomerSelect()">
                                <label for="walkin"><i class="fas fa-user"></i> Walk-in Customer</label>
                            </div>
                            <div class="sale-type-option">
                                <input type="radio" name="customer_type" id="credit_customer" value="credit_customer" onchange="toggleCustomerSelect()">
                                <label for="credit_customer"><i class="fas fa-users"></i> Credit Customer</label>
                            </div>
                        </div>

                        <div id="customer_select_section" style="display: none;">
                            <div class="form-group-custom">
                                <label><i class="fas fa-user"></i> Select Customer</label>
                                <select name="customer_id" id="customer_id" class="form-control-modern">
                                    <option value="">-- Select Customer --</option>
                                    <?php 
                                    mysqli_data_seek($customers_result, 0);
                                    while($cust = mysqli_fetch_assoc($customers_result)): 
                                    ?>
                                        <option value="<?php echo $cust['id']; ?>">
                                            <?php echo htmlspecialchars($cust['name']); ?> (Balance: Rs <?php echo number_format($cust['balance'], 2); ?>)
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>

                        <div class="form-row-custom">
                            <div class="form-group-custom half">
                                <label><i class="fas fa-file-invoice"></i> Invoice No *</label>
                                <input type="text" name="sale_invoice" class="form-control-modern" required value="INV-<?php echo date('YmdHis'); ?>">
                            </div>
                            <div class="form-group-custom half">
                                <label><i class="fas fa-calendar"></i> Sale Date *</label>
                                <input type="date" name="sale_date" class="form-control-modern" required value="<?php echo date('Y-m-d'); ?>">
                            </div>
                        </div>

                        <div class="form-row-custom">
                            <div class="form-group-custom half">
                                <label><i class="fas fa-percent"></i> Discount (%)</label>
                                <input type="number" step="0.01" name="discount_percent" id="discount_percent" class="form-control-modern" value="0" onkeyup="updateGrandTotal()">
                            </div>
                            <div class="form-group-custom half">
                                <label><i class="fas fa-rupee-sign"></i> Grand Total</label>
                                <input type="text" id="grand_total" class="form-control-modern" readonly style="background:#f0f0f0; font-weight:bold; color:#28a745;" value="Rs <?php echo number_format($total_amount, 2); ?>">
                            </div>
                        </div>

                        <div id="walkin_payment_section">
                            <div class="form-group-custom">
                                <label><i class="fas fa-money-bill-wave"></i> Payment Method</label>
                                <select name="payment_method" id="payment_method" class="form-control-modern" onchange="toggleBankField()">
                                    <option value="cash">Cash</option>
                                    <option value="bank">Bank Transfer</option>
                                </select>
                            </div>

                            <div class="form-group-custom" id="bank_div" style="display: none;">
                                <label><i class="fas fa-university"></i> Select Bank Account *</label>
                                <select name="bank_id" id="bank_id" class="form-control-modern">
                                    <option value="">-- Select Bank Account --</option>
                                    <?php 
                                    mysqli_data_seek($bank_accounts_result, 0);
                                    while($bank = mysqli_fetch_assoc($bank_accounts_result)): 
                                    ?>
                                        <option value="<?php echo $bank['id']; ?>">
                                            <?php echo htmlspecialchars($bank['bank_name']); ?> - <?php echo htmlspecialchars($bank['account_title']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>

                            <div class="form-group-custom" id="cash_received_section">
                                <label><i class="fas fa-hand-holding-usd"></i> Cash Received</label>
                                <input type="number" step="0.01" name="cash_received" id="cash_received" class="form-control-modern" value="<?php echo $total_amount; ?>" onkeyup="calculateChange()">
                                <div id="change_due" style="margin-top: 5px; font-size: 12px; font-weight: bold;"></div>
                            </div>
                        </div>

                        <div id="credit_payment_section" style="display: none;">
                            <div class="payment-method-credit">
                                <i class="fas fa-credit-card"></i> 
                                <p>Payment Method: <strong>Credit</strong> (Will be added to customer's balance)</p>
                                <small>Amount will be added to customer's outstanding balance</small>
                            </div>
                            <input type="hidden" name="payment_method" value="credit">
                            <input type="hidden" name="cash_received" value="0">
                        </div>

                        <button type="submit" name="save_sale" class="btn-save">
                            <i class="fas fa-save"></i> Complete Sale & Print Invoice
                        </button>
                    </form>
                    
                <?php else: ?>
                    <div class="empty-cart"><i class="fas fa-shopping-cart"></i><p>Cart is empty</p><small>Click on products to add to cart</small></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Quick Add Modal -->
<div id="quickAddModal" class="modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add to Cart</h5>
                <button type="button" class="close" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="addToCartForm" method="POST" action="">
                    <input type="hidden" name="add_to_cart" value="1">
                    <input type="hidden" name="product_id" id="modal_product_id">
                    <input type="hidden" name="sale_price" id="modal_product_price">
                    <div class="form-group-custom"><label>Product</label><input type="text" id="modal_product_name" class="form-control-modern" readonly></div>
                    <div class="form-group-custom"><label>Price (Rs)</label><input type="text" id="modal_product_price_display" class="form-control-modern" readonly></div>
                    <div class="form-group-custom"><label>Quantity</label><input type="number" step="0.01" name="quantity" id="modal_quantity" class="form-control-modern" value="1" required></div>
                    <div class="form-group-custom"><label>Total</label><input type="text" id="modal_total" class="form-control-modern" readonly></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary-modal" onclick="closeModal()">Cancel</button>
                <button type="button" class="btn-primary-modal" onclick="submitAddToCart()">Add to Cart</button>
            </div>
        </div>
    </div>
</div>

<style>
/* Lube Sales Styles */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');

* {
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background: #f0f2f5;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-value,
.form-card-header h4,
.card-header-custom h4 {
    font-family: 'Times New Roman', serif;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f0f2f5;
}

.lube-sales-container {
    max-width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 18px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    font-size: 22px;
    margin-bottom: 4px;
    font-weight: 700;
}

.page-header p {
    font-size: 12px;
    opacity: 0.9;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 15px;
    border-radius: 30px;
    font-weight: 600;
    font-size: 12px;
}

/* POS Grid */
.pos-grid {
    display: grid;
    grid-template-columns: 1fr 400px;
    gap: 20px;
    width: 100%;
}

.products-grid-card, .cart-card {
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    border: 1px solid #eee;
}

.card-header-custom {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 12px 15px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #fff;
}

.card-header-custom h4 {
    margin: 0;
    font-size: 14px;
    flex: 1;
}

.product-search {
    position: relative;
}

.product-search i {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #fff;
    font-size: 11px;
}

.search-input-pos {
    padding: 5px 10px 5px 28px;
    border: none;
    border-radius: 20px;
    width: 160px;
    font-size: 11px;
}

.card-body-custom {
    padding: 15px;
    max-height: calc(100vh - 150px);
    overflow-y: auto;
}

.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 12px;
}

.product-card {
    border: 1px solid #e8e8e8;
    border-radius: 10px;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.2s;
}

.product-card:hover {
    border-color: #A04657;
    box-shadow: 0 2px 8px rgba(160,70,87,0.1);
}

.product-name {
    font-weight: 700;
    font-size: 13px;
    margin-bottom: 3px;
}

.product-code {
    font-size: 10px;
    color: #999;
    margin-bottom: 3px;
}

.product-price {
    font-size: 12px;
    font-weight: 700;
    color: #A04657;
}

.product-stock {
    font-size: 9px;
    color: #666;
}

.btn-quick-add {
    background: #A04657;
    color: #fff;
    border: none;
    width: 28px;
    height: 28px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 12px;
}

.btn-clear {
    background: rgba(255,255,255,0.2);
    padding: 4px 10px;
    border-radius: 15px;
    font-size: 11px;
    color: #fff;
    text-decoration: none;
}

/* Cart Table */
.cart-table {
    width: 100%;
    border-collapse: collapse;
}

.cart-table th {
    padding: 6px;
    background: #f8f9fc;
    font-size: 10px;
    font-weight: 700;
    text-align: left;
}

.cart-table td {
    padding: 6px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 11px;
}

.cart-qty {
    padding: 4px;
    border: 1px solid #ddd;
    border-radius: 6px;
    text-align: center;
    width: 60px;
    font-size: 11px;
}

.btn-remove {
    color: #dc3545;
    text-decoration: none;
    font-size: 12px;
}

.btn-update-cart {
    width: 100%;
    padding: 8px;
    background: #f0f0f0;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    margin-bottom: 15px;
    font-size: 12px;
}

/* Sale Type Selector */
.sale-type-selector {
    display: flex;
    gap: 15px;
    margin-bottom: 15px;
    padding: 8px;
    background: #f8f9fc;
    border-radius: 10px;
}

.sale-type-option {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
}

/* Form Elements */
.form-group-custom {
    margin-bottom: 12px;
}

.form-group-custom label {
    display: block;
    margin-bottom: 4px;
    font-weight: 600;
    font-size: 11px;
    color: #555;
}

.form-control-modern {
    width: 100%;
    padding: 8px 12px;
    border: 2px solid #e8e8e8;
    border-radius: 8px;
    font-size: 12px;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
}

.form-row-custom {
    display: flex;
    gap: 12px;
}

.half {
    flex: 1;
}

/* Buttons */
.btn-save {
    width: 100%;
    padding: 10px;
    background: linear-gradient(135deg, #28a745, #1e7e34);
    color: #fff;
    border: none;
    border-radius: 8px;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    font-size: 13px;
}

.empty-cart {
    text-align: center;
    padding: 30px;
}

.empty-cart i {
    font-size: 40px;
    color: #A04657;
    opacity: 0.3;
}

/* Alerts */
.alert-custom {
    padding: 10px 15px;
    border-radius: 10px;
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
}

.alert-success {
    background: #e8f5e9;
    color: #2e7d32;
    border-left: 3px solid #28a745;
}

.alert-danger {
    background: #ffebee;
    color: #c62828;
    border-left: 3px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
}

/* Payment Method Credit */
.payment-method-credit {
    background: #e3f2fd;
    border-radius: 8px;
    padding: 10px;
    margin-bottom: 15px;
    text-align: center;
}

.payment-method-credit p {
    margin: 0;
    font-size: 12px;
    color: #1565c0;
    font-weight: 600;
}

/* Modal */
.modal {
    display: none;
    position: fixed;
    z-index: 9999;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-dialog {
    position: relative;
    width: auto;
    max-width: 400px;
    margin: 50px auto;
}

.modal-content {
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
}

.modal-header {
    background: #A04657;
    color: white;
    padding: 12px 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h5 {
    margin: 0;
    font-size: 16px;
}

.close {
    background: none;
    border: none;
    color: white;
    font-size: 24px;
    cursor: pointer;
}

.modal-body {
    padding: 15px;
}

.modal-footer {
    padding: 12px 15px;
    background: #f8f9fc;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.btn-secondary-modal {
    padding: 6px 15px;
    background: #6c757d;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
}

.btn-primary-modal {
    padding: 6px 15px;
    background: #A04657;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
}

/* Responsive */
@media (max-width: 1000px) {
    .pos-grid {
        grid-template-columns: 1fr;
    }
    .products-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-left: 0;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 10px;
        padding: 15px;
    }
    .form-row-custom {
        flex-direction: column;
        gap: 0;
    }
    .cart-table th, .cart-table td {
        font-size: 9px;
        padding: 4px;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

<script>
let currentProduct = {};

function openAddToCartModal(id, name, price) {
    currentProduct = {id: id, name: name, price: price};
    document.getElementById('modal_product_id').value = id;
    document.getElementById('modal_product_name').value = name;
    document.getElementById('modal_product_price').value = price;
    document.getElementById('modal_product_price_display').value = 'Rs ' + price.toFixed(2);
    document.getElementById('modal_quantity').value = 1;
    updateModalTotal();
    document.getElementById('quickAddModal').style.display = 'block';
}

function closeModal() { 
    document.getElementById('quickAddModal').style.display = 'none'; 
}

function updateModalTotal() {
    let qty = parseFloat(document.getElementById('modal_quantity').value) || 0;
    let price = parseFloat(document.getElementById('modal_product_price').value) || 0;
    document.getElementById('modal_total').value = 'Rs ' + (qty * price).toFixed(2);
}

document.getElementById('modal_quantity')?.addEventListener('input', updateModalTotal);

function submitAddToCart() { 
    document.getElementById('addToCartForm').submit(); 
}

function toggleCustomerSelect() {
    let creditSelected = document.getElementById('credit_customer').checked;
    let customerSection = document.getElementById('customer_select_section');
    let walkinPayment = document.getElementById('walkin_payment_section');
    let creditPayment = document.getElementById('credit_payment_section');
    
    if(creditSelected) {
        customerSection.style.display = 'block';
        walkinPayment.style.display = 'none';
        creditPayment.style.display = 'block';
        document.getElementById('payment_method').removeAttribute('name');
        document.getElementById('cash_received').removeAttribute('name');
    } else {
        customerSection.style.display = 'none';
        walkinPayment.style.display = 'block';
        creditPayment.style.display = 'none';
        document.getElementById('payment_method').setAttribute('name', 'payment_method');
        document.getElementById('cash_received').setAttribute('name', 'cash_received');
        toggleBankField();
    }
}

function toggleBankField() {
    let paymentMethod = document.getElementById('payment_method').value;
    let bankDiv = document.getElementById('bank_div');
    let cashSection = document.getElementById('cash_received_section');
    
    if(paymentMethod === 'bank') {
        bankDiv.style.display = 'block';
        cashSection.style.display = 'none';
        document.getElementById('bank_id').required = true;
    } else {
        bankDiv.style.display = 'none';
        cashSection.style.display = 'block';
        document.getElementById('bank_id').required = false;
    }
}

function updateGrandTotal() {
    let subtotal = <?php echo $subtotal; ?>;
    let discountPercent = parseFloat(document.getElementById('discount_percent').value) || 0;
    let grandTotal = subtotal - ((subtotal * discountPercent) / 100);
    document.getElementById('grand_total').value = 'Rs ' + grandTotal.toFixed(2);
    document.getElementById('cash_received').value = grandTotal;
}

function calculateChange() {
    let grandTotal = parseFloat(document.getElementById('grand_total').value.replace('Rs ', '').replace(/,/g, '')) || 0;
    let cashReceived = parseFloat(document.getElementById('cash_received').value) || 0;
    let change = cashReceived - grandTotal;
    let changeDiv = document.getElementById('change_due');
    
    if(change > 0) {
        changeDiv.innerHTML = '<span style="color:#28a745;">Change Due: Rs ' + change.toFixed(2) + '</span>';
    } else if(change < 0) {
        changeDiv.innerHTML = '<span style="color:#dc3545;">Short by: Rs ' + Math.abs(change).toFixed(2) + '</span>';
    } else if(change === 0 && grandTotal > 0) {
        changeDiv.innerHTML = '<span style="color:#28a745;">Exact Amount Received</span>';
    } else {
        changeDiv.innerHTML = '';
    }
}

// Product search
document.getElementById('productSearch')?.addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase();
    document.querySelectorAll('.product-card').forEach(product => {
        product.style.display = product.textContent.toLowerCase().includes(searchValue) ? 'flex' : 'none';
    });
});

// Close modal on outside click
window.onclick = function(event) {
    let modal = document.getElementById('quickAddModal');
    if (event.target == modal) modal.style.display = 'none';
}

// Auto-hide alerts
document.querySelectorAll('.alert-custom').forEach(alert => {
    setTimeout(() => { alert.style.opacity = '0'; setTimeout(() => alert.remove(), 300); }, 5000);
});

// Initialize change calculation on page load
<?php if($total_amount > 0): ?>
document.getElementById('cash_received').value = <?php echo $total_amount; ?>;
calculateChange();
<?php endif; ?>
</script>

<?php include('../includes/ft.php'); ?>