<?php
// modules/sales/ajax/pos.php
session_start();
require_once '../../assets/db_connect.php';

// Check if user is logged in
if (!isset($_SESSION['user'])) {
    die("Access denied. Please login.");
}

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_id = $_SESSION['user']['id'] ?? 0;
$user_role = $_SESSION['user']['role'] ?? 'cashier';

if ($shop_id == 0) {
    die("Shop session missing.");
}

// Get shop info
$shop_sql = "SELECT * FROM shops WHERE id = ?";
$shop_stmt = $pdo->prepare($shop_sql);
$shop_stmt->execute([$shop_id]);
$shop = $shop_stmt->fetch(PDO::FETCH_ASSOC);

// Get available products with stock
$products_sql = "SELECT 
                    pa.*,
                    pb.id as batch_id,
                    pb.batch_no,
                    pb.sell_price as batch_price,
                    pb.expiry_date,
                    pb.qty as batch_stock
                FROM product_availability pa
                JOIN product_batches pb ON pa.batch_id = pb.id
                WHERE pa.shop_id = ? 
                AND pa.batch_qty > 0
                AND pb.is_active = 1
                AND (pb.expiry_date IS NULL OR pb.expiry_date > CURDATE())
                ORDER BY pa.name ASC, pb.expiry_date ASC";
$products_stmt = $pdo->prepare($products_sql);
$products_stmt->execute([$shop_id]);
$products = $products_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get customers
$customers_sql = "SELECT * FROM customers WHERE shop_id = ? OR shop_id IS NULL ORDER BY name";
$customers_stmt = $pdo->prepare($customers_sql);
$customers_stmt->execute([$shop_id]);
$customers = $customers_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Point of Sale - <?= htmlspecialchars($shop['name']) ?></title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Select2 -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        body {
            background: #f5f5f5;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .pos-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }
        .products-section {
            flex: 3;
            background: white;
            overflow-y: auto;
            padding: 15px;
        }
        .cart-section {
            flex: 2;
            background: #fff;
            border-left: 1px solid #dee2e6;
            display: flex;
            flex-direction: column;
        }
        .product-card {
            cursor: pointer;
            transition: all 0.3s;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 10px;
            background: white;
        }
        .product-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            border-color: #0d6efd;
        }
        .product-card.selected {
            border-color: #198754;
            background-color: #f8fff9;
        }
        .product-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        .product-details {
            font-size: 12px;
            color: #6c757d;
        }
        .product-price {
            font-weight: bold;
            color: #198754;
            font-size: 14px;
        }
        .stock-badge {
            font-size: 11px;
            padding: 2px 6px;
            border-radius: 10px;
        }
        .stock-low { background: #fff3cd; color: #856404; }
        .stock-good { background: #d1ecf1; color: #0c5460; }
        .stock-high { background: #d4edda; color: #155724; }
        .cart-header {
            background: #2c3e50;
            color: white;
            padding: 15px;
            border-bottom: 3px solid #3498db;
        }
        .cart-items {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
        }
        .cart-footer {
            background: #f8f9fa;
            padding: 15px;
            border-top: 1px solid #dee2e6;
        }
        .cart-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
            transition: background 0.2s;
        }
        .cart-item:hover {
            background: #f8f9fa;
        }
        .item-qty {
            width: 60px;
            text-align: center;
        }
        .item-total {
            font-weight: bold;
            color: #2c3e50;
        }
        .remove-item {
            color: #dc3545;
            cursor: pointer;
            padding: 5px;
        }
        .remove-item:hover {
            color: #bd2130;
        }
        .totals-box {
            background: white;
            border: 2px solid #2c3e50;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .total-row {
            display: flex;
            justify-content: space-between;
            margin: 8px 0;
            font-size: 14px;
        }
        .total-amount {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }
        .payment-section {
            background: #e8f4fc;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
        }
        .btn-sale {
            font-size: 18px;
            font-weight: bold;
            padding: 12px;
            height: auto;
        }
        .search-box {
            position: sticky;
            top: 0;
            background: white;
            padding: 10px 0;
            z-index: 100;
            border-bottom: 1px solid #dee2e6;
        }
        .category-filter {
            margin-top: 10px;
        }
        .category-btn {
            margin: 2px;
            padding: 4px 8px;
            font-size: 12px;
        }
        .quantity-controls {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .qty-btn {
            width: 30px;
            height: 30px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .receipt-preview {
            background: white;
            border: 1px dashed #ccc;
            border-radius: 5px;
            padding: 15px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
            margin-top: 15px;
        }
        .customer-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 15px;
        }
        .payment-methods {
            display: flex;
            gap: 10px;
            margin: 10px 0;
        }
        .payment-method-btn {
            flex: 1;
            text-align: center;
            padding: 8px;
            border: 2px solid #dee2e6;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .payment-method-btn:hover,
        .payment-method-btn.active {
            border-color: #198754;
            background: #d4edda;
        }
        .receipt-item {
            display: flex;
            justify-content: space-between;
            border-bottom: 1px dotted #ccc;
            padding: 2px 0;
        }
        .pos-nav {
            background: #2c3e50;
            color: white;
            padding: 10px 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .pos-nav a {
            color: white;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <!-- POS Navigation -->
    <div class="pos-nav">
        <div>
            <h4 class="mb-0">
                <i class="fas fa-cash-register"></i> 
                <?= htmlspecialchars($shop['name']) ?> - Point of Sale
            </h4>
            <small><?= date('F j, Y h:i A') ?></small>
        </div>
        <div>
            <a href="../list_sales.php" class="btn btn-sm btn-outline-light me-2">
                <i class="fas fa-arrow-left"></i> Back to Sales
            </a>
            <a href="../../dashboard.php" class="btn btn-sm btn-outline-light">
                <i class="fas fa-home"></i> Dashboard
            </a>
        </div>
    </div>
    
    <div class="pos-container">
        <!-- Products Section -->
        <div class="products-section">
            <div class="search-box">
                <div class="input-group mb-2">
                    <span class="input-group-text"><i class="fas fa-search"></i></span>
                    <input type="text" id="productSearch" class="form-control" placeholder="Search products by name, SKU, or category...">
                    <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="category-filter" id="categoryFilters">
                    <!-- Categories will be loaded dynamically -->
                </div>
            </div>
            
            <div class="row" id="productsGrid">
                <?php if (empty($products)): ?>
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                        <h4>No products available for sale</h4>
                        <p class="text-muted">Add products with stock to start selling</p>
                        <a href="../../products/manage_products.php" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Add Products
                        </a>
                    </div>
                <?php else: ?>
                    <?php foreach ($products as $product): ?>
                        <?php
                        // Determine stock status
                        $stock_qty = $product['batch_qty'];
                        if ($stock_qty <= 0) {
                            $stock_class = 'stock-low';
                            $stock_text = 'Out of Stock';
                        } elseif ($stock_qty <= 10) {
                            $stock_class = 'stock-low';
                            $stock_text = 'Low Stock';
                        } elseif ($stock_qty <= 50) {
                            $stock_class = 'stock-good';
                            $stock_text = 'In Stock';
                        } else {
                            $stock_class = 'stock-high';
                            $stock_text = 'High Stock';
                        }
                        
                        // Format expiry date
                        $expiry_text = '';
                        if ($product['expiry_date']) {
                            $expiry_days = (strtotime($product['expiry_date']) - time()) / (60 * 60 * 24);
                            if ($expiry_days < 30) {
                                $expiry_text = 'Expires soon';
                            }
                        }
                        ?>
                        <div class="col-md-3 col-sm-4 col-6 mb-3">
                            <div class="product-card" 
                                 onclick="addToCart(<?= $product['product_id'] ?>, <?= $product['batch_id'] ?>, '<?= htmlspecialchars(addslashes($product['name'])) ?>', <?= $product['batch_price'] ?>, <?= $stock_qty ?>)"
                                 data-category="<?= htmlspecialchars($product['category']) ?>"
                                 data-search="<?= strtolower(htmlspecialchars($product['name'] . ' ' . $product['sku'] . ' ' . $product['generic_name'] . ' ' . $product['category'])) ?>">
                                <div class="product-name"><?= htmlspecialchars($product['name']) ?></div>
                                <div class="product-details mb-2">
                                    <div><small>SKU: <?= htmlspecialchars($product['sku']) ?></small></div>
                                    <?php if ($product['generic_name']): ?>
                                        <div><small><?= htmlspecialchars($product['generic_name']) ?></small></div>
                                    <?php endif; ?>
                                    <div><small><?= htmlspecialchars($product['category']) ?></small></div>
                                    <?php if ($product['batch_no']): ?>
                                        <div><small>Batch: <?= htmlspecialchars($product['batch_no']) ?></small></div>
                                    <?php endif; ?>
                                </div>
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="product-price">TZS <?= number_format($product['batch_price'], 2) ?></span>
                                    <span class="stock-badge <?= $stock_class ?>">
                                        <?= $stock_qty ?> <?= $product['unit'] ?>
                                    </span>
                                </div>
                                <?php if ($expiry_text): ?>
                                    <div class="text-danger small mt-1">
                                        <i class="fas fa-exclamation-circle"></i> <?= $expiry_text ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Cart Section -->
        <div class="cart-section">
            <div class="cart-header">
                <h4 class="mb-0">
                    <i class="fas fa-shopping-cart"></i> Current Sale
                    <span class="badge bg-light text-dark float-end" id="cartCount">0</span>
                </h4>
            </div>
            
            <!-- Customer Section -->
            <div class="customer-section mx-3 mt-3">
                <label class="form-label"><i class="fas fa-user"></i> Customer</label>
                <select id="customerSelect" class="form-select">
                    <option value="">Walk-in Customer</option>
                    <?php foreach ($customers as $customer): ?>
                        <option value="<?= $customer['id'] ?>">
                            <?= htmlspecialchars($customer['name']) ?>
                            <?php if ($customer['phone']): ?>
                                (<?= htmlspecialchars($customer['phone']) ?>)
                            <?php endif; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="mt-2">
                    <button class="btn btn-sm btn-outline-primary" onclick="showNewCustomerModal()">
                        <i class="fas fa-plus"></i> New Customer
                    </button>
                </div>
            </div>
            
            <!-- Cart Items -->
            <div class="cart-items" id="cartItems">
                <div class="text-center text-muted py-5" id="emptyCartMessage">
                    <i class="fas fa-shopping-cart fa-3x mb-3"></i>
                    <h5>Cart is Empty</h5>
                    <p>Select products from the left to add to cart</p>
                </div>
            </div>
            
            <!-- Totals -->
            <div class="mx-3">
                <div class="totals-box">
                    <div class="total-row">
                        <span>Subtotal:</span>
                        <span id="subtotal">TZS 0.00</span>
                    </div>
                    <div class="total-row">
                        <span>Discount:</span>
                        <div class="input-group input-group-sm" style="width: 150px;">
                            <input type="number" id="discountAmount" class="form-control" value="0" min="0" step="0.01">
                            <span class="input-group-text">TZS</span>
                        </div>
                    </div>
                    <div class="total-row">
                        <span>VAT:</span>
                        <span id="vatAmount">TZS 0.00</span>
                    </div>
                    <hr>
                    <div class="total-row total-amount">
                        <span>TOTAL:</span>
                        <span id="grandTotal">TZS 0.00</span>
                    </div>
                </div>
                
                <!-- Payment Section -->
                <div class="payment-section">
                    <h6><i class="fas fa-credit-card"></i> Payment</h6>
                    
                    <div class="payment-methods">
                        <div class="payment-method-btn active" onclick="selectPaymentMethod('CASH')" id="cashMethod">
                            <i class="fas fa-money-bill-wave fa-2x"></i>
                            <div>CASH</div>
                        </div>
                        <div class="payment-method-btn" onclick="selectPaymentMethod('M-PESA')" id="mpesaMethod">
                            <i class="fas fa-mobile-alt fa-2x"></i>
                            <div>M-PESA</div>
                        </div>
                        <div class="payment-method-btn" onclick="selectPaymentMethod('TIGO-PESA')" id="tigopesaMethod">
                            <i class="fas fa-mobile-alt fa-2x"></i>
                            <div>TIGO PESA</div>
                        </div>
                        <div class="payment-method-btn" onclick="selectPaymentMethod('AIRTEL-MONEY')" id="airtelMethod">
                            <i class="fas fa-mobile-alt fa-2x"></i>
                            <div>AIRTEL MONEY</div>
                        </div>
                        <div class="payment-method-btn" onclick="selectPaymentMethod('CARD')" id="cardMethod">
                            <i class="fas fa-credit-card fa-2x"></i>
                            <div>CARD</div>
                        </div>
                    </div>
                    
                    <div class="mt-3">
                        <label class="form-label">Amount Paid</label>
                        <input type="number" id="amountPaid" class="form-control" value="0" min="0" step="0.01" oninput="calculateChange()">
                    </div>
                    
                    <div class="mt-2">
                        <label class="form-label">Change</label>
                        <input type="text" id="changeAmount" class="form-control" value="TZS 0.00" readonly style="font-weight: bold; color: #198754;">
                    </div>
                    
                    <!-- Receipt Preview -->
                    <div class="receipt-preview mt-3 d-none" id="receiptPreview">
                        <div class="text-center mb-2">
                            <strong><?= htmlspecialchars($shop['name']) ?></strong><br>
                            <?= htmlspecialchars($shop['address']) ?><br>
                            Tel: <?= htmlspecialchars($shop['phone']) ?><br>
                            <small>Date: <?= date('d/m/Y H:i:s') ?></small>
                        </div>
                        <div id="receiptItems">
                            <!-- Items will be added here -->
                        </div>
                        <hr>
                        <div class="receipt-item">
                            <span>Total:</span>
                            <span id="receiptTotal">TZS 0.00</span>
                        </div>
                        <div class="receipt-item">
                            <span>Paid:</span>
                            <span id="receiptPaid">TZS 0.00</span>
                        </div>
                        <div class="receipt-item">
                            <span>Change:</span>
                            <span id="receiptChange">TZS 0.00</span>
                        </div>
                        <div class="text-center mt-2">
                            <small>Thank you for your business!</small>
                        </div>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="d-grid gap-2 mt-3">
                        <button class="btn btn-success btn-sale" onclick="processSale()" id="processSaleBtn" disabled>
                            <i class="fas fa-check-circle"></i> COMPLETE SALE
                        </button>
                        <button class="btn btn-warning" onclick="holdSale()">
                            <i class="fas fa-pause"></i> HOLD SALE
                        </button>
                        <button class="btn btn-danger" onclick="clearCart()">
                            <i class="fas fa-trash"></i> CLEAR CART
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- New Customer Modal -->
    <div class="modal fade" id="newCustomerModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">New Customer</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="newCustomerForm">
                        <div class="mb-3">
                            <label class="form-label">Name *</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Phone</label>
                            <input type="text" name="phone" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Address</label>
                            <textarea name="address" class="form-control" rows="2"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="saveNewCustomer()">Save Customer</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Hold Sale Modal -->
    <div class="modal fade" id="holdSaleModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title">Hold Sale</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Reference Note (Optional)</label>
                        <input type="text" id="holdNote" class="form-control" placeholder="e.g., Customer name or phone">
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> This sale will be saved and can be retrieved later.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-warning" onclick="saveHoldSale()">Hold Sale</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.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://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
    // Cart data structure
    let cart = [];
    let selectedPaymentMethod = 'CASH';
    
    $(document).ready(function() {
        // Initialize Select2 for customer search
        $('#customerSelect').select2({
            placeholder: 'Select customer or walk-in',
            allowClear: true
        });
        
        // Initialize categories
        initCategories();
        
        // Set cash as default payment method
        selectPaymentMethod('CASH');
        
        // Load any held sale
        loadHeldSale();
    });
    
    function initCategories() {
        const categories = new Set();
        $('.product-card').each(function() {
            const category = $(this).data('category');
            if (category) categories.add(category);
        });
        
        const container = $('#categoryFilters');
        container.empty();
        
        // Add "All" button
        container.append(`
            <button class="btn btn-sm btn-primary category-btn" onclick="filterByCategory('all')">
                All Products
            </button>
        `);
        
        // Add category buttons
        categories.forEach(category => {
            container.append(`
                <button class="btn btn-sm btn-outline-secondary category-btn" onclick="filterByCategory('${category}')">
                    ${category}
                </button>
            `);
        });
    }
    
    function filterByCategory(category) {
        if (category === 'all') {
            $('.product-card').show();
            $('.category-btn').removeClass('btn-primary').addClass('btn-outline-secondary');
            $('.category-btn:first').removeClass('btn-outline-secondary').addClass('btn-primary');
            return;
        }
        
        $('.product-card').hide();
        $(`.product-card[data-category="${category}"]`).show();
        
        // Update button styles
        $('.category-btn').removeClass('btn-primary').addClass('btn-outline-secondary');
        $(`.category-btn:contains("${category}")`).removeClass('btn-outline-secondary').addClass('btn-primary');
        $('.category-btn:contains("All Products")').removeClass('btn-primary').addClass('btn-outline-secondary');
    }
    
    $('#productSearch').on('keyup', function() {
        const searchTerm = $(this).val().toLowerCase();
        
        if (searchTerm.length === 0) {
            $('.product-card').show();
            return;
        }
        
        $('.product-card').each(function() {
            const searchData = $(this).data('search');
            if (searchData.includes(searchTerm)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
    
    function clearSearch() {
        $('#productSearch').val('');
        $('.product-card').show();
        filterByCategory('all');
    }
    
    function addToCart(productId, batchId, productName, price, maxQty) {
        // Check if product already in cart
        const existingItem = cart.find(item => item.batch_id === batchId);
        
        if (existingItem) {
            if (existingItem.qty >= maxQty) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Stock Limit',
                    text: `Only ${maxQty} units available in stock`,
                    timer: 2000
                });
                return;
            }
            existingItem.qty += 1;
            updateCartItem(existingItem);
        } else {
            if (maxQty <= 0) {
                Swal.fire({
                    icon: 'error',
                    title: 'Out of Stock',
                    text: 'This product is out of stock',
                    timer: 2000
                });
                return;
            }
            
            const newItem = {
                product_id: productId,
                batch_id: batchId,
                name: productName,
                price: price,
                qty: 1,
                max_qty: maxQty
            };
            cart.push(newItem);
            addCartItemToDOM(newItem);
        }
        
        updateCartDisplay();
        showSuccessMessage('Added to cart');
    }
    
    function addCartItemToDOM(item) {
        const cartItems = $('#cartItems');
        const emptyMsg = $('#emptyCartMessage');
        
        if (emptyMsg.is(':visible')) {
            emptyMsg.hide();
        }
        
        const itemHtml = `
            <div class="cart-item" id="cartItem_${item.batch_id}">
                <div style="flex: 2;">
                    <div class="fw-bold">${item.name}</div>
                    <small class="text-muted">TZS ${item.price.toFixed(2)} each</small>
                </div>
                <div class="quantity-controls">
                    <button class="btn btn-sm btn-outline-secondary qty-btn" onclick="updateCartQty(${item.batch_id}, -1)">
                        <i class="fas fa-minus"></i>
                    </button>
                    <input type="number" class="form-control form-control-sm item-qty" 
                           value="${item.qty}" min="1" max="${item.max_qty}"
                           onchange="setCartQty(${item.batch_id}, this.value)">
                    <button class="btn btn-sm btn-outline-secondary qty-btn" onclick="updateCartQty(${item.batch_id}, 1)">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
                <div class="item-total">
                    TZS ${(item.price * item.qty).toFixed(2)}
                </div>
                <div class="remove-item" onclick="removeFromCart(${item.batch_id})">
                    <i class="fas fa-trash"></i>
                </div>
            </div>
        `;
        
        cartItems.append(itemHtml);
    }
    
    function updateCartItem(item) {
        const itemElement = $(`#cartItem_${item.batch_id}`);
        itemElement.find('.item-qty').val(item.qty);
        itemElement.find('.item-total').text(`TZS ${(item.price * item.qty).toFixed(2)}`);
    }
    
    function updateCartQty(batchId, change) {
        const item = cart.find(item => item.batch_id === batchId);
        if (!item) return;
        
        const newQty = item.qty + change;
        if (newQty < 1) {
            removeFromCart(batchId);
            return;
        }
        
        if (newQty > item.max_qty) {
            Swal.fire({
                icon: 'warning',
                title: 'Stock Limit',
                text: `Only ${item.max_qty} units available in stock`,
                timer: 2000
            });
            return;
        }
        
        item.qty = newQty;
        updateCartItem(item);
        updateCartDisplay();
    }
    
    function setCartQty(batchId, qty) {
        const item = cart.find(item => item.batch_id === batchId);
        if (!item) return;
        
        qty = parseInt(qty);
        if (isNaN(qty) || qty < 1) qty = 1;
        if (qty > item.max_qty) {
            qty = item.max_qty;
            Swal.fire({
                icon: 'warning',
                title: 'Stock Limit',
                text: `Limited to ${item.max_qty} units`,
                timer: 2000
            });
        }
        
        item.qty = qty;
        updateCartItem(item);
        updateCartDisplay();
    }
    
    function removeFromCart(batchId) {
        cart = cart.filter(item => item.batch_id !== batchId);
        $(`#cartItem_${batchId}`).remove();
        updateCartDisplay();
    }
    
    function updateCartDisplay() {
        // Update cart count
        const totalItems = cart.reduce((sum, item) => sum + item.qty, 0);
        $('#cartCount').text(totalItems);
        
        // Calculate totals
        let subtotal = cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
        const discount = parseFloat($('#discountAmount').val()) || 0;
        const vat = subtotal * 0.18; // Assuming 18% VAT
        const grandTotal = subtotal - discount + vat;
        
        // Update display
        $('#subtotal').text(`TZS ${subtotal.toFixed(2)}`);
        $('#vatAmount').text(`TZS ${vat.toFixed(2)}`);
        $('#grandTotal').text(`TZS ${grandTotal.toFixed(2)}`);
        
        // Update receipt preview
        updateReceiptPreview(subtotal, discount, vat, grandTotal);
        
        // Enable/disable process button
        const processBtn = $('#processSaleBtn');
        if (cart.length > 0) {
            processBtn.prop('disabled', false);
            $('#receiptPreview').removeClass('d-none');
        } else {
            processBtn.prop('disabled', true);
            $('#receiptPreview').addClass('d-none');
            $('#emptyCartMessage').show();
        }
        
        // Auto-set amount paid to grand total for cash payments
        if (selectedPaymentMethod === 'CASH' && $('#amountPaid').val() == 0) {
            $('#amountPaid').val(grandTotal.toFixed(2));
            calculateChange();
        }
    }
    
    function updateReceiptPreview(subtotal, discount, vat, grandTotal) {
        const receiptItems = $('#receiptItems');
        receiptItems.empty();
        
        cart.forEach(item => {
            receiptItems.append(`
                <div class="receipt-item">
                    <span>${item.name} x${item.qty}</span>
                    <span>TZS ${(item.price * item.qty).toFixed(2)}</span>
                </div>
            `);
        });
        
        $('#receiptTotal').text(`TZS ${grandTotal.toFixed(2)}`);
        
        const paid = parseFloat($('#amountPaid').val()) || 0;
        $('#receiptPaid').text(`TZS ${paid.toFixed(2)}`);
        $('#receiptChange').text(`TZS ${(paid - grandTotal).toFixed(2)}`);
    }
    
    function selectPaymentMethod(method) {
        selectedPaymentMethod = method;
        
        // Update UI
        $('.payment-method-btn').removeClass('active');
        $(`#${method.toLowerCase()}Method`).addClass('active');
        
        // Auto-set amount paid for cash
        if (method === 'CASH') {
            const grandTotal = parseFloat($('#grandTotal').text().replace('TZS ', '').replace(',', ''));
            $('#amountPaid').val(grandTotal.toFixed(2));
        } else {
            $('#amountPaid').val('');
        }
        
        calculateChange();
    }
    
    function calculateChange() {
        const grandTotal = parseFloat($('#grandTotal').text().replace('TZS ', '').replace(',', '')) || 0;
        const paid = parseFloat($('#amountPaid').val()) || 0;
        const change = paid - grandTotal;
        
        $('#changeAmount').val(`TZS ${change.toFixed(2)}`);
        
        // Update receipt preview
        $('#receiptPaid').text(`TZS ${paid.toFixed(2)}`);
        $('#receiptChange').text(`TZS ${change.toFixed(2)}`);
    }
    
    function showNewCustomerModal() {
        const modal = new bootstrap.Modal(document.getElementById('newCustomerModal'));
        modal.show();
    }
    
    function saveNewCustomer() {
        const formData = new FormData(document.getElementById('newCustomerForm'));
        formData.append('shop_id', <?= $shop_id ?>);
        
        $.ajax({
            url: '../ajax/save_customer.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.status === 'success') {
                        // Add new customer to select
                        const newOption = new Option(
                            `${result.customer.name} (${result.customer.phone || ''})`,
                            result.customer.id,
                            true,
                            true
                        );
                        $('#customerSelect').append(newOption).trigger('change');
                        
                        // Close modal
                        $('#newCustomerModal').modal('hide');
                        $('#newCustomerForm')[0].reset();
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Customer Saved',
                            text: 'Customer added successfully',
                            timer: 2000
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: result.message
                        });
                    }
                } catch (e) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Invalid response from server'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to save customer'
                });
            }
        });
    }
    
    function processSale() {
        if (cart.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Empty Cart',
                text: 'Add products to cart before processing sale'
            });
            return;
        }
        
        const customerId = $('#customerSelect').val();
        const discount = parseFloat($('#discountAmount').val()) || 0;
        const paid = parseFloat($('#amountPaid').val()) || 0;
        const grandTotal = parseFloat($('#grandTotal').text().replace('TZS ', '').replace(',', '')) || 0;
        
        if (paid < grandTotal && selectedPaymentMethod !== 'CASH') {
            Swal.fire({
                icon: 'warning',
                title: 'Incomplete Payment',
                text: 'Amount paid is less than total amount'
            });
            return;
        }
        
        // Prepare sale data
        const saleData = {
            customer_id: customerId || null,
            items: cart.map(item => ({
                product_id: item.product_id,
                batch_id: item.batch_id,
                qty: item.qty,
                unit_price: item.price
            })),
            discount: discount,
            payment: {
                method: selectedPaymentMethod,
                amount: paid
            }
        };
        
        // Show confirmation
        Swal.fire({
            title: 'Confirm Sale',
            html: `Total: <strong>TZS ${grandTotal.toFixed(2)}</strong><br>
                   Paid: <strong>TZS ${paid.toFixed(2)}</strong><br>
                   Method: <strong>${selectedPaymentMethod}</strong>`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#198754',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Complete Sale',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                submitSale(saleData);
            }
        });
    }
    
    function submitSale(saleData) {
        $('#processSaleBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Processing...');
        
        $.ajax({
            url: '../ajax/process_sale.php',
            type: 'POST',
            data: JSON.stringify(saleData),
            contentType: 'application/json',
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.status === 'success') {
                        // Show success message with receipt
                        Swal.fire({
                            title: 'Sale Completed!',
                            html: `Invoice: <strong>${result.invoice_no}</strong><br>
                                   Total: <strong>TZS ${result.total.toFixed(2)}</strong><br>
                                   <small>Receipt has been generated</small>`,
                            icon: 'success',
                            showCancelButton: true,
                            confirmButtonText: 'Print Receipt',
                            cancelButtonText: 'New Sale'
                        }).then((result2) => {
                            if (result2.isConfirmed) {
                                // Print receipt
                                window.open(`../print_receipt.php?id=${result.sale_id}`, '_blank');
                            }
                            // Clear cart and reset
                            clearCart();
                            resetForm();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Sale Failed',
                            text: result.message
                        });
                        $('#processSaleBtn').prop('disabled', false).html('<i class="fas fa-check-circle"></i> COMPLETE SALE');
                    }
                } catch (e) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Invalid response from server'
                    });
                    $('#processSaleBtn').prop('disabled', false).html('<i class="fas fa-check-circle"></i> COMPLETE SALE');
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Network Error',
                    text: 'Failed to process sale. Please check connection.'
                });
                $('#processSaleBtn').prop('disabled', false).html('<i class="fas fa-check-circle"></i> COMPLETE SALE');
            }
        });
    }
    
    function holdSale() {
        if (cart.length === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Empty Cart',
                text: 'Add products to cart before holding sale'
            });
            return;
        }
        
        const modal = new bootstrap.Modal(document.getElementById('holdSaleModal'));
        modal.show();
    }
    
    function saveHoldSale() {
        const note = $('#holdNote').val();
        
        // Save to localStorage
        const holdData = {
            items: cart,
            customer_id: $('#customerSelect').val(),
            discount: $('#discountAmount').val(),
            note: note,
            timestamp: new Date().toISOString()
        };
        
        localStorage.setItem('held_sale', JSON.stringify(holdData));
        
        Swal.fire({
            icon: 'success',
            title: 'Sale Held',
            text: 'Sale has been saved. You can retrieve it later.',
            timer: 2000
        }).then(() => {
            $('#holdSaleModal').modal('hide');
            clearCart();
            $('#holdNote').val('');
        });
    }
    
    function loadHeldSale() {
        const heldData = localStorage.getItem('held_sale');
        if (!heldData) return;
        
        Swal.fire({
            title: 'Held Sale Found',
            text: 'Do you want to load the held sale?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Load',
            cancelButtonText: 'Discard'
        }).then((result) => {
            if (result.isConfirmed) {
                const data = JSON.parse(heldData);
                
                // Clear current cart
                cart = [];
                $('#cartItems').empty();
                
                // Load held items
                data.items.forEach(item => {
                    cart.push(item);
                    addCartItemToDOM(item);
                });
                
                // Load other data
                if (data.customer_id) {
                    $('#customerSelect').val(data.customer_id).trigger('change');
                }
                if (data.discount) {
                    $('#discountAmount').val(data.discount);
                }
                
                updateCartDisplay();
                
                // Remove from localStorage
                localStorage.removeItem('held_sale');
                
                Swal.fire({
                    icon: 'success',
                    title: 'Sale Loaded',
                    text: 'Held sale has been loaded to cart',
                    timer: 2000
                });
            } else {
                // Discard held sale
                localStorage.removeItem('held_sale');
            }
        });
    }
    
    function clearCart() {
        Swal.fire({
            title: 'Clear Cart?',
            text: 'This will remove all items from the cart',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Clear',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                cart = [];
                $('#cartItems').empty();
                updateCartDisplay();
                $('#emptyCartMessage').show();
            }
        });
    }
    
    function resetForm() {
        $('#customerSelect').val('').trigger('change');
        $('#discountAmount').val('0');
        $('#amountPaid').val('0');
        selectPaymentMethod('CASH');
    }
    
    function showSuccessMessage(message) {
        // Create toast notification
        const toast = $(`
            <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
                <div class="toast align-items-center text-white bg-success border-0" role="alert">
                    <div class="d-flex">
                        <div class="toast-body">
                            <i class="fas fa-check-circle me-2"></i> ${message}
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                </div>
            </div>
        `);
        
        $('body').append(toast);
        const toastElement = new bootstrap.Toast(toast.find('.toast')[0]);
        toastElement.show();
        
        // Remove after animation
        setTimeout(() => {
            toast.remove();
        }, 2000);
    }
    </script>
</body>
</html>