<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];

// Handle pre-selected customer
$preSelectedCustomer = null;
if (isset($_GET['customer_id']) && !empty($_GET['customer_id'])) {
    $customerId = intval($_GET['customer_id']);
    
    // Get customer details
    $customerQuery = "
        SELECT 
            c.ID,
            c.CustomerName,
            c.Mobile,
            c.Area,
            c.CustomerType,
            COALESCE(SUM(CASE WHEN cp.TransactionType = 'Debit' THEN cp.Amount ELSE -cp.Amount END), 0) as Outstanding
        FROM tblcustomers c
        LEFT JOIN tblcustomerpayments cp ON c.ID = cp.CustomerID AND cp.Status = 'Completed' AND cp.IsActive = 1
        WHERE c.ID = ? AND c.IsActive = 1
        GROUP BY c.ID
    ";
    $stmt = mysqli_prepare($con, $customerQuery);
    mysqli_stmt_bind_param($stmt, "i", $customerId);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if ($customer = mysqli_fetch_assoc($result)) {
        $preSelectedCustomer = $customer;
    }
}

// Handle deliver order or edit order
$orderToDeliver = null;
$orderToEdit = null;
if (isset($_GET['deliver_order']) && !empty($_GET['deliver_order'])) {
    $orderToDeliver = intval($_GET['deliver_order']);
} elseif (isset($_GET['edit_order']) && !empty($_GET['edit_order'])) {
    $orderToEdit = intval($_GET['edit_order']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    
    <title>POS System - Mariyappa Nadar Ricemill</title>
    
    <!-- Custom fonts for this template-->
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
    
    <!-- Custom styles for this template-->
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    
    <!-- POS Styles -->
    <link href="css/pos.css" rel="stylesheet">
</head>

<body id="page-top">
    <div class="pos-container">
        <!-- Amazon-style Header -->
        <div class="pos-header">
            <h1><a href="dashboard.php" class="pos-title-link"><i class="fas fa-store-alt mr-2"></i>Dashboard</a></h1>
            <div class="header-actions">
                <span class="header-badge" id="product-count">0 Products</span>
                <a href="pending-orders-management.php" class="btn btn-reports" title="View Pending Orders" style="background: #FF9900; margin-right: 8px;">
                    <i class="fas fa-bookmark mr-1"></i>Orders
                </a>
                <a href="pos-reports.php" class="btn btn-reports" title="View Reports">
                    <i class="fas fa-chart-line mr-1"></i>Reports
                </a>
            </div>
        </div>

        <!-- Main Content -->
        <div class="pos-content">
            <!-- Products Section -->
            <div class="products-section" id="products-section" style="display: none;">
                <div class="products-header">
                    <h2 class="section-title">Choose Products</h2>
                    <button class="close-products-btn" id="close-products-btn" onclick="hideProducts()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                
                <div class="search-container">
                    <input type="text" class="search-input" id="product-search" placeholder="Search for rice products, brands, or types">
                </div>

                <div class="products-grid" id="products-grid">
                    <!-- Products will be loaded here -->
                </div>
            </div>

                <!-- Shopping Cart Section -->
            <div class="cart-section">
                <div class="cart-header">
                    <h2 class="cart-title">Shopping Cart</h2>
                    <div class="cart-count" id="cart-count">0</div>
                </div>                <!-- Customer Selection -->
                <div class="customer-section">
                    <div class="customer-label">Select Customer</div>
                    <div style="position: relative;">
                        <input type="text" class="customer-input" id="customer-search" placeholder="Search by name or mobile number">
                        <div class="customer-dropdown" id="customer-dropdown"></div>
                    </div>

                    <!-- Selected Customer Info -->
                    <div id="selected-customer" style="display: none;">
                        <div class="selected-customer-info">
                            <div class="customer-name" id="customer-name"></div>
                            <div class="customer-details" id="customer-details"></div>
                            <div class="customer-actions" style="margin-top: 8px; display: flex; gap: 8px;">
                                <button class="order-btn" onclick="showProducts()" style="background: #FF9900; color: #0F1111; border: none; border-radius: 4px; padding: 6px 12px; font-size: 12px; font-weight: 600; cursor: pointer; flex: 1;">
                                    <i class="fas fa-shopping-bag mr-1"></i>Order
                                </button>
                                <button class="payment-btn" onclick="openPaymentModal()" style="background: #28a745; color: white; border: none; border-radius: 4px; padding: 6px 12px; font-size: 12px; font-weight: 600; cursor: pointer; flex: 1;">
                                    <i class="fas fa-rupee-sign mr-1"></i>Payment
                                </button>
                                <button class="history-btn" onclick="openHistoryPage()" style="background: #17a2b8; color: white; border: none; border-radius: 4px; padding: 6px 12px; font-size: 12px; font-weight: 600; cursor: pointer; flex: 1;">
                                    <i class="fas fa-history mr-1"></i>History
                                </button>
                                <button class="reminder-btn" onclick="openReminderModal()" style="background: #007185; color: white; border: none; border-radius: 4px; padding: 6px 12px; font-size: 12px; font-weight: 600; cursor: pointer; flex: 1;">
                                    <i class="fas fa-bell mr-1"></i>Reminder
                                </button>
                            </div>
                        </div>
                        <div id="customer-outstanding" style="display: none;" class="outstanding-warning">
                            <i class="fas fa-exclamation-triangle mr-1"></i>
                            <strong>Outstanding Balance: <span id="outstanding-amount">₹0</span></strong>
                        </div>
                    </div>
                </div>

                <!-- Cart Items -->
                <div class="cart-items" id="cart-items">
                    <div class="empty-cart">
                        <i class="fas fa-shopping-cart"></i>
                        <div>Your cart is empty</div>
                        <div style="font-size: 12px; margin-top: 4px;">Add items from the product catalog</div>
                    </div>
                </div>

                <!-- Cart Summary & Checkout -->
                <div class="cart-summary" id="cart-summary" style="display: none;">
                    <div class="summary-row">
                        <span>Subtotal:</span>
                        <span id="subtotal">₹0</span>
                    </div>
                    <div class="summary-row" id="discount-row" style="display: none;">
                        <span>Discount:</span>
                        <span id="discount-amount" style="color: #B12704;">-₹0</span>
                    </div>
                    <div class="summary-total">
                        <span>Order Total:</span>
                        <span id="total">₹0</span>
                    </div>
                    
                    <button class="checkout-button" id="checkout-btn" onclick="openCheckoutModal()" style="display: none;">
                        Proceed to Checkout
                    </button>
                    
                    <!-- Save as Order Button (shows when cart has items) -->
                    <button class="checkout-button" id="save-order-btn" onclick="savePendingOrder()" style="display: none; background: #FF9900; margin-bottom: 8px;">
                        <i class="fas fa-bookmark" style="margin-right: 8px;"></i>Save as Order
                    </button>
                    
                    <!-- Order Products Button (shows when cart is empty or products are hidden) -->
                    <button class="checkout-button" id="order-btn" onclick="showProducts()" style="background: #28a745;">
                        <i class="fas fa-plus" style="margin-right: 8px;"></i>Order Products
                    </button>
                    
                    <!-- Cancel Edit Button (only shown in edit mode) -->
                    <button class="checkout-button" id="cancel-edit-btn" style="display: none; background: #D13212; margin-top: 8px;" onclick="cancelEdit()">>
                        Cancel & Return to Reports
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Amazon-style Checkout Modal -->
    <div class="modal" id="checkout-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Review your order</h3>
                <button type="button" class="modal-close" onclick="closeCheckoutModal()">×</button>
            </div>
            <div class="modal-body">
                <form id="checkout-form">
                    <div class="form-group">
                        <label class="form-label">Discount Amount (Optional)</label>
                        <input type="number" class="form-control" id="discount-input" step="0.01" min="0" placeholder="Enter discount amount" onchange="updateCheckoutTotals()">
                    </div>
                    
                    <div class="checkout-summary">
                        <div class="summary-row">
                            <span>Subtotal:</span>
                            <span id="checkout-subtotal">₹0</span>
                        </div>
                        <div class="summary-row" id="checkout-discount-row" style="display: none;">
                            <span>Discount:</span>
                            <span id="checkout-discount" style="color: #B12704;">-₹0</span>
                        </div>
                        <div class="summary-total">
                            <span>Total Amount:</span>
                            <span id="checkout-total">₹0</span>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Payment Method</label>
                        <select class="form-control" id="payment-method" required>
                            <option value="Cash">Cash Payment</option>
                            <option value="UPI">UPI / Digital Payment</option>
                            <option value="Card">Credit/Debit Card</option>
                            <option value="Bank Transfer">Bank Transfer</option>
                            <option value="Cheque">Cheque</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Amount Received</label>
                        <input type="number" class="form-control" id="amount-received" step="0.01" required placeholder="Enter amount" onchange="calculateChange()">
                        <div id="change-amount" style="margin-top: 5px; font-weight: bold; color: #1cc88a; display: none;">
                            Change: <span id="change-value">₹0</span>
                        </div>
                    </div>
                    
                    <div class="form-group" id="reference-group" style="display: none;">
                        <label class="form-label">Transaction Reference</label>
                        <input type="text" class="form-control" id="reference-number" placeholder="UPI ID, Transaction ID, or Reference Number">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Order Notes (Optional)</label>
                        <textarea class="form-control" id="sale-notes" rows="3" placeholder="Add any special instructions or notes..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn-secondary" onclick="closeCheckoutModal()">Cancel</button>
                <button type="submit" class="btn-primary" form="checkout-form">
                    Complete Order
                </button>
            </div>
        </div>
    </div>

    <!-- Payment Modal -->
    <div class="modal" id="payment-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Record Payment</h3>
                <button type="button" class="modal-close" onclick="closePaymentModal()">×</button>
            </div>
            <div class="modal-body">
                <form id="payment-form">
                    <div class="form-group">
                        <label class="form-label">Customer</label>
                        <input type="text" class="form-control" id="payment-customer-name" readonly style="background: #f8f9fa;">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Transaction Type</label>
                        <select class="form-control" id="payment-transaction-type" required>
                            <option value="Credit">Credit (Money Received)</option>
                            <option value="Debit">Debit (Money Paid)</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Payment Amount (₹)</label>
                        <input type="number" class="form-control" id="payment-amount" placeholder="Enter amount" step="0.01" min="0" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Payment Method</label>
                        <select class="form-control" id="payment-method-select" required>
                            <option value="Cash">Cash</option>
                            <option value="Bank Transfer">Bank Transfer</option>
                            <option value="UPI">UPI</option>
                            <option value="Cheque">Cheque</option>
                            <option value="Card">Card</option>
                            <option value="Online">Online</option>
                        </select>
                    </div>
                    
                    <div class="form-group" id="payment-reference-group" style="display: none;">
                        <label class="form-label">Reference Number</label>
                        <input type="text" class="form-control" id="payment-reference" placeholder="Enter reference/transaction number">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Description (Optional)</label>
                        <textarea class="form-control" id="payment-description" rows="2" placeholder="Enter payment description"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Payment Date</label>
                        <input type="date" class="form-control" id="payment-date" required>
                    </div>
                </form>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn-secondary" onclick="closePaymentModal()">Cancel</button>
                <button type="submit" class="btn-primary" form="payment-form">Record Payment</button>
            </div>
        </div>
    </div>

    <!-- Reminder Modal -->
    <div class="modal" id="reminder-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">Customer Reminders</h3>
                <button type="button" class="modal-close" onclick="closeReminderModal()">×</button>
            </div>
            <div class="modal-body">
                <!-- Add New Reminder Form -->
                <div class="form-group">
                    <h4 style="margin-bottom: 12px; font-size: 16px; color: #0F1111;">Add New Reminder</h4>
                    <form id="reminder-form">
                        <div class="form-group">
                            <label class="form-label">Reminder Date & Time</label>
                            <input type="datetime-local" class="form-control" id="reminder-datetime" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Reminder Note</label>
                            <textarea class="form-control" id="reminder-text" rows="3" placeholder="Enter reminder details..." required></textarea>
                        </div>
                        
                        <button type="submit" class="btn-primary" style="width: 100%; margin-bottom: 16px;">
                            <i class="fas fa-bell mr-1"></i>Add Reminder
                        </button>
                    </form>
                </div>
                
                <!-- Latest Reminder -->
                <div class="form-group">
                    <h4 style="margin-bottom: 12px; font-size: 16px; color: #0F1111;">Latest Reminder</h4>
                    <div id="reminders-list" style="max-height: 200px; overflow-y: auto;">
                        <!-- Latest reminder will be loaded here -->
                    </div>
                </div>
            </div>
            <div class="modal-actions">
                <button type="button" class="btn-secondary" onclick="closeReminderModal()">Close</button>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- POS JavaScript -->
    <script>
        let cart = [];
        let selectedCustomer = null;
        let products = [];
    let editMode = false;
    let editSaleId = null;
    let editSaleData = null; // holds existing sale data when editing

        // Initialize POS
        $(document).ready(function() {
            // Check if we're in edit mode
            const urlParams = new URLSearchParams(window.location.search);
            editSaleId = urlParams.get('edit');
            const deliverOrderId = urlParams.get('deliver_order');
            const editOrderId = urlParams.get('edit_order');
            
            if (editSaleId) {
                editMode = true;
                loadExistingSale(editSaleId);
            } else if (deliverOrderId) {
                // Load pending order for delivery
                loadPendingOrderForDelivery(deliverOrderId);
            } else if (editOrderId) {
                // Load pending order for editing
                loadPendingOrderForEdit(editOrderId);
            }
            
            // Check for pre-selected customer
            <?php if ($preSelectedCustomer): ?>
            selectCustomer(
                <?php echo $preSelectedCustomer['ID']; ?>,
                '<?php echo addslashes($preSelectedCustomer['CustomerName']); ?>',
                '<?php echo addslashes($preSelectedCustomer['Mobile']); ?>',
                '<?php echo addslashes($preSelectedCustomer['Area']); ?>',
                '<?php echo addslashes($preSelectedCustomer['CustomerType']); ?>',
                <?php echo $preSelectedCustomer['Outstanding']; ?>
            );
            <?php endif; ?>
            
            loadProducts();
            setupEventListeners();
            handleResize();
            updateLayout();
            updateCartButtonVisibility(); // Initialize button visibility
        });

        // Update layout based on products visibility
        function updateLayout() {
            const productsVisible = $('#products-section').is(':visible');
            if (productsVisible) {
                $('.pos-content').removeClass('products-hidden');
            } else {
                $('.pos-content').addClass('products-hidden');
            }
        }

        // Show products section when Order button is clicked
        function showProducts() {
            $('#products-section').show();
            $('#order-btn').hide();
            updateLayout();
        }

        // Hide products section when close button is clicked
        function hideProducts() {
            $('#products-section').hide();
            updateCartButtonVisibility();
            updateLayout();
        }

        // Load existing sale for editing
        function loadExistingSale(saleId) {
            $.ajax({
                url: 'api/get-payment-details.php',
                method: 'GET',
                data: { id: saleId, include_items: true },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        const saleData = response.data;
                        editSaleData = saleData; // store for pre-filling checkout
                        
                        // Load customer
                        if (saleData.CustomerID) {
                            selectedCustomer = {
                                ID: saleData.CustomerID,
                                CustomerName: saleData.CustomerName,
                                Mobile: saleData.MobileNumber || '',
                                Area: '',
                                CustomerType: 'Retail', // Default, will be updated when products load
                                Outstanding: 0
                            };
                            
                            $('#customer-search').val(saleData.CustomerName);
                            $('#customer-name').text(saleData.CustomerName);
                            $('#customer-details').text(`${saleData.MobileNumber || 'No mobile'} • ${selectedCustomer.CustomerType} Customer`);
                            $('#selected-customer').show();
                        }
                        
                        // Update header to show edit mode
                        $('.pos-header h1').html('<i class="fas fa-edit mr-2"></i>Edit Sale #' + saleData.SaleNumber);
                        $('.btn-reports').text('Back to Reports').attr('href', 'pos-reports.php');
                        $('#checkout-btn').text('Update Sale');
                        $('#cancel-edit-btn').show();
                        
                        // Load items when products are ready
                        setTimeout(() => {
                            loadSaleItems(saleData.items || []);
                        }, 1000);
                        
                    } else {
                        alert('Error loading sale details: ' + response.message);
                        window.location.href = 'pos-reports.php';
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading sale:', error);
                    alert('Error loading sale details');
                    window.location.href = 'pos-reports.php';
                }
            });
        }

        // Load sale items into cart
        function loadSaleItems(items) {
            cart = [];
            
            items.forEach(item => {
                const product = products.find(p => p.ID == item.RiceBagID);
                if (product) {
                    cart.push({
                        product: product,
                        quantity: parseFloat(item.Quantity)
                    });
                }
            });
            
            renderCart();
            updateCartSummary();
            renderProducts(products); // Re-render products to show quantity controls
        }

        // Load pending order for delivery
        function loadPendingOrderForDelivery(orderId) {
            $.ajax({
                url: 'api/pending-orders.php',
                method: 'GET',
                data: { id: orderId },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        const orderData = response.data;
                        
                        // Load customer
                        selectCustomer(
                            orderData.CustomerID,
                            orderData.CustomerName,
                            orderData.Mobile,
                            orderData.Area,
                            orderData.CustomerType,
                            0 // Outstanding will be fetched separately if needed
                        );
                        
                        // Update header to show delivery mode
                        $('.pos-header h1').html('<i class="fas fa-truck mr-2"></i>Deliver Order #' + orderData.OrderNumber);
                        $('#checkout-btn').text('Complete Delivery');
                        
                        // Load items when products are ready
                        setTimeout(() => {
                            loadPendingOrderItems(orderData.items || []);
                        }, 1000);
                        
                    } else {
                        alert('Error loading order: ' + response.message);
                        window.location.href = 'pending-orders-management.php';
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading order:', error);
                    alert('Error loading order details');
                    window.location.href = 'pending-orders-management.php';
                }
            });
        }

        // Load pending order for editing
        function loadPendingOrderForEdit(orderId) {
            $.ajax({
                url: 'api/pending-orders.php',
                method: 'GET',
                data: { id: orderId },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        const orderData = response.data;
                        
                        // Load customer
                        selectCustomer(
                            orderData.CustomerID,
                            orderData.CustomerName,
                            orderData.Mobile,
                            orderData.Area,
                            orderData.CustomerType,
                            0 // Outstanding will be fetched separately if needed
                        );
                        
                        // Update header to show edit mode
                        $('.pos-header h1').html('<i class="fas fa-edit mr-2"></i>Edit Order #' + orderData.OrderNumber);
                        $('.btn-reports').text('Back to Orders').attr('href', 'pending-orders-management.php');
                        $('#checkout-btn').text('Save Order');
                        $('#save-order-btn').text('Update Order');
                        
                        // Store order data for updating
                        editSaleData = orderData;
                        editSaleId = orderId;
                        editMode = true;
                        
                        // Load items when products are ready
                        setTimeout(() => {
                            loadPendingOrderItems(orderData.items || []);
                        }, 1000);
                        
                    } else {
                        alert('Error loading order: ' + response.message);
                        window.location.href = 'pending-orders-management.php';
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading order:', error);
                    alert('Error loading order details');
                    window.location.href = 'pending-orders-management.php';
                }
            });
        }

        // Load pending order items into cart
        function loadPendingOrderItems(items) {
            cart = [];
            
            items.forEach(item => {
                const product = products.find(p => p.ID == item.ProductID);
                if (product) {
                    cart.push({
                        product: product,
                        quantity: parseFloat(item.Quantity)
                    });
                }
            });
            
            renderCart();
            updateCartSummary();
            renderProducts(products); // Re-render products to show quantity controls
        }

        // Handle window resize for responsive behavior
        function handleResize() {
            $(window).on('resize', function() {
                renderProducts(products);
            });
        }

        // Load products from API
        function loadProducts() {
            $.ajax({
                url: 'api/get-rice-bag.php',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        products = response.data;
                        renderProducts(products);
                        $('#product-count').text(products.length + ' Products');
                    } else {
                        console.error('Failed to load products:', response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading products:', error);
                }
            });
        }

        // Render products grid
        function renderProducts(productsToShow) {
            const grid = $('#products-grid');
            grid.empty();

            if (productsToShow.length === 0) {
                grid.html('<div class="col-12 text-center text-muted py-4"><i class="fas fa-box-open fa-2x mb-2"></i><p>No products found</p></div>');
                return;
            }

            productsToShow.forEach(product => {
                const productCard = createProductCard(product);
                grid.append(productCard);
            });
        }

        // Create product card HTML
        function createProductCard(product) {
            const imageSrc = product.ProductImage ? product.ProductImage : '';
            const imageHtml = imageSrc ? 
                `<img src="${imageSrc}" alt="${product.RiceBagName}">` :
                `<i class="fas fa-seedling"></i>`;

            const rate = selectedCustomer && selectedCustomer.CustomerType === 'Shop' ? 
                product.ShopRate : product.RetailRate;

            const stockClass = product.StockInBags < 2 ? 'low' : '';
            const stockText = product.StockInBags > 0 ? 
                `In Stock (${product.StockInBags} bags)` : 
                'Out of Stock';

            // Check if product is in cart
            const cartItem = cart.find(item => item.product.ID == product.ID);
            const quantity = cartItem ? cartItem.quantity : 0;

            return `
                <div class="product-card" ${product.StockInBags <= 0 ? 'style="opacity: 0.6; cursor: not-allowed;"' : ''}>
                    <div class="product-image">${imageHtml}</div>
                    <div class="product-title">${product.RiceBagName}</div>
                    <div class="product-price">
                        <span class="currency">₹</span>${parseFloat(rate * product.BagKg).toFixed(0)}
                        <span style="font-size: 12px; color: #565959; font-weight: normal;">/bag (${product.BagKg}kg)</span>
                    </div>
                    <div class="product-stock ${stockClass}">${stockText}</div>
                    
                    ${quantity > 0 ? `
                        <div class="quantity-controls-product">
                            <button class="qty-btn-product" onclick="updateProductQuantity(${product.ID}, ${quantity - 1})">
                                ${quantity <= 1 ? '<i class="fas fa-trash"></i>' : '-'}
                            </button>
                            <span class="qty-display-product">${quantity}</span>
                            <button class="qty-btn-product" onclick="updateProductQuantity(${product.ID}, ${quantity + 1})" ${quantity >= product.StockInBags ? 'disabled' : ''}>
                                +
                            </button>
                        </div>
                    ` : `
                        <button class="add-btn" onclick="addToCart(${product.ID})" ${product.StockInBags <= 0 ? 'disabled style="opacity: 0.5; cursor: not-allowed;"' : ''}>
                            ${product.StockInBags <= 0 ? 'Out of Stock' : 'Add to Cart'}
                        </button>
                    `}
                </div>
            `;
        }

        // Add product to cart
        function addToCart(productId) {
            const product = products.find(p => p.ID == productId);
            if (!product) return;

            if (product.StockInBags <= 0) {
                alert('Product is out of stock!');
                return;
            }

            const existingItem = cart.find(item => item.product.ID == productId);
            if (existingItem) {
                if (existingItem.quantity + 1 <= product.StockInBags) {
                    existingItem.quantity += 1;
                } else {
                    alert('Insufficient stock!');
                    return;
                }
            } else {
                cart.push({
                    product: product,
                    quantity: 1
                });
            }

            renderCart();
            updateCartSummary();
            renderProducts(products); // Re-render to show quantity controls
        }

        // Update product quantity from product card
        function updateProductQuantity(productId, newQuantity) {
            const product = products.find(p => p.ID == productId);
            if (!product) return;

            if (newQuantity <= 0) {
                // Remove from cart
                const itemIndex = cart.findIndex(item => item.product.ID == productId);
                if (itemIndex > -1) {
                    cart.splice(itemIndex, 1);
                }
            } else {
                if (newQuantity > product.StockInBags) {
                    alert('Insufficient stock!');
                    return;
                }

                const existingItem = cart.find(item => item.product.ID == productId);
                if (existingItem) {
                    existingItem.quantity = newQuantity;
                } else {
                    cart.push({
                        product: product,
                        quantity: newQuantity
                    });
                }
            }

            renderCart();
            updateCartSummary();
            renderProducts(products); // Re-render to update quantity controls
        }

        // Render cart items
        function renderCart() {
            const cartContainer = $('#cart-items');
            cartContainer.empty();

            if (cart.length === 0) {
                cartContainer.html(`
                    <div class="empty-cart">
                        <i class="fas fa-shopping-cart"></i>
                        <div>Your cart is empty</div>
                        <div style="font-size: 12px; margin-top: 4px;">Add items from the product catalog</div>
                    </div>
                `);
                $('#cart-summary').hide();
                $('#cart-count').text('0');
                updateCartButtonVisibility();
                return;
            }

            cart.forEach((item, index) => {
                const rate = selectedCustomer && selectedCustomer.CustomerType === 'Shop' ? 
                    item.product.ShopRate : item.product.RetailRate;
                // Calculate price per bag (rate per kg * kg per bag)
                const bagPrice = rate * item.product.BagKg;

                const imageSrc = item.product.ProductImage ? item.product.ProductImage : '';
                const imageHtml = imageSrc ? 
                    `<img src="${imageSrc}" alt="${item.product.RiceBagName}">` :
                    `<i class="fas fa-seedling"></i>`;

                const cartItemHtml = `
                    <div class="cart-item">
                        <div class="item-image">${imageHtml}</div>
                        <div class="item-details">
                            <div class="item-name">${item.product.RiceBagName}</div>
                            <div class="item-price">₹${parseFloat(bagPrice).toFixed(0)} per bag (${item.product.BagKg}kg)</div>
                            <div class="quantity-controls">
                                <button class="qty-btn" onclick="updateQuantity(${index}, ${item.quantity - 1})">−</button>
                                <div class="qty-display">${item.quantity} bag${item.quantity > 1 ? 's' : ''}</div>
                                <button class="qty-btn" onclick="updateQuantity(${index}, ${item.quantity + 1})">+</button>
                            </div>
                            <button class="remove-item" onclick="removeFromCart(${index})">Remove</button>
                        </div>
                    </div>
                `;
                cartContainer.append(cartItemHtml);
            });

            $('#cart-summary').show();
            $('#cart-count').text(cart.length);
            updateCartButtonVisibility();
        }

        // Update cart button visibility
        function updateCartButtonVisibility() {
            if (cart.length > 0) {
                $('#checkout-btn').show();
                $('#save-order-btn').show(); // Show save as order button when cart has items
                $('#order-btn').hide();
            } else {
                $('#checkout-btn').hide();
                $('#save-order-btn').hide();
                if (!$('#products-section').is(':visible')) {
                    $('#order-btn').show();
                }
            }
        }

        // Update item quantity
        function updateQuantity(index, newQuantity) {
            newQuantity = parseInt(newQuantity);
            if (newQuantity <= 0) {
                removeFromCart(index);
                return;
            }

            const item = cart[index];
            if (newQuantity > item.product.StockInBags) {
                alert('Insufficient stock!');
                return;
            }

            cart[index].quantity = newQuantity;
            renderCart();
            updateCartSummary();
            renderProducts(products); // Re-render to update quantity controls
        }

        // Remove item from cart
        function removeFromCart(index) {
            cart.splice(index, 1);
            renderCart();
            updateCartSummary();
            renderProducts(products); // Re-render to update quantity controls
        }

        // Update cart summary
        function updateCartSummary() {
            let subtotal = 0;

            cart.forEach(item => {
                const rate = selectedCustomer && selectedCustomer.CustomerType === 'Shop' ? 
                    item.product.ShopRate : item.product.RetailRate;
                // Calculate price per bag (rate per kg * kg per bag)
                const bagPrice = rate * item.product.BagKg;
                subtotal += bagPrice * item.quantity;
            });

            $('#subtotal').text('₹' + subtotal.toFixed(0));
            $('#total').text('₹' + subtotal.toFixed(0));
            // In edit mode, keep previously paid amount; otherwise suggest total
            const currentAmt = $('#amount-received').val();
            if (!editMode) {
                $('#amount-received').val(subtotal.toFixed(2));
            } else if (!currentAmt) {
                // only set if empty
                $('#amount-received').val(subtotal.toFixed(2));
            }
            
            // Update checkout modal totals
            updateCheckoutTotals();
        }

        // Update checkout totals with discount
        function updateCheckoutTotals() {
            let subtotal = 0;
            cart.forEach(item => {
                const rate = selectedCustomer && selectedCustomer.CustomerType === 'Shop' ? 
                    item.product.ShopRate : item.product.RetailRate;
                // Calculate price per bag (rate per kg * kg per bag)
                const bagPrice = rate * item.product.BagKg;
                subtotal += bagPrice * item.quantity;
            });

            const discount = parseFloat($('#discount-input').val() || 0);
            const total = Math.max(0, subtotal - discount);

            $('#checkout-subtotal').text('₹' + subtotal.toFixed(0));
            $('#checkout-total').text('₹' + total.toFixed(0));
            
            if (discount > 0) {
                $('#checkout-discount').text('-₹' + discount.toFixed(0));
                $('#checkout-discount-row').show();
                $('#discount-amount').text('-₹' + discount.toFixed(0));
                $('#discount-row').show();
            } else {
                $('#checkout-discount-row').hide();
                $('#discount-row').hide();
            }
            
            // Update total in main cart summary
            $('#total').text('₹' + total.toFixed(0));
            
            // Update amount received suggestion
            $('#amount-received').attr('placeholder', 'Enter amount (Total: ₹' + total.toFixed(0) + ')');
            
            calculateChange();
        }

        // Calculate change amount
        function calculateChange() {
            const subtotal = cart.reduce((sum, item) => {
                const rate = selectedCustomer && selectedCustomer.CustomerType === 'Shop' ? 
                    item.product.ShopRate : item.product.RetailRate;
                // Calculate price per bag (rate per kg * kg per bag)
                const bagPrice = rate * item.product.BagKg;
                return sum + (bagPrice * item.quantity);
            }, 0);
            
            const discount = parseFloat($('#discount-input').val() || 0);
            const total = Math.max(0, subtotal - discount);
            const received = parseFloat($('#amount-received').val() || 0);
            const change = received - total;

            if (received > 0 && change > 0) {
                $('#change-value').text('₹' + change.toFixed(2));
                $('#change-amount').show();
            } else {
                $('#change-amount').hide();
            }
        }

        // Setup event listeners
        function setupEventListeners() {
            // Product search
            $('#product-search').on('input', function() {
                const searchTerm = $(this).val().toLowerCase();
                const filteredProducts = products.filter(product => 
                    product.RiceBagName.toLowerCase().includes(searchTerm) ||
                    product.Brand.toLowerCase().includes(searchTerm) ||
                    product.ManufactureType.toLowerCase().includes(searchTerm)
                );
                renderProducts(filteredProducts);
            });

            // Customer search
            $('#customer-search').on('input', function() {
                const searchTerm = $(this).val();
                if (searchTerm.length >= 2) {
                    searchCustomers(searchTerm);
                } else {
                    $('#customer-dropdown').hide();
                }
            });

            // Payment method change
            $('#payment-method').on('change', function() {
                const method = $(this).val();
                if (method === 'Bank Transfer' || method === 'UPI' || method === 'Cheque') {
                    $('#reference-group').show();
                } else {
                    $('#reference-group').hide();
                }
            });

            // Checkout form submission
            $('#checkout-form').on('submit', function(e) {
                e.preventDefault();
                processCheckout();
            });

            // Reminder form submission
            $('#reminder-form').on('submit', function(e) {
                e.preventDefault();
                addReminder();
            });

            // Payment form submission
            $('#payment-form').on('submit', function(e) {
                e.preventDefault();
                processPayment();
            });

            // Payment method change for payment modal
            $('#payment-method-select').on('change', function() {
                const method = $(this).val();
                if (method === 'Bank Transfer' || method === 'UPI' || method === 'Cheque' || method === 'Card' || method === 'Online') {
                    $('#payment-reference-group').show();
                } else {
                    $('#payment-reference-group').hide();
                }
            });

            // Click outside to close customer dropdown
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.customer-section').length) {
                    $('#customer-dropdown').hide();
                }
            });
        }

        // Search customers
        function searchCustomers(searchTerm) {
            $.ajax({
                url: 'api/get-customers-search.php',
                method: 'GET',
                data: { search: searchTerm },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        renderCustomerDropdown(response.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error searching customers:', error);
                }
            });
        }

        // Render customer dropdown
        function renderCustomerDropdown(customers) {
            const dropdown = $('#customer-dropdown');
            dropdown.empty();

            if (customers.length === 0) {
                dropdown.html('<div class="customer-option">No customers found</div>');
            } else {
                customers.forEach(customer => {
                    const customerHtml = `
                        <div class="customer-option" onclick="selectCustomer(${customer.ID}, '${customer.CustomerName}', '${customer.Mobile}', '${customer.Area}', '${customer.CustomerType}', ${customer.Outstanding || 0})">
                            <div class="customer-name">${customer.CustomerName}</div>
                            <div class="customer-details">${customer.Mobile} • ${customer.CustomerType} Customer</div>
                            ${customer.Outstanding > 0 ? `<div style="font-size: 11px; color: #B12704; margin-top: 2px;">Outstanding: ₹${customer.Outstanding.toFixed(0)}</div>` : ''}
                        </div>
                    `;
                    dropdown.append(customerHtml);
                });
            }

            dropdown.show();
        }

        // Select customer
        function selectCustomer(id, name, mobile, area, type, outstanding) {
            selectedCustomer = {
                ID: id,
                CustomerName: name,
                Mobile: mobile,
                Area: area,
                CustomerType: type,
                Outstanding: outstanding
            };

            $('#customer-search').val(name);
            $('#customer-name').text(name);
            $('#customer-details').text(`${mobile} • ${area} • ${type} Customer`);
            
            if (outstanding > 0) {
                $('#outstanding-amount').text('₹' + outstanding.toFixed(0));
                $('#customer-outstanding').show();
            } else {
                $('#customer-outstanding').hide();
            }

            $('#selected-customer').show();
            $('#customer-dropdown').hide();

            // Re-render products with updated pricing
            renderProducts(products);
            renderCart();
            updateCartSummary();
        }

        // Open checkout modal
        function openCheckoutModal() {
            if (cart.length === 0) {
                alert('Cart is empty!');
                return;
            }
            if (!selectedCustomer) {
                alert('Please select a customer!');
                return;
            }
            
            // Reset checkout form defaults
            if (!editMode) {
                $('#discount-input').val('');
                $('#payment-method').val('Cash');
                $('#reference-number').val('');
                $('#sale-notes').val('');
            }
            
            // Update modal title for edit mode
            if (editMode) {
                $('.modal-title').text('Update Order');
                $('button[form="checkout-form"]').text('Update Order');
                // Prefill fields from existing sale
                if (editSaleData) {
                    const paid = parseFloat(editSaleData.PaidAmount || 0) || 0;
                    const disc = parseFloat(editSaleData.DiscountAmount || 0) || 0;
                    $('#discount-input').val(disc ? disc.toFixed(2) : '');
                    if (editSaleData.PaymentMethod) {
                        $('#payment-method').val(editSaleData.PaymentMethod);
                    }
                    $('#amount-received').val(paid.toFixed(2));
                    if (editSaleData.ReferenceNumber) {
                        $('#reference-number').val(editSaleData.ReferenceNumber);
                    }
                    if (editSaleData.Description) {
                        $('#sale-notes').val(editSaleData.Description);
                    }
                }
                // Update totals and change display based on prefilled values
                updateCheckoutTotals();
                calculateChange();
            } else {
                $('.modal-title').text('Review your order');
                $('button[form="checkout-form"]').text('Complete Order');
                updateCheckoutTotals();
            }
            
            $('#checkout-modal').show();
        }

        // Cancel edit and return to reports
        function cancelEdit() {
            if (confirm('Are you sure you want to cancel editing? Any changes will be lost.')) {
                window.location.href = 'pos-reports.php';
            }
        }

        // Close checkout modal
        function closeCheckoutModal() {
            $('#checkout-modal').hide();
        }

        // Process checkout
        function processCheckout() {
            const discount = parseFloat($('#discount-input').val() || 0);
            const urlParams = new URLSearchParams(window.location.search);
            const deliverOrderId = urlParams.get('deliver_order');
            const editOrderId = urlParams.get('edit_order');
            
            const saleData = {
                customer_id: selectedCustomer.ID,
                payment_method: $('#payment-method').val(),
                amount_received: parseFloat($('#amount-received').val()),
                reference_number: $('#reference-number').val(),
                notes: $('#sale-notes').val(),
                discount_amount: discount,
                cart_items: cart.map(item => ({
                    product_id: item.product.ID,
                    quantity: item.quantity, // quantity in bags
                    rate: selectedCustomer.CustomerType === 'Shop' ? item.product.ShopRate : item.product.RetailRate, // rate per kg
                    bag_kg: item.product.BagKg // kg per bag
                }))
            };
            
            let apiUrl = 'api/process-sale-detailed.php?debug=1';
            
            // Handle different modes
            if (deliverOrderId) {
                // For delivery, create sale and mark order as delivered
                saleData.pending_order_id = deliverOrderId;
            } else if (editOrderId) {
                // For order editing, update the pending order
                apiUrl = 'api/pending-orders.php';
                saleData.order_id = editOrderId;
            } else if (editMode && editSaleId) {
                // For sale editing
                saleData.sale_id = editSaleId;
                apiUrl = 'api/update-sale.php';
            }

            const method = editOrderId ? 'PUT' : 'POST';

            $.ajax({
                url: apiUrl,
                method: method,
                data: JSON.stringify(saleData),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        const saleInfo = response.data;
                        let message = editMode ? 
                            `Sale updated successfully!\n\n` : 
                            `Sale completed successfully!\n\n`;
                        message += `Sale Number: ${saleInfo.sale_number}\n`;
                        message += `Total Amount: ₹${saleInfo.total_amount}\n`;
                        message += `Paid Amount: ₹${saleInfo.paid_amount}\n`;
                        
                        if (saleInfo.balance_amount > 0) {
                            message += `Balance Due: ₹${saleInfo.balance_amount}\n`;
                        }
                        
                        if (saleInfo.change_amount > 0) {
                            message += `Change: ₹${saleInfo.change_amount}\n`;
                        }
                        
                        message += `\nPayment Status: ${saleInfo.payment_status}`;
                        
                        alert(message);
                        
                        // Show receipt printing options
                        if (!editMode && confirm('Sale completed successfully! Would you like to print a receipt?')) {
                            printReceipt(saleInfo.sale_id);
                        }
                        
                        // Redirect back to reports after successful update/creation
                        if (editMode) {
                            window.location.href = 'pos-reports.php';
                        } else {
                            // Reset cart and customer for new sale
                            cart = [];
                            selectedCustomer = null;
                            $('#customer-search').val('');
                            $('#selected-customer').hide();
                            $('#discount-input').val('');
                            
                            renderCart();
                            updateCartSummary();
                            closeCheckoutModal();
                            loadProducts(); // Reload to update stock
                        }
                    } else {
                        alert('Error processing sale: ' + response.message + (response.error ? ('\nDetails: ' + response.error) : ''));
                        console.error('Process sale error object:', response);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error:', status, error, 'Raw:', xhr.responseText);
                    alert('Error processing sale. Server did not return valid JSON.');
                }
            });
        }

        // Print receipt function
        function printReceipt(saleId) {
            const receiptUrl = `api/print-receipt.php?sale_id=${saleId}`;
            
            // Open receipt in new window for printing
            const receiptWindow = window.open('', '_blank', 'width=400,height=600,scrollbars=yes,resizable=yes');
            
            // Show loading message
            receiptWindow.document.write(`
                <html>
                    <head><title>Loading Receipt...</title></head>
                    <body style="font-family: Arial; text-align: center; padding: 50px;">
                        <h3>Generating Receipt...</h3>
                        <p>Please wait while we prepare your thermal receipt.</p>
                    </body>
                </html>
            `);
            
            // Fetch receipt HTML
            $.ajax({
                url: receiptUrl,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Write receipt HTML to new window
                        receiptWindow.document.open();
                        receiptWindow.document.write(response.data.html);
                        receiptWindow.document.close();
                        
                        // Focus the window for printing
                        receiptWindow.focus();
                    } else {
                        receiptWindow.document.body.innerHTML = `
                            <div style="font-family: Arial; text-align: center; padding: 50px; color: red;">
                                <h3>Receipt Error</h3>
                                <p>${response.message}</p>
                                <button onclick="window.close()" style="padding: 10px 20px; margin-top: 20px;">Close</button>
                            </div>
                        `;
                    }
                },
                error: function(xhr, status, error) {
                    receiptWindow.document.body.innerHTML = `
                        <div style="font-family: Arial; text-align: center; padding: 50px; color: red;">
                            <h3>Connection Error</h3>
                            <p>Unable to generate receipt. Please try again.</p>
                            <button onclick="window.close()" style="padding: 10px 20px; margin-top: 20px;">Close</button>
                        </div>
                    `;
                }
            });
        }

        // Open payment modal
        function openPaymentModal() {
            if (!selectedCustomer) {
                alert('Please select a customer first!');
                return;
            }
            
            // Reset and populate form
            $('#payment-form')[0].reset();
            $('#payment-customer-name').val(selectedCustomer.CustomerName);
            
            // Set current date as default
            const today = new Date().toISOString().split('T')[0];
            $('#payment-date').val(today);
            
            // Show modal
            $('#payment-modal').show();
        }

        // Close payment modal
        function closePaymentModal() {
            $('#payment-modal').hide();
        }

        // Open history page
        function openHistoryPage() {
            if (!selectedCustomer) {
                alert('Please select a customer first!');
                return;
            }
            const url = `transaction-history.php?customer_id=${selectedCustomer.ID}`;
            window.location.href = url;
        }

        // Process payment
        function processPayment() {
            const paymentData = {
                customer_id: selectedCustomer.ID,
                transaction_type: $('#payment-transaction-type').val(),
                amount: parseFloat($('#payment-amount').val()),
                payment_method: $('#payment-method-select').val(),
                reference_number: $('#payment-reference').val().trim(),
                description: $('#payment-description').val().trim(),
                payment_date: $('#payment-date').val()
            };

            // Validate required fields
            if (!paymentData.amount || paymentData.amount <= 0) {
                alert('Please enter a valid payment amount');
                return;
            }

            if (!paymentData.payment_date) {
                alert('Please select a payment date');
                return;
            }

            // Show processing message
            $('button[form="payment-form"]').prop('disabled', true).text('Processing...');

            // Send payment data to API
            $.ajax({
                url: 'api/record-payment.php',
                method: 'POST',
                data: JSON.stringify(paymentData),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        alert('Payment recorded successfully!');
                        closePaymentModal();
                        
                        // Refresh customer outstanding balance
                        if (selectedCustomer) {
                            selectCustomer(
                                selectedCustomer.ID,
                                selectedCustomer.CustomerName,
                                selectedCustomer.Mobile,
                                selectedCustomer.Area,
                                selectedCustomer.CustomerType,
                                selectedCustomer.Outstanding - paymentData.amount
                            );
                        }
                    } else {
                        alert('Error recording payment: ' + (response.message || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Payment processing error:', error);
                    console.log('Response text:', xhr.responseText);
                    
                    // Try to parse error response
                    let errorMessage = 'Error recording payment. Please try again.';
                    try {
                        const errorResponse = JSON.parse(xhr.responseText);
                        if (errorResponse.message) {
                            errorMessage = errorResponse.message;
                        }
                    } catch (e) {
                        errorMessage = 'Server error. Response: ' + xhr.responseText.substring(0, 100);
                    }
                    
                    alert(errorMessage);
                },
                complete: function() {
                    $('button[form="payment-form"]').prop('disabled', false).text('Record Payment');
                }
            });
        }

        // Open reminder modal
        function openReminderModal() {
            if (!selectedCustomer) {
                alert('Please select a customer first!');
                return;
            }
            
            // Reset form
            $('#reminder-form')[0].reset();
            
            // Set default datetime to current time + 1 hour
            const now = new Date();
            now.setHours(now.getHours() + 1);
            const dateTimeString = now.toISOString().slice(0, 16);
            $('#reminder-datetime').val(dateTimeString);
            
            // Load existing reminders
            loadCustomerReminders();
            
            $('#reminder-modal').show();
        }

        // Close reminder modal
        function closeReminderModal() {
            $('#reminder-modal').hide();
        }

        // Add new reminder
        function addReminder() {
            const reminderData = {
                customer_id: selectedCustomer.ID,
                reminder_date: $('#reminder-datetime').val(),
                reminder_text: $('#reminder-text').val().trim()
            };

            if (!reminderData.reminder_date || !reminderData.reminder_text) {
                alert('Please fill in all fields');
                return;
            }

            console.log('Sending reminder data:', reminderData);

            $.ajax({
                url: 'api/customer-reminders.php',
                method: 'POST',
                data: JSON.stringify(reminderData),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    console.log('Response received:', response);
                    
                    if (response && response.success) {
                        alert('Reminder added successfully!');
                        $('#reminder-form')[0].reset();
                        
                        // Set default datetime again
                        const now = new Date();
                        now.setHours(now.getHours() + 1);
                        const dateTimeString = now.toISOString().slice(0, 16);
                        $('#reminder-datetime').val(dateTimeString);
                        
                        // Reload reminders list
                        loadCustomerReminders();
                    } else {
                        alert('Error adding reminder: ' + (response ? response.message : 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', {
                        status: status,
                        error: error,
                        responseText: xhr.responseText,
                        statusCode: xhr.status
                    });
                    
                    let errorMessage = 'Error adding reminder';
                    if (xhr.responseText) {
                        try {
                            const errorResponse = JSON.parse(xhr.responseText);
                            errorMessage += ': ' + errorResponse.message;
                        } catch (e) {
                            errorMessage += ': ' + xhr.responseText;
                        }
                    }
                    alert(errorMessage);
                }
            });
        }

        // Load customer reminders
        function loadCustomerReminders() {
            if (!selectedCustomer) return;

            $.ajax({
                url: 'api/customer-reminders.php',
                method: 'GET',
                data: { customer_id: selectedCustomer.ID },
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data && response.data.length > 0) {
                        // Show only the latest reminder
                        renderReminders([response.data[0]]);
                    } else {
                        $('#reminders-list').html('<div style="text-align: center; color: #565959; padding: 20px;">No reminders found</div>');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading reminders:', error);
                    $('#reminders-list').html('<div style="text-align: center; color: #B12704; padding: 20px;">Error loading reminder</div>');
                }
            });
        }

        // Render reminders list
        function renderReminders(reminders) {
            const container = $('#reminders-list');
            container.empty();

            if (reminders.length === 0) {
                container.html('<div style="text-align: center; color: #565959; padding: 20px;">No reminders found</div>');
                return;
            }

            const now = new Date();

            reminders.forEach(reminder => {
                const reminderDate = new Date(reminder.ReminderDate);
                const isOverdue = reminderDate < now && !reminder.IsCompleted;
                const isCompleted = reminder.IsCompleted == 1;

                let statusClass = 'pending';
                let statusText = 'Pending';
                
                if (isCompleted) {
                    statusClass = 'completed';
                    statusText = 'Completed';
                } else if (isOverdue) {
                    statusClass = 'overdue';
                    statusText = 'Overdue';
                }

                const reminderHtml = `
                    <div class="reminder-item ${isCompleted ? 'completed' : ''} ${isOverdue ? 'overdue' : ''}">
                        <div class="reminder-date">
                            <i class="fas fa-calendar mr-1"></i>
                            ${reminderDate.toLocaleDateString()} at ${reminderDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
                        </div>
                        <div class="reminder-text">${reminder.ReminderText}</div>
                        <div class="reminder-actions">
                            <span class="reminder-status ${statusClass}">${statusText}</span>
                            ${!isCompleted ? `<button class="mark-complete-btn" onclick="markReminderComplete(${reminder.ID})">Mark Complete</button>` : ''}
                        </div>
                    </div>
                `;
                container.append(reminderHtml);
            });
        }

        // Mark reminder as complete
        function markReminderComplete(reminderID) {
            $.ajax({
                url: 'api/customer-reminders.php',
                method: 'PUT',
                data: JSON.stringify({
                    reminder_id: reminderID,
                    is_completed: 1
                }),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Reload reminders list
                        loadCustomerReminders();
                    } else {
                        alert('Error updating reminder: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error updating reminder:', error);
                    alert('Error updating reminder');
                }
            });
        }

        // Save pending order
        function savePendingOrder() {
            if (cart.length === 0) {
                alert('Cart is empty!');
                return;
            }
            if (!selectedCustomer) {
                alert('Please select a customer!');
                return;
            }
            
            const notes = prompt('Add notes for this order (optional):');
            if (notes === null) return; // User canceled
            
            const orderData = {
                customer_id: selectedCustomer.ID,
                notes: notes,
                cart_items: cart.map(item => ({
                    product_id: item.product.ID,
                    quantity: item.quantity,
                    rate: selectedCustomer.CustomerType === 'Shop' ? item.product.ShopRate : item.product.RetailRate,
                    bag_kg: item.product.BagKg
                }))
            };
            
            $.ajax({
                url: 'api/pending-orders.php',
                method: 'POST',
                data: JSON.stringify(orderData),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        alert(`Order saved successfully!\nOrder Number: ${response.data.order_number}\nTotal Amount: ₹${response.data.total_amount}`);
                        
                        // Clear cart and reset interface
                        cart = [];
                        selectedCustomer = null;
                        $('#customer-search').val('');
                        $('#selected-customer').hide();
                        renderCart();
                        updateCartSummary();
                        renderProducts(products);
                    } else {
                        alert('Error saving order: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error saving order:', error);
                    alert('Error saving order. Please try again.');
                }
            });
        }

        // Mark order as delivered
        function markOrderDelivered(orderId) {
            $.ajax({
                url: 'api/pending-orders.php',
                method: 'PUT',
                data: JSON.stringify({
                    order_id: orderId,
                    order_status: 'Delivered'
                }),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    console.log('Order marked as delivered:', response);
                },
                error: function(xhr, status, error) {
                    console.error('Error marking order as delivered:', error);
                }
            });
        }
    </script>
</body>
</html>
