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

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

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

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

// Generate invoice number
$invoice_no = 'SALE-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="text-success mb-0">
                <i class="fas fa-cash-register"></i> Point of Sale (POS)
            </h3>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb bg-transparent p-0">
                    <li class="breadcrumb-item"><a href="../dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="list_sales.php">Sales</a></li>
                    <li class="breadcrumb-item active">POS</li>
                </ol>
            </nav>
        </div>
        <div>
            <button type="button" class="btn btn-secondary" onclick="window.history.back()">
                <i class="fas fa-arrow-left"></i> Back
            </button>
        </div>
    </div>
    
    <!-- POS Container -->
    <div class="row">
        <!-- Product Search & Selection -->
        <div class="col-md-8">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-search"></i> Search & Add Products</h5>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-9">
                            <div class="input-group">
                                <input type="text" id="productSearch" class="form-control" 
                                       placeholder="Search by product name, SKU, or category...">
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-success w-100" onclick="openProductModal()">
                                <i class="fas fa-plus"></i> Add Product
                            </button>
                        </div>
                    </div>
                    
                    <!-- Categories Filter -->
                    <div class="mb-3" id="categoryFilters">
                        <!-- Categories will be loaded dynamically -->
                    </div>
                    
                    <!-- Products Grid -->
                    <div class="row" id="productsGrid">
                        <div class="col-12 text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <p class="mt-2">Loading products...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Cart & Payment -->
        <div class="col-md-4">
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h5 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>
                    </h5>
                </div>
                <div class="card-body">
                    <!-- Customer Section -->
                    <div class="mb-3">
                        <label class="form-label"><i class="fas fa-user"></i> Customer</label>
                        <div class="input-group">
                            <select id="customerSelect" class="form-control">
                                <option value="">Walk-in Customer</option>
                                <!-- Customers will be loaded dynamically -->
                            </select>
                            <button class="btn btn-outline-primary" type="button" onclick="openCustomerModal()">
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Cart Items -->
                    <div class="cart-items mb-3" id="cartItems" style="max-height: 300px; overflow-y: auto;">
                        <div class="text-center text-muted py-4" id="emptyCartMessage">
                            <i class="fas fa-shopping-cart fa-2x mb-2"></i>
                            <p>Cart is empty</p>
                        </div>
                    </div>
                    
                    <!-- Totals -->
                    <div class="totals-box p-3 mb-3 border rounded">
                        <div class="d-flex justify-content-between mb-2">
                            <span>Subtotal:</span>
                            <span id="subtotal">TZS 0.00</span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span>Discount:</span>
                            <div class="input-group input-group-sm" style="width: 120px;">
                                <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="d-flex justify-content-between mb-2">
                            <span>VAT:</span>
                            <span id="vatAmount">TZS 0.00</span>
                        </div>
                        <hr>
                        <div class="d-flex justify-content-between font-weight-bold">
                            <span>TOTAL:</span>
                            <span id="grandTotal">TZS 0.00</span>
                        </div>
                    </div>
                    
                    <!-- Payment -->
                    <div class="payment-section mb-3">
                        <label class="form-label"><i class="fas fa-credit-card"></i> Payment Method</label>
                        <div class="btn-group btn-group-sm w-100 mb-2" role="group">
                            <button type="button" class="btn btn-outline-primary active" data-method="CASH">CASH</button>
                            <button type="button" class="btn btn-outline-primary" data-method="M-PESA">M-PESA</button>
                            <button type="button" class="btn btn-outline-primary" data-method="TIGO-PESA">TIGO PESA</button>
                            <button type="button" class="btn btn-outline-primary" data-method="AIRTEL-MONEY">AIRTEL</button>
                            <button type="button" class="btn btn-outline-primary" data-method="CARD">CARD</button>
                        </div>
                        
                        <div class="mb-2">
                            <label class="form-label">Amount Paid</label>
                            <input type="number" id="amountPaid" class="form-control" value="0" min="0" step="0.01">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">Change</label>
                            <input type="text" id="changeAmount" class="form-control" value="TZS 0.00" readonly>
                        </div>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="d-grid gap-2">
                        <button class="btn btn-success btn-lg" 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>
</div>

<!-- Product Selection Modal -->
<div class="modal fade" id="productModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Select Product</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="productModalBody">
                <!-- Product selection form will be loaded here -->
            </div>
        </div>
    </div>
</div>

<!-- Customer Modal -->
<div class="modal fade" id="customerModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title">Add New Customer</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="customerForm">
                    <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="saveCustomer()">Save Customer</button>
            </div>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>

<!-- Include SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
    // Load products and customers
    loadProducts();
    loadCustomers();
    
    // Set up payment method buttons
    $('.btn-group button[data-method]').click(function() {
        $('.btn-group button').removeClass('active');
        $(this).addClass('active');
        updateCartDisplay();
    });
    
    // Set up search
    $('#productSearch').on('keyup', function() {
        const searchTerm = $(this).val().toLowerCase();
        filterProducts(searchTerm);
    });
    
    // Calculate change when amount paid changes
    $('#amountPaid').on('input', updateCartDisplay);
    $('#discountAmount').on('input', updateCartDisplay);
    
    // Auto-calculate totals when cart changes
    $(document).on('change', '.cart-qty', updateCartDisplay);
});

let cart = [];
let selectedPaymentMethod = 'CASH';

function loadProducts() {
    $.ajax({
        url: 'ajax/get_products.php',
        type: 'GET',
        data: { shop_id: <?= $shop_id ?> },
        success: function(response) {
            $('#productsGrid').html(response);
            initCategories();
        },
        error: function() {
            $('#productsGrid').html(`
                <div class="col-12 text-center py-4 text-danger">
                    <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                    <p>Failed to load products</p>
                </div>
            `);
        }
    });
}

function loadCustomers() {
    $.ajax({
        url: 'ajax/get_customers.php',
        type: 'GET',
        data: { shop_id: <?= $shop_id ?> },
        success: function(response) {
            $('#customerSelect').html(`
                <option value="">Walk-in Customer</option>
                ${response}
            `);
        }
    });
}

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 mb-1 me-1" onclick="filterByCategory('all')">
            All Products
        </button>
    `);
    
    // Add category buttons
    categories.forEach(category => {
        container.append(`
            <button class="btn btn-sm btn-outline-secondary mb-1 me-1" onclick="filterByCategory('${category}')">
                ${category}
            </button>
        `);
    });
}

function filterProducts(searchTerm) {
    if (searchTerm.length === 0) {
        $('.product-card').show();
        return;
    }
    
    $('.product-card').each(function() {
        const productText = $(this).text().toLowerCase();
        if (productText.includes(searchTerm)) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}

function filterByCategory(category) {
    if (category === 'all') {
        $('.product-card').show();
        $('.btn', '#categoryFilters').removeClass('btn-primary').addClass('btn-outline-secondary');
        $('#categoryFilters .btn:first').removeClass('btn-outline-secondary').addClass('btn-primary');
        return;
    }
    
    $('.product-card').hide();
    $(`.product-card[data-category="${category}"]`).show();
    
    // Update button styles
    $('.btn', '#categoryFilters').removeClass('btn-primary').addClass('btn-outline-secondary');
    $(`.btn:contains("${category}")`).removeClass('btn-outline-secondary').addClass('btn-primary');
    $('#categoryFilters .btn:contains("All Products")').removeClass('btn-primary').addClass('btn-outline-secondary');
}

function clearSearch() {
    $('#productSearch').val('');
    $('.product-card').show();
    filterByCategory('all');
}

function openProductModal() {
    // This would open a modal for manual product addition
    // For now, we'll just show a message
    Swal.fire({
        title: 'Add Product',
        text: 'To add a new product, go to the Products Management page.',
        icon: 'info',
        confirmButtonText: 'OK'
    });
}

function addProductToCart(productId) {
    $.ajax({
        url: 'ajax/get_product_details.php',
        type: 'GET',
        data: { 
            product_id: productId,
            shop_id: <?= $shop_id ?>
        },
        success: function(response) {
            $('#productModalBody').html(response);
            $('#productModal').modal('show');
        },
        error: function() {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Failed to load product details'
            });
        }
    });
}

function addToCart(productId, batchId, productName, price, qty, maxQty) {
    // Check if product already in cart
    const existingItem = cart.find(item => item.product_id === productId && item.batch_id === batchId);
    
    if (existingItem) {
        const newQty = existingItem.qty + qty;
        if (newQty > maxQty) {
            Swal.fire({
                icon: 'warning',
                title: 'Stock Limit',
                text: `Only ${maxQty} units available in stock`,
                timer: 2000
            });
            return;
        }
        existingItem.qty = newQty;
        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: qty,
            max_qty: maxQty,
            vat_percent: 0 // Will be updated from product details
        };
        cart.push(newItem);
        addCartItemToDOM(newItem);
    }
    
    updateCartDisplay();
    $('#productModal').modal('hide');
    showToast('Product added to cart');
}

function addCartItemToDOM(item) {
    const cartItems = $('#cartItems');
    const emptyMsg = $('#emptyCartMessage');
    
    if (emptyMsg.is(':visible')) {
        emptyMsg.hide();
    }
    
    const itemId = `${item.product_id}_${item.batch_id}`;
    const itemHtml = `
        <div class="cart-item mb-2 p-2 border rounded" id="cartItem_${itemId}">
            <div class="d-flex justify-content-between align-items-center">
                <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="d-flex align-items-center">
                    <button class="btn btn-sm btn-outline-secondary" onclick="updateCartQty('${itemId}', -1)">
                        <i class="fas fa-minus"></i>
                    </button>
                    <input type="number" class="form-control form-control-sm cart-qty mx-1" 
                           style="width: 60px;" value="${item.qty}" min="1" max="${item.max_qty}"
                           onchange="setCartQty('${itemId}', this.value)">
                    <button class="btn btn-sm btn-outline-secondary" onclick="updateCartQty('${itemId}', 1)">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
                <div class="ms-2 fw-bold">
                    TZS ${(item.price * item.qty).toFixed(2)}
                </div>
                <button class="btn btn-sm btn-outline-danger ms-2" onclick="removeFromCart('${itemId}')">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
    `;
    
    cartItems.append(itemHtml);
}

function updateCartItem(item) {
    const itemId = `${item.product_id}_${item.batch_id}`;
    const itemElement = $(`#cartItem_${itemId}`);
    itemElement.find('.cart-qty').val(item.qty);
    itemElement.find('.fw-bold').last().text(`TZS ${(item.price * item.qty).toFixed(2)}`);
}

function updateCartQty(itemId, change) {
    const [productId, batchId] = itemId.split('_');
    const item = cart.find(item => item.product_id == productId && item.batch_id == batchId);
    if (!item) return;
    
    const newQty = item.qty + change;
    if (newQty < 1) {
        removeFromCart(itemId);
        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(itemId, qty) {
    const [productId, batchId] = itemId.split('_');
    const item = cart.find(item => item.product_id == productId && 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(itemId) {
    const [productId, batchId] = itemId.split('_');
    cart = cart.filter(item => !(item.product_id == productId && item.batch_id == batchId));
    $(`#cartItem_${itemId}`).remove();
    updateCartDisplay();
    
    if (cart.length === 0) {
        $('#emptyCartMessage').show();
    }
}

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)}`);
    
    // Get selected payment method
    selectedPaymentMethod = $('.btn-group button.active').data('method') || 'CASH';
    
    // Calculate change
    const paid = parseFloat($('#amountPaid').val()) || 0;
    const change = paid - grandTotal;
    $('#changeAmount').val(`TZS ${change > 0 ? change.toFixed(2) : '0.00'}`);
    
    // Enable/disable process button
    const processBtn = $('#processSaleBtn');
    if (cart.length > 0) {
        processBtn.prop('disabled', false);
    } else {
        processBtn.prop('disabled', true);
    }
}

function openCustomerModal() {
    $('#customerModal').modal('show');
}

function saveCustomer() {
    const formData = new FormData(document.getElementById('customerForm'));
    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 optionText = result.customer.phone ? 
                        `${result.customer.name} (${result.customer.phone})` : 
                        result.customer.name;
                    
                    $('#customerSelect').append(`
                        <option value="${result.customer.id}" selected>
                            ${optionText}
                        </option>
                    `);
                    
                    // Close modal and reset form
                    $('#customerModal').modal('hide');
                    $('#customerForm')[0].reset();
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Customer saved 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;
    
    // Validate payment
    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>
               Change: <strong>TZS ${(paid - grandTotal).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
                    Swal.fire({
                        title: 'Sale Completed!',
                        html: `Invoice: <strong>${result.invoice_no}</strong><br>
                               Total: <strong>TZS ${result.total.toFixed(2)}</strong>`,
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: 'Print Receipt',
                        cancelButtonText: 'New Sale'
                    }).then((result2) => {
                        if (result2.isConfirmed) {
                            window.open(`print_receipt.php?id=${result.sale_id}`, '_blank');
                        }
                        // Reset for new sale
                        clearCart();
                        resetForm();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Sale Failed',
                        text: result.message
                    });
                }
            } 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'
            });
            $('#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;
    }
    
    // Save to localStorage
    const holdData = {
        items: cart,
        customer_id: $('#customerSelect').val(),
        discount: $('#discountAmount').val(),
        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(() => {
        clearCart();
    });
}

function clearCart() {
    if (cart.length === 0) return;
    
    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('');
    $('#discountAmount').val('0');
    $('#amountPaid').val('0');
    $('.btn-group button').removeClass('active');
    $('.btn-group button:first').addClass('active');
    updateCartDisplay();
}

function showToast(message) {
    // Simple toast notification
    const toast = $(`
        <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 1056">
            <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();
    
    setTimeout(() => {
        toast.remove();
    }, 2000);
}
</script>

<style>
.product-card {
    cursor: pointer;
    transition: all 0.3s;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 10px;
    margin-bottom: 10px;
}
.product-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    border-color: #0d6efd;
}
.cart-item {
    background: #f8f9fa;
}
.toast {
    font-size: 14px;
}
</style>