<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * POS Terminal - COMPLETE FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Load the universal initializer (go up two levels from /pos/sales/ to root)
require_once dirname(dirname(__DIR__)) . '/config/init.php';

// Require authentication
require_auth();

// Set page title
$page_title = 'POS Terminal';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Check for open shift - this is critical
$active_shift = null;
$show_shift_warning = true;
$current_shift_id = null;

try {
    $active_shift = db_fetch_one("
        SELECT * FROM pos_shifts 
        WHERE user_id = ? AND status = 'open'
        ORDER BY opened_at DESC LIMIT 1
    ", [$user_id]);
    
    if ($active_shift) {
        $show_shift_warning = false;
        $current_shift_id = $active_shift['shift_id'];
    } else {
        $show_shift_warning = true;
    }
} catch (Exception $e) {
    error_log("Error checking shift: " . $e->getMessage());
}

// Get outlets for dropdown
$outlets = [];
try {
    $outlets = db_fetch_all("SELECT * FROM pos_outlets WHERE is_active = 1 ORDER BY outlet_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching outlets: " . $e->getMessage());
}

// Get categories for product grid - specifically identify SOFT DRINKS and Alcoholic Drinks
$categories = [];
$stock_tracked_categories = []; // Store IDs of categories that should track stock
try {
    $categories = db_fetch_all("
        SELECT c.*, 
               (SELECT COUNT(*) FROM pos_products WHERE category_id = c.category_id AND is_active = 1) as product_count
        FROM pos_categories c
        WHERE c.is_active = 1
        ORDER BY c.sort_order, c.category_name
    ") ?: [];
    
    // Identify which categories should track stock (SOFT DRINKS and Alcoholic Drinks)
    foreach ($categories as $cat) {
        $cat_name = strtolower($cat['category_name'] ?? '');
        if (strpos($cat_name, 'soft drink') !== false || 
            strpos($cat_name, 'soft drinks') !== false ||
            strpos($cat_name, 'soda') !== false ||
            strpos($cat_name, 'alcoholic') !== false || 
            strpos($cat_name, 'alcohol') !== false ||
            strpos($cat_name, 'beer') !== false ||
            strpos($cat_name, 'wine') !== false ||
            strpos($cat_name, 'spirit') !== false) {
            $stock_tracked_categories[] = $cat['category_id'];
        }
    }
} catch (Exception $e) {
    error_log("Error fetching categories: " . $e->getMessage());
}

// Get initial products with stock information
$initial_products = [];
try {
    // First, get all active products
    $initial_products = db_fetch_all("
        SELECT p.*, c.category_name, c.category_id
        FROM pos_products p
        LEFT JOIN pos_categories c ON p.category_id = c.category_id
        WHERE p.is_active = 1
        ORDER BY c.sort_order, p.product_name
        LIMIT 50
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching products: " . $e->getMessage());
}

// Get active reservations for room charge
$active_reservations = [];
try {
    $active_reservations = db_fetch_all("
        SELECT r.reservation_id, r.booking_code, 
               g.first_name, g.last_name,
               rm.room_number
        FROM reservations r
        JOIN guests g ON r.guest_id = g.guest_id
        LEFT JOIN rooms rm ON r.room_id = rm.room_id
        WHERE r.booking_status = 'checked_in'
        ORDER BY rm.room_number
    ") ?: [];
} catch (Exception $e) {
    error_log("Error fetching reservations: " . $e->getMessage());
}

// Get recent sales for adding items
$recent_sales = [];
try {
    $recent_sales = db_fetch_all("
        SELECT sale_id, receipt_number, customer_name, total_amount, sale_time
        FROM pos_sales
        WHERE created_by = ? AND DATE(sale_time) = CURDATE()
        ORDER BY sale_time DESC
        LIMIT 20
    ", [$user_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching recent sales: " . $e->getMessage());
}

// Handle AJAX requests directly in this file
if (isset($_GET['ajax']) || isset($_POST['ajax'])) {
    handle_ajax_requests($user_id, $current_shift_id, $stock_tracked_categories);
    exit;
}

// Include header
$header_path = BASE_PATH . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>POS Terminal</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .kitchen-print-btn { background-color: #ffc107; color: #000; }
            .kitchen-print-btn:hover { background-color: #e0a800; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">POS Terminal</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> <?php echo htmlspecialchars($current_user['username'] ?? 'User'); ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">POS Terminal</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/pos/dashboard.php">POS</a></li>
                    <li class="breadcrumb-item active">Terminal</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Shift Warning -->
        <?php if ($show_shift_warning): ?>
        <div class="alert alert-warning alert-dismissible fade show">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <strong>No Open Shift!</strong> You need to open a shift before you can process sales.
            <a href="/HMSPOS/pos/shifts/open.php" class="btn btn-sm btn-warning ms-2">Open Shift</a>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <!-- Quick Actions -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <button type="button" class="btn btn-info me-2" onclick="searchGuest()">
                            <i class="fas fa-user"></i> Find Guest
                        </button>
                        <button type="button" class="btn btn-warning me-2" onclick="showAddToExistingModal()">
                            <i class="fas fa-plus-circle"></i> Add to Existing Receipt
                        </button>
                        <a href="orders.php" class="btn btn-secondary me-2">
                            <i class="fas fa-clipboard-list"></i> View Kitchen Orders
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Product Grid -->
            <div class="col-md-8">
                <!-- Outlet Selector -->
                <div class="card card-outline card-primary">
                    <div class="card-body py-2">
                        <div class="row g-3 align-items-center">
                            <div class="col-auto">
                                <label for="outlet_id" class="col-form-label">Outlet:</label>
                            </div>
                            <div class="col-auto">
                                <select class="form-select" id="outlet_id" required>
                                    <option value="">Select Outlet</option>
                                    <?php foreach ($outlets as $outlet): ?>
                                        <option value="<?php echo $outlet['outlet_id'] ?? 0; ?>">
                                            <?php echo htmlspecialchars($outlet['outlet_name'] ?? 'Unknown'); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-auto">
                                <label for="customer" class="col-form-label">Customer:</label>
                            </div>
                            <div class="col-auto">
                                <input type="text" class="form-control" id="customer" 
                                       placeholder="Walk-in Customer" value="Walk-in Customer" style="min-width: 200px;">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Category Tabs -->
                <div class="card">
                    <div class="card-header p-0">
                        <ul class="nav nav-pills" id="categoryTabs">
                            <li class="nav-item">
                                <a class="nav-link active" href="#" data-category="all" onclick="loadProducts('all'); return false;">All Products</a>
                            </li>
                            <?php foreach ($categories as $category): ?>
                                <?php if (($category['product_count'] ?? 0) > 0): ?>
                                <li class="nav-item">
                                    <a class="nav-link" href="#" data-category="<?php echo $category['category_id'] ?? 0; ?>" 
                                       onclick="loadProducts(<?php echo $category['category_id'] ?? 0; ?>); return false;">
                                        <?php echo htmlspecialchars($category['category_name'] ?? 'Category'); ?>
                                    </a>
                                </li>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    
                    <div class="card-body">
                        <!-- Search Bar -->
                        <div class="input-group mb-3">
                            <input type="text" class="form-control" id="productSearch" placeholder="Search products..." onkeyup="searchProducts()">
                            <button class="btn btn-primary" type="button" onclick="searchProducts()"><i class="fas fa-search"></i></button>
                        </div>
                        
                        <!-- Product Grid -->
                        <div class="pos-product-grid" id="productGrid">
                            <?php if (empty($initial_products)): ?>
                                <div class="text-center text-muted py-5">No products found</div>
                            <?php else: 
                                foreach ($initial_products as $product): 
                                    // Determine if this product should track stock
                                    $track_stock = in_array($product['category_id'], $stock_tracked_categories);
                                    
                                    // Calculate stock status only for tracked categories
                                    $is_out_of_stock = false;
                                    $is_low_stock = false;
                                    $stock_class = '';
                                    
                                    if ($track_stock) {
                                        $is_out_of_stock = ($product['current_stock'] ?? 0) <= 0;
                                        $is_low_stock = ($product['current_stock'] ?? 0) <= ($product['min_stock'] ?? 5) && ($product['current_stock'] ?? 0) > 0;
                                        $stock_class = $is_out_of_stock ? 'out-of-stock' : ($is_low_stock ? 'low-stock' : '');
                                    }
                                ?>
                                    <div class="pos-product-item <?php echo $stock_class; ?>" 
                                         data-id="<?php echo $product['product_id'] ?? 0; ?>"
                                         data-name="<?php echo htmlspecialchars($product['product_name'] ?? 'Product'); ?>"
                                         data-price="<?php echo $product['unit_price'] ?? 0; ?>"
                                         data-stock="<?php echo $product['current_stock'] ?? 0; ?>"
                                         data-category-id="<?php echo $product['category_id'] ?? 0; ?>"
                                         data-track-stock="<?php echo $track_stock ? '1' : '0'; ?>"
                                         onclick="<?php echo ($track_stock && $is_out_of_stock) ? '' : 'addToCart(this)'; ?>">
                                        
                                        <?php if ($track_stock): ?>
                                            <?php if ($is_out_of_stock): ?>
                                                <span class="stock-badge badge bg-danger">Out of Stock</span>
                                            <?php elseif ($is_low_stock): ?>
                                                <span class="stock-badge badge bg-warning">Low Stock</span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        
                                        <div class="product-name"><?php echo htmlspecialchars($product['product_name'] ?? 'Product'); ?></div>
                                        <div class="price"><?php echo function_exists('format_currency') ? format_currency($product['unit_price'] ?? 0) : 'RWF ' . number_format($product['unit_price'] ?? 0, 2); ?></div>
                                        
                                        <?php if (!empty($product['product_code'])): ?>
                                            <div class="product-code small text-muted"><?php echo htmlspecialchars($product['product_code']); ?></div>
                                        <?php endif; ?>
                                        
                                        <?php if ($track_stock && !$is_out_of_stock): ?>
                                            <div class="stock-info small text-muted">Stock: <?php echo $product['current_stock'] ?? 0; ?></div>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                        
                        <div id="productLoading" style="display: none; text-align: center; padding: 50px;">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Shopping Cart -->
            <div class="col-md-4">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">Current Sale</h3>
                        <button type="button" class="btn btn-tool" onclick="clearCart()"><i class="fas fa-trash"></i></button>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="pos-cart" id="cartContainer">
                            <div class="pos-cart-items" id="cartItems">
                                <div class="text-center text-muted py-5">
                                    <i class="fas fa-shopping-cart fa-3x mb-3"></i>
                                    <p>Cart is empty</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="pos-cart-totals">
                            <table class="table table-sm">
                                <tr><th>Subtotal:</th><td class="text-end" id="subtotal">RWF 0.00</td></tr>
                                <tr><th>Tax (18%):</th><td class="text-end" id="tax">RWF 0.00</td></tr>
                                <tr class="table-active"><th>Total:</th><td class="text-end" id="total"><strong>RWF 0.00</strong></td></tr>
                            </table>
                            
                            <div class="input-group mb-2">
                                <span class="input-group-text">Discount</span>
                                <input type="number" class="form-control" id="discount" value="0" min="0" step="0.01" onchange="updateDiscount()">
                                <select class="form-select" id="discount_type" style="max-width: 80px;" onchange="updateDiscount()">
                                    <option value="fixed">RWF</option>
                                    <option value="percentage">%</option>
                                </select>
                            </div>
                            
                            <div class="row g-2">
                                <div class="col-6">
                                    <button class="btn btn-success w-100" onclick="checkout('cash')" 
                                            id="checkoutBtnCash"
                                            <?php echo $show_shift_warning ? 'disabled' : ''; ?>>
                                        <i class="fas fa-money-bill"></i> Make Order
                                    </button>
                                </div>
                                <!--<div class="col-6">
                                    <button class="btn btn-primary w-100" onclick="checkout('card')" 
                                            id="checkoutBtnCard"
                                            <?php echo $show_shift_warning ? 'disabled' : ''; ?>>
                                        <i class="fas fa-credit-card"></i> Card
                                    </button>
                                </div>
                                <div class="col-6">
                                    <button class="btn btn-info w-100" onclick="checkout('mobile')" 
                                            id="checkoutBtnMobile"
                                            <?php echo $show_shift_warning ? 'disabled' : ''; ?>>
                                        <i class="fas fa-mobile-alt"></i> Mobile
                                    </button>
                                </div>-->
                                <div class="col-6">
                                    <button class="btn btn-warning w-100" onclick="showRoomChargeModal()" 
                                            id="roomChargeBtn"
                                            <?php echo $show_shift_warning ? 'disabled' : ''; ?>>
                                        <i class="fas fa-bed"></i> Room
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Guest Search Modal -->
<div class="modal fade" id="guestSearchModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Search Guest</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3">
                    <input type="text" class="form-control" id="guestSearch" placeholder="Type name, email, phone, or guest code...">
                    <button class="btn btn-primary" type="button" onclick="searchGuests()"><i class="fas fa-search"></i></button>
                </div>
                <div id="guestResults" style="max-height: 400px; overflow-y: auto;"></div>
                <div id="guestLoading" style="display: none; text-align: center; padding: 20px;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Room Charge Modal -->
<div class="modal fade" id="roomChargeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">Room Charge</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <select class="form-select" id="reservation_id">
                    <option value="">Select a reservation</option>
                    <?php foreach ($active_reservations as $res): ?>
                        <option value="<?php echo $res['reservation_id'] ?? 0; ?>">
                            Room <?php echo htmlspecialchars($res['room_number'] ?? 'N/A'); ?> - 
                            <?php echo htmlspecialchars(($res['first_name'] ?? '') . ' ' . ($res['last_name'] ?? '')); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" onclick="processRoomCharge()">Charge to Room</button>
            </div>
        </div>
    </div>
</div>

<!-- Add to Existing Receipt Modal -->
<div class="modal fade" id="addToExistingModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Add to Existing Receipt</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Recent Sales Today</h6>
                        <div class="list-group" id="recentSalesList" style="max-height: 300px; overflow-y: auto;">
                            <?php foreach ($recent_sales as $sale): ?>
                                <a href="#" class="list-group-item list-group-item-action" onclick="selectSale(<?php echo $sale['sale_id']; ?>, '<?php echo htmlspecialchars($sale['receipt_number']); ?>', '<?php echo htmlspecialchars($sale['customer_name']); ?>'); return false;">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <strong><?php echo htmlspecialchars($sale['receipt_number']); ?></strong><br>
                                            <small><?php echo htmlspecialchars($sale['customer_name']); ?></small>
                                        </div>
                                        <div class="text-end">
                                            <span class="badge bg-success"><?php echo function_exists('format_currency') ? format_currency($sale['total_amount']) : 'RWF ' . number_format($sale['total_amount'], 2); ?></span><br>
                                            <small><?php echo date('H:i', strtotime($sale['sale_time'])); ?></small>
                                        </div>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6>Selected Sale</h6>
                        <div id="selectedSaleInfo" class="border p-3 rounded">
                            <p class="text-muted">No sale selected</p>
                        </div>
                        <input type="hidden" id="selectedSaleId" value="">
                    </div>
                </div>
                
                <hr>
                
                <h6>Items to Add</h6>
                <div id="addItemsCart" class="border p-3 rounded" style="min-height: 100px;">
                    <p class="text-muted">No items selected</p>
                </div>
                
                <button type="button" class="btn btn-sm btn-primary mt-2" onclick="showProductSelector()">
                    <i class="fas fa-plus"></i> Add Product
                </button>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="processAddToExisting()">Add Items to Receipt</button>
            </div>
        </div>
    </div>
</div>

<!-- Product Selector Modal (for adding to existing) -->
<div class="modal fade" id="productSelectorModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Select Products to Add</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="input-group mb-3">
                    <input type="text" class="form-control" id="modalProductSearch" placeholder="Search products...">
                    <button class="btn btn-primary" type="button" onclick="searchModalProducts()"><i class="fas fa-search"></i></button>
                </div>
                <div id="modalProductGrid" class="pos-product-grid" style="max-height: 300px; overflow-y: auto;">
                    <!-- Products will be loaded here -->
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let cart = [];
let addItemsCart = [];
let currentCustomer = 'Walk-in Customer';
let currentGuestId = null;
let selectedSaleId = null;
let selectedSaleInfo = {};

// Load products by category
function loadProducts(categoryId) {
    $('#productGrid').hide();
    $('#productLoading').show();
    
    $.ajax({
        url: window.location.href,
        method: 'GET',
        data: { ajax: 'get_products', category: categoryId },
        dataType: 'html',
        timeout: 10000,
        success: function(response) {
            $('#productLoading').hide();
            $('#productGrid').html(response).fadeIn();
        },
        error: function(xhr, status, error) {
            $('#productLoading').hide();
            $('#productGrid').show();
            console.error('AJAX Error:', status, error);
            $('#productGrid').html('<div class="text-center text-muted py-5">Failed to load products. Error: ' + error + '</div>');
        }
    });
}

// Search products
function searchProducts() {
    const query = $('#productSearch').val();
    if (query.length < 2) {
        loadProducts('all');
        return;
    }
    
    $('#productGrid').hide();
    $('#productLoading').show();
    
    $.ajax({
        url: window.location.href,
        method: 'GET',
        data: { ajax: 'search_products', query: query },
        dataType: 'html',
        timeout: 10000,
        success: function(response) {
            $('#productLoading').hide();
            $('#productGrid').html(response).fadeIn();
        },
        error: function(xhr, status, error) {
            $('#productLoading').hide();
            $('#productGrid').show();
            console.error('Search AJAX Error:', status, error);
            $('#productGrid').html('<div class="text-center text-muted py-5">Search failed. Please try again.</div>');
        }
    });
}

// Search products in modal
function searchModalProducts() {
    const query = $('#modalProductSearch').val();
    if (query.length < 2) {
        loadModalProducts();
        return;
    }
    
    $('#modalProductGrid').html('<div class="text-center py-3"><div class="spinner-border text-primary"></div></div>');
    
    $.ajax({
        url: window.location.href,
        method: 'GET',
        data: { ajax: 'search_products', query: query },
        dataType: 'html',
        timeout: 10000,
        success: function(response) {
            $('#modalProductGrid').html(response);
        },
        error: function() {
            $('#modalProductGrid').html('<div class="text-center text-muted py-3">Search failed</div>');
        }
    });
}

// Load all products in modal
function loadModalProducts() {
    $('#modalProductGrid').html('<div class="text-center py-3"><div class="spinner-border text-primary"></div></div>');
    
    $.ajax({
        url: window.location.href,
        method: 'GET',
        data: { ajax: 'get_products', category: 'all' },
        dataType: 'html',
        timeout: 10000,
        success: function(response) {
            $('#modalProductGrid').html(response);
        },
        error: function() {
            $('#modalProductGrid').html('<div class="text-center text-muted py-3">Failed to load products</div>');
        }
    });
}

// Add to cart using data attributes
function addToCart(element) {
    const productId = $(element).data('id');
    const productName = $(element).data('name');
    const price = $(element).data('price');
    const trackStock = $(element).data('track-stock');
    const currentStock = $(element).data('stock');
    
    // Check stock for tracked items
    if (trackStock == 1 && currentStock <= 0) {
        alert('This item is out of stock');
        return;
    }
    
    const existingItem = cart.find(item => item.id === productId);
    
    if (existingItem) {
        // Check if adding another would exceed stock for tracked items
        if (trackStock == 1 && existingItem.quantity + 1 > currentStock) {
            alert('Not enough stock available');
            return;
        }
        existingItem.quantity++;
    } else {
        cart.push({ 
            id: productId, 
            name: productName, 
            price: parseFloat(price), 
            quantity: 1,
            trackStock: trackStock,
            categoryId: $(element).data('category-id')
        });
    }
    
    updateCartDisplay();
    
    // Visual feedback
    $(element).css('background-color', '#d4edda');
    setTimeout(() => $(element).css('background-color', ''), 200);
}

// Add to existing cart (for adding to existing receipt)
function addToExistingCart(element) {
    const productId = $(element).data('id');
    const productName = $(element).data('name');
    const price = $(element).data('price');
    const trackStock = $(element).data('track-stock');
    const currentStock = $(element).data('stock');
    
    // Check if a sale is selected
    if (!$('#selectedSaleId').val()) {
        alert('Please select a sale first');
        $('#recentSalesList').css('border', '2px solid red').fadeOut(100).fadeIn(100);
        setTimeout(() => $('#recentSalesList').css('border', ''), 1000);
        return;
    }
    
    // Check stock for tracked items
    if (trackStock == 1 && currentStock <= 0) {
        alert('This item is out of stock');
        return;
    }
    
    const existingItem = addItemsCart.find(item => item.id === productId);
    
    if (existingItem) {
        // Check if adding another would exceed stock for tracked items
        if (trackStock == 1 && existingItem.quantity + 1 > currentStock) {
            alert('Not enough stock available');
            return;
        }
        existingItem.quantity++;
    } else {
        addItemsCart.push({ 
            id: productId, 
            name: productName, 
            price: parseFloat(price), 
            quantity: 1,
            trackStock: trackStock,
            categoryId: $(element).data('category-id')
        });
    }
    
    updateAddItemsCartDisplay();
    
    // Visual feedback
    $(element).css('background-color', '#d4edda');
    setTimeout(() => $(element).css('background-color', ''), 200);
}

// Update add items cart display
function updateAddItemsCartDisplay() {
    if (addItemsCart.length === 0) {
        $('#addItemsCart').html('<p class="text-muted">No items selected</p>');
        return;
    }
    
    let html = '<table class="table table-sm">';
    html += '<thead><tr><th>Item</th><th class="text-center">Qty</th><th class="text-end">Price</th><th class="text-end">Total</th><th></th></tr></thead><tbody>';
    
    let subtotal = 0;
    
    addItemsCart.forEach((item, index) => {
        const itemTotal = item.price * item.quantity;
        subtotal += itemTotal;
        
        html += `
            <tr>
                <td>${item.name}</td>
                <td class="text-center">
                    <input type="number" class="form-control form-control-sm text-center" 
                           value="${item.quantity}" min="1" style="width: 70px;"
                           onchange="updateAddItemQuantity(${index}, this.value)">
                </td>
                <td class="text-end">${formatCurrency(item.price)}</td>
                <td class="text-end">${formatCurrency(itemTotal)}</td>
                <td class="text-center">
                    <button class="btn btn-sm btn-danger" onclick="removeFromAddCart(${index})">
                        <i class="fas fa-times"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    html += `<tr class="table-active">
                <td colspan="3" class="text-end"><strong>Total to Add:</strong></td>
                <td class="text-end"><strong>${formatCurrency(subtotal)}</strong></td>
                <td></td>
            </tr>`;
    html += '</tbody></table>';
    
    $('#addItemsCart').html(html);
}

// Update add item quantity
function updateAddItemQuantity(index, quantity) {
    if (quantity && quantity > 0) {
        addItemsCart[index].quantity = parseInt(quantity);
        updateAddItemsCartDisplay();
    }
}

// Remove from add cart
function removeFromAddCart(index) {
    addItemsCart.splice(index, 1);
    updateAddItemsCartDisplay();
}

// Update cart display
function updateCartDisplay() {
    if (cart.length === 0) {
        $('#cartItems').html('<div class="text-center text-muted py-5"><i class="fas fa-shopping-cart fa-3x mb-3"></i><p>Cart is empty</p></div>');
        $('#subtotal').text('RWF 0.00');
        $('#tax').text('RWF 0.00');
        $('#total').html('<strong>RWF 0.00</strong>');
        return;
    }
    
    let html = '';
    let subtotal = 0;
    
    cart.forEach((item, index) => {
        const itemTotal = item.price * item.quantity;
        subtotal += itemTotal;
        
        html += `
            <div class="pos-cart-item">
                <div>
                    <strong>${item.name}</strong><br>
                    <small>${formatCurrency(item.price)} x ${item.quantity}</small>
                </div>
                <div class="text-end">
                    <strong>${formatCurrency(itemTotal)}</strong><br>
                    <button class="btn btn-sm btn-link text-danger p-0" onclick="removeFromCart(${index})" title="Remove">
                        <i class="fas fa-times"></i>
                    </button>
                    <button class="btn btn-sm btn-link p-0 ms-1" onclick="editQuantity(${index})" title="Edit quantity">
                        <i class="fas fa-pencil-alt"></i>
                    </button>
                </div>
            </div>
        `;
    });
    
    $('#cartItems').html(html);
    updateTotals(subtotal);
}

// Update totals
function updateTotals(subtotal) {
    const discount = parseFloat($('#discount').val()) || 0;
    const discountType = $('#discount_type').val();
    let discountAmount = discountType === 'percentage' ? (subtotal * discount) / 100 : discount;
    const tax = subtotal * 0.18;
    const total = subtotal + tax - discountAmount;
    
    $('#subtotal').text(formatCurrency(subtotal));
    $('#tax').text(formatCurrency(tax));
    $('#total').html('<strong>' + formatCurrency(total) + '</strong>');
}

// Remove from cart
function removeFromCart(index) {
    cart.splice(index, 1);
    updateCartDisplay();
}

// Edit quantity
function editQuantity(index) {
    const item = cart[index];
    const newQty = prompt('Enter quantity:', item.quantity);
    
    if (newQty && !isNaN(newQty) && newQty > 0) {
        // Check stock for tracked items - we need to get current stock from server
        if (item.trackStock == 1) {
            $.ajax({
                url: window.location.href,
                method: 'GET',
                data: { ajax: 'check_stock', product_id: item.id, quantity: newQty },
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success' && response.data.available) {
                        cart[index].quantity = parseFloat(newQty);
                        updateCartDisplay();
                    } else {
                        alert('Not enough stock available. Current stock: ' + response.data.current_stock);
                    }
                },
                error: function() {
                    alert('Error checking stock. Please try again.');
                }
            });
        } else {
            cart[index].quantity = parseFloat(newQty);
            updateCartDisplay();
        }
    }
}

// Clear cart
function clearCart() {
    if (cart.length > 0 && confirm('Clear all items from cart?')) {
        cart = [];
        updateCartDisplay();
    }
}

// Update discount
function updateDiscount() {
    const subtotal = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
    updateTotals(subtotal);
}

// Format currency
function formatCurrency(amount) {
    return 'RWF ' + amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// Search guests function
function searchGuests() {
    const query = $('#guestSearch').val();
    if (query.length < 2) {
        alert('Please enter at least 2 characters');
        return;
    }
    
    $('#guestResults').hide();
    $('#guestLoading').show();
    
    $.ajax({
        url: window.location.href,
        method: 'GET',
        data: { ajax: 'search_guests', query: query },
        dataType: 'json',
        timeout: 10000,
        success: function(response) {
            $('#guestLoading').hide();
            $('#guestResults').show();
            
            if (response.status === 'success' && response.data && response.data.length > 0) {
                let html = '<div class="list-group">';
                response.data.forEach(guest => {
                    const guestName = `${guest.first_name || ''} ${guest.last_name || ''}`.trim() || 'Unknown';
                    const email = guest.email ? `<br><small>Email: ${guest.email}</small>` : '';
                    const phone = guest.phone ? `<br><small>Phone: ${guest.phone}</small>` : '';
                    const code = guest.guest_code ? `<br><small>Code: ${guest.guest_code}</small>` : '';
                    
                    html += `<a href="#" class="list-group-item list-group-item-action" 
                               onclick="selectGuest(${guest.guest_id || 0}, '${guestName.replace(/'/g, "\\'")}'); return false;">
                               <div class="d-flex justify-content-between align-items-start">
                                   <div>
                                       <strong>${guestName}</strong>
                                       ${email}
                                       ${phone}
                                       ${code}
                                   </div>
                                   <span class="badge bg-info rounded-pill">Select</span>
                               </div>
                            </a>`;
                });
                html += '</div>';
                $('#guestResults').html(html);
            } else {
                $('#guestResults').html('<div class="alert alert-info">No guests found matching your search.</div>');
            }
        },
        error: function(xhr, status, error) {
            $('#guestLoading').hide();
            $('#guestResults').show();
            console.error('Guest search error:', error);
            $('#guestResults').html('<div class="alert alert-danger">Error searching guests. Please try again.</div>');
        }
    });
}

// Checkout function
function checkout(paymentType) {
    if (cart.length === 0) {
        alert('Cart is empty');
        return;
    }
    
    const outletId = $('#outlet_id').val();
    if (!outletId) {
        alert('Please select an outlet');
        return;
    }
    
    // Determine which button was clicked
    let btnId = '';
    if (paymentType === 'cash') btnId = '#checkoutBtnCash';
    else if (paymentType === 'card') btnId = '#checkoutBtnCard';
    else if (paymentType === 'mobile') btnId = '#checkoutBtnMobile';
    
    const checkoutData = {
        outlet_id: outletId,
        customer_name: currentCustomer,
        guest_id: currentGuestId,
        items: cart.map(item => ({
            id: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            trackStock: item.trackStock,
            categoryId: item.categoryId
        })),
        subtotal: cart.reduce((sum, item) => sum + (item.price * item.quantity), 0),
        discount: parseFloat($('#discount').val()) || 0,
        discount_type: $('#discount_type').val()
    };
    
    // Show loading indicator
    const $btn = $(btnId);
    const originalText = $btn.html();
    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
    
    $.ajax({
        url: window.location.href,
        method: 'POST',
        data: { ajax: 'checkout', data: JSON.stringify(checkoutData) },
        dataType: 'json',
        timeout: 30000,
        success: function(response) {
            if (response.status === 'success') {
                // Clear cart after successful checkout
                cart = [];
                currentGuestId = null;
                currentCustomer = 'Walk-in Customer';
                $('#customer').val('Walk-in Customer');
                $('#discount').val(0);
                updateCartDisplay();
                
                // Show success message with receipt options
                showReceiptOptions(response.data.sale_id, response.data.receipt_number);
            } else {
                alert('Checkout failed: ' + (response.message || 'Unknown error'));
                $btn.prop('disabled', false).html(originalText);
            }
        },
        error: function(xhr, status, error) {
            console.error('Checkout error:', error);
            alert('Checkout failed. Please try again. Error: ' + error);
            $btn.prop('disabled', false).html(originalText);
        }
    });
}

// Show receipt options after successful checkout
function showReceiptOptions(saleId, receiptNumber) {
    // Remove existing modal if any
    $('#receiptOptionsModal').remove();
    
    const modalHtml = `
        <div class="modal fade" id="receiptOptionsModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-success text-white">
                        <h5 class="modal-title">Checkout Successful</h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <p>Receipt #: <strong>${receiptNumber}</strong></p>
                        <p>What would you like to do?</p>
                        <div class="d-grid gap-2">
                            <button class="btn btn-primary" onclick="downloadReceipt(${saleId})">
                                <i class="fas fa-download"></i> Download Receipt
                            </button>
                            <button class="btn btn-warning" onclick="printKitchenOrder(${saleId})">
                                <i class="fas fa-utensils"></i> Print Order
                            </button>
                            <button class="btn btn-info" onclick="viewReceipt(${saleId})">
                                <i class="fas fa-eye"></i> View Receipt
                            </button>
                            <button class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times"></i> Close
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Add new modal to body
    $('body').append(modalHtml);
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('receiptOptionsModal'));
    modal.show();
}

// Download receipt
function downloadReceipt(saleId) {
    window.open('receipt-pdf.php?id=' + saleId + '&download=1', '_blank');
    bootstrap.Modal.getInstance(document.getElementById('receiptOptionsModal')).hide();
}

// Print kitchen order
function printKitchenOrder(saleId) {
    window.open('kitchen-order.php?id=' + saleId, '_blank');
    bootstrap.Modal.getInstance(document.getElementById('receiptOptionsModal')).hide();
}

// View receipt
function viewReceipt(saleId) {
    window.open('receipt-pdf.php?id=' + saleId, '_blank');
    bootstrap.Modal.getInstance(document.getElementById('receiptOptionsModal')).hide();
}

// Show add to existing receipt modal
function showAddToExistingModal() {
    addItemsCart = [];
    updateAddItemsCartDisplay();
    $('#selectedSaleId').val('');
    $('#selectedSaleInfo').html('<p class="text-muted">No sale selected</p>');
    $('#recentSalesList a').removeClass('active');
    
    const modal = new bootstrap.Modal(document.getElementById('addToExistingModal'));
    modal.show();
}

// Show product selector in add to existing modal
function showProductSelector() {
    if (!$('#selectedSaleId').val()) {
        alert('Please select a sale first');
        $('#recentSalesList').css('border', '2px solid red').fadeOut(100).fadeIn(100);
        setTimeout(() => $('#recentSalesList').css('border', ''), 1000);
        return;
    }
    loadModalProducts();
    new bootstrap.Modal(document.getElementById('productSelectorModal')).show();
}

// Select a sale for adding items
function selectSale(saleId, receiptNumber, customerName) {
    selectedSaleId = saleId;
    $('#selectedSaleId').val(saleId);
    $('#selectedSaleInfo').html(`
        <p><strong>Receipt:</strong> ${receiptNumber}</p>
        <p><strong>Customer:</strong> ${customerName}</p>
        <p><small class="text-success">Sale selected - you can now add products</small></p>
    `);
    
    // Highlight selected sale
    $('#recentSalesList a').removeClass('active');
    event.currentTarget.classList.add('active');
}

// Process adding items to existing receipt
function processAddToExisting() {
    const saleId = $('#selectedSaleId').val();
    if (!saleId) {
        alert('Please select a sale');
        return;
    }
    
    if (addItemsCart.length === 0) {
        alert('No items to add');
        return;
    }
    
    const outletId = $('#outlet_id').val();
    if (!outletId) {
        alert('Please select an outlet');
        return;
    }
    
    const addData = {
        sale_id: saleId,
        outlet_id: outletId,
        items: addItemsCart.map(item => ({
            id: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            trackStock: item.trackStock,
            categoryId: item.categoryId
        }))
    };
    
    $('#addToExistingModal .btn-success').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Adding...');
    
    $.ajax({
        url: window.location.href,
        method: 'POST',
        data: { ajax: 'add_to_existing', data: JSON.stringify(addData) },
        dataType: 'json',
        timeout: 30000,
        success: function(response) {
            if (response.status === 'success') {
                alert('Items added successfully!');
                $('#addToExistingModal').modal('hide');
                $('#productSelectorModal').modal('hide');
                
                // Show receipt options for updated sale
                showReceiptOptions(saleId, response.data.receipt_number);
            } else {
                alert('Failed to add items: ' + (response.message || 'Unknown error'));
            }
            $('#addToExistingModal .btn-success').prop('disabled', false).html('Add Items to Receipt');
        },
        error: function(xhr, status, error) {
            console.error('Add to existing error:', error);
            alert('Failed to add items. Please try again.');
            $('#addToExistingModal .btn-success').prop('disabled', false).html('Add Items to Receipt');
        }
    });
}

// Show room charge modal
function showRoomChargeModal() {
    if (cart.length === 0) {
        alert('Cart is empty');
        return;
    }
    new bootstrap.Modal(document.getElementById('roomChargeModal')).show();
}

// Process room charge
function processRoomCharge() {
    const reservationId = $('#reservation_id').val();
    if (!reservationId) {
        alert('Please select a reservation');
        return;
    }
    
    const outletId = $('#outlet_id').val();
    if (!outletId) {
        alert('Please select an outlet');
        return;
    }
    
    const checkoutData = {
        outlet_id: outletId,
        reservation_id: reservationId,
        items: cart.map(item => ({
            id: item.id,
            name: item.name,
            price: item.price,
            quantity: item.quantity,
            trackStock: item.trackStock,
            categoryId: item.categoryId
        })),
        subtotal: cart.reduce((sum, item) => sum + (item.price * item.quantity), 0),
        discount: parseFloat($('#discount').val()) || 0,
        discount_type: $('#discount_type').val()
    };
    
    $('#roomChargeBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Processing...');
    
    $.ajax({
        url: window.location.href,
        method: 'POST',
        data: { ajax: 'room_charge', data: JSON.stringify(checkoutData) },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                // Clear cart after successful room charge
                cart = [];
                currentGuestId = null;
                currentCustomer = 'Walk-in Customer';
                $('#customer').val('Walk-in Customer');
                $('#discount').val(0);
                updateCartDisplay();
                
                $('#roomChargeModal').modal('hide');
                
                // Show receipt options
                showReceiptOptions(response.data.sale_id, response.data.receipt_number);
            } else {
                alert('Room charge failed: ' + (response.message || 'Unknown error'));
                $('#roomChargeBtn').prop('disabled', false).html('<i class="fas fa-bed"></i> Room');
            }
        },
        error: function(xhr, status, error) {
            console.error('Room charge error:', error);
            alert('Room charge failed. Please try again.');
            $('#roomChargeBtn').prop('disabled', false).html('<i class="fas fa-bed"></i> Room');
        }
    });
}

// Search guest (opens modal)
function searchGuest() {
    $('#guestSearch').val('');
    $('#guestResults').empty();
    new bootstrap.Modal(document.getElementById('guestSearchModal')).show();
}

// Handle Enter key in guest search
$(document).on('keypress', '#guestSearch', function(e) {
    if (e.which === 13) {
        searchGuests();
        e.preventDefault();
    }
});

// Handle Enter key in modal product search
$(document).on('keypress', '#modalProductSearch', function(e) {
    if (e.which === 13) {
        searchModalProducts();
        e.preventDefault();
    }
});

// Select guest
function selectGuest(guestId, guestName) {
    currentGuestId = guestId;
    currentCustomer = guestName;
    $('#customer').val(guestName);
    bootstrap.Modal.getInstance(document.getElementById('guestSearchModal')).hide();
}

// Initialize on document ready
$(document).ready(function() {
    // Set default outlet if available
    const firstOutlet = $('#outlet_id option:first').val();
    if (firstOutlet) $('#outlet_id').val(firstOutlet);
    
    // Handle Enter key in product search
    $('#productSearch').on('keypress', function(e) {
        if (e.which === 13) {
            searchProducts();
            e.preventDefault();
        }
    });
    
    // Prevent default for all anchor clicks
    $(document).on('click', 'a[href="#"]', function(e) {
        e.preventDefault();
    });
});
</script>

<style>
.pos-product-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 10px;
    max-height: 500px;
    overflow-y: auto;
    padding: 5px;
}

.pos-product-item {
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 10px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
}

.pos-product-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    border-color: #28a745;
}

.pos-product-item.out-of-stock {
    opacity: 0.5;
    cursor: not-allowed;
    background-color: #f8d7da;
    border-color: #dc3545;
}

.pos-product-item.out-of-stock:hover {
    transform: none;
    box-shadow: none;
}

.pos-product-item.low-stock {
    border-left: 4px solid #ffc107;
    background-color: #fff3cd;
}

.pos-product-item .product-name {
    font-weight: 600;
    margin-bottom: 5px;
    font-size: 0.9rem;
}

.pos-product-item .price {
    color: #28a745;
    font-weight: bold;
    font-size: 1rem;
}

.pos-product-item .stock-badge {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 0.7rem;
}

.pos-product-item .product-code {
    font-size: 0.7rem;
    margin-top: 5px;
    color: #6c757d;
}

.pos-product-item .stock-info {
    font-size: 0.7rem;
    margin-top: 5px;
    color: #17a2b8;
}

.pos-cart {
    height: 350px;
    overflow-y: auto;
}

.pos-cart-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #dee2e6;
}

.pos-cart-item:last-child {
    border-bottom: none;
}

.pos-cart-totals {
    padding: 15px;
    border-top: 2px solid #dee2e6;
}

.nav-pills .nav-link {
    border-radius: 0;
    padding: 10px 15px;
    color: #495057;
}

.nav-pills .nav-link.active {
    background-color: #28a745;
    color: white;
}

.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.ms-1 { margin-left: 0.25rem; }
.ms-2 { margin-left: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.text-end { text-align: right; }
.w-100 { width: 100%; }
</style>

<?php
$footer_path = BASE_PATH . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}

/**
 * Generate a unique transaction code
 */
function generate_transaction_code($prefix = 'FOL') {
    return $prefix . '-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
}

/**
 * Generate a unique order number for kitchen
 */
function generate_kitchen_order_number() {
    return 'KIT-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
}

/**
 * Handle AJAX requests
 */
function handle_ajax_requests($user_id, $current_shift_id, $stock_tracked_categories) {
    // Get request type
    $ajax_action = $_GET['ajax'] ?? $_POST['ajax'] ?? '';
    
    // Search guests
    if ($ajax_action === 'search_guests') {
        $query = $_GET['query'] ?? '';
        
        if (strlen($query) < 2) {
            json_response(['status' => 'error', 'message' => 'Query too short', 'data' => []]);
            return;
        }
        
        try {
            $search_term = "%$query%";
            
            $guests = db_fetch_all("
                SELECT 
                    guest_id,
                    guest_code,
                    first_name,
                    last_name,
                    email,
                    phone
                FROM guests 
                WHERE first_name LIKE ? 
                   OR last_name LIKE ? 
                   OR CONCAT(first_name, ' ', last_name) LIKE ?
                   OR email LIKE ? 
                   OR phone LIKE ? 
                ORDER BY first_name ASC
                LIMIT 50
            ", [
                $search_term, $search_term, $search_term, $search_term, $search_term
            ]);
            
            json_response(['status' => 'success', 'data' => $guests ?: []]);
        } catch (Exception $e) {
            error_log("Guest search error: " . $e->getMessage());
            json_response(['status' => 'error', 'message' => $e->getMessage(), 'data' => []]);
        }
        return;
    }
    
    // Get products by category
    if ($ajax_action === 'get_products') {
        $category = $_GET['category'] ?? 'all';
        
        $sql = "SELECT p.*, c.category_name, c.category_id
                FROM pos_products p
                LEFT JOIN pos_categories c ON p.category_id = c.category_id
                WHERE p.is_active = 1";
        $params = [];
        
        if ($category !== 'all') {
            $sql .= " AND p.category_id = ?";
            $params[] = (int)$category;
        }
        
        $sql .= " ORDER BY c.sort_order, p.product_name LIMIT 50";
        
        try {
            $products = db_fetch_all($sql, $params) ?: [];
            
            if (empty($products)) {
                echo '<div class="text-center text-muted py-5">No products found in this category</div>';
            } else {
                foreach ($products as $product) {
                    // Determine if this product should track stock
                    $track_stock = in_array($product['category_id'], $stock_tracked_categories);
                    
                    // Calculate stock status only for tracked categories
                    $is_out_of_stock = false;
                    $is_low_stock = false;
                    $stock_class = '';
                    
                    if ($track_stock) {
                        $is_out_of_stock = ($product['current_stock'] ?? 0) <= 0;
                        $is_low_stock = ($product['current_stock'] ?? 0) <= ($product['min_stock'] ?? 5) && ($product['current_stock'] ?? 0) > 0;
                        $stock_class = $is_out_of_stock ? 'out-of-stock' : ($is_low_stock ? 'low-stock' : '');
                    }
                    ?>
                    <div class="pos-product-item <?php echo $stock_class; ?>" 
                         data-id="<?php echo $product['product_id'] ?? 0; ?>"
                         data-name="<?php echo htmlspecialchars($product['product_name'] ?? 'Product'); ?>"
                         data-price="<?php echo $product['unit_price'] ?? 0; ?>"
                         data-stock="<?php echo $product['current_stock'] ?? 0; ?>"
                         data-category-id="<?php echo $product['category_id'] ?? 0; ?>"
                         data-track-stock="<?php echo $track_stock ? '1' : '0'; ?>"
                         onclick="<?php echo ($track_stock && $is_out_of_stock) ? '' : 'addToCart(this)'; ?>">
                        
                        <?php if ($track_stock): ?>
                            <?php if ($is_out_of_stock): ?>
                                <span class="stock-badge badge bg-danger">Out of Stock</span>
                            <?php elseif ($is_low_stock): ?>
                                <span class="stock-badge badge bg-warning">Low Stock</span>
                            <?php endif; ?>
                        <?php endif; ?>
                        
                        <div class="product-name"><?php echo htmlspecialchars($product['product_name'] ?? 'Product'); ?></div>
                        <div class="price"><?php echo function_exists('format_currency') ? format_currency($product['unit_price'] ?? 0) : 'RWF ' . number_format($product['unit_price'] ?? 0, 2); ?></div>
                        
                        <?php if (!empty($product['product_code'])): ?>
                            <div class="product-code small text-muted"><?php echo htmlspecialchars($product['product_code']); ?></div>
                        <?php endif; ?>
                        
                        <?php if ($track_stock && !$is_out_of_stock): ?>
                            <div class="stock-info small text-muted">Stock: <?php echo $product['current_stock'] ?? 0; ?></div>
                        <?php endif; ?>
                    </div>
                    <?php
                }
            }
        } catch (Exception $e) {
            echo '<div class="text-center text-muted py-5">Error loading products: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
        return;
    }
    
    // Search products
    if ($ajax_action === 'search_products') {
        $query = $_GET['query'] ?? '';
        
        if (strlen($query) < 2) {
            echo '<div class="text-center text-muted py-5">Please enter at least 2 characters</div>';
            return;
        }
        
        try {
            $products = db_fetch_all("
                SELECT p.*, c.category_name, c.category_id
                FROM pos_products p
                LEFT JOIN pos_categories c ON p.category_id = c.category_id
                WHERE p.is_active = 1 
                AND (p.product_name LIKE ? OR p.product_code LIKE ?)
                ORDER BY p.product_name
                LIMIT 50
            ", ["%$query%", "%$query%"]) ?: [];
            
            if (empty($products)) {
                echo '<div class="text-center text-muted py-5">No products found</div>';
            } else {
                foreach ($products as $product) {
                    // Determine if this product should track stock
                    $track_stock = in_array($product['category_id'], $stock_tracked_categories);
                    
                    // Calculate stock status only for tracked categories
                    $is_out_of_stock = false;
                    $is_low_stock = false;
                    $stock_class = '';
                    
                    if ($track_stock) {
                        $is_out_of_stock = ($product['current_stock'] ?? 0) <= 0;
                        $is_low_stock = ($product['current_stock'] ?? 0) <= ($product['min_stock'] ?? 5) && ($product['current_stock'] ?? 0) > 0;
                        $stock_class = $is_out_of_stock ? 'out-of-stock' : ($is_low_stock ? 'low-stock' : '');
                    }
                    ?>
                    <div class="pos-product-item <?php echo $stock_class; ?>" 
                         data-id="<?php echo $product['product_id'] ?? 0; ?>"
                         data-name="<?php echo htmlspecialchars($product['product_name'] ?? 'Product'); ?>"
                         data-price="<?php echo $product['unit_price'] ?? 0; ?>"
                         data-stock="<?php echo $product['current_stock'] ?? 0; ?>"
                         data-category-id="<?php echo $product['category_id'] ?? 0; ?>"
                         data-track-stock="<?php echo $track_stock ? '1' : '0'; ?>"
                         onclick="<?php echo ($track_stock && $is_out_of_stock) ? '' : 'addToCart(this)'; ?>">
                        
                        <?php if ($track_stock): ?>
                            <?php if ($is_out_of_stock): ?>
                                <span class="stock-badge badge bg-danger">Out of Stock</span>
                            <?php elseif ($is_low_stock): ?>
                                <span class="stock-badge badge bg-warning">Low Stock</span>
                            <?php endif; ?>
                        <?php endif; ?>
                        
                        <div class="product-name"><?php echo htmlspecialchars($product['product_name'] ?? 'Product'); ?></div>
                        <div class="price"><?php echo function_exists('format_currency') ? format_currency($product['unit_price'] ?? 0) : 'RWF ' . number_format($product['unit_price'] ?? 0, 2); ?></div>
                        
                        <?php if (!empty($product['product_code'])): ?>
                            <div class="product-code small text-muted"><?php echo htmlspecialchars($product['product_code']); ?></div>
                        <?php endif; ?>
                        
                        <?php if ($track_stock && !$is_out_of_stock): ?>
                            <div class="stock-info small text-muted">Stock: <?php echo $product['current_stock'] ?? 0; ?></div>
                        <?php endif; ?>
                    </div>
                    <?php
                }
            }
        } catch (Exception $e) {
            echo '<div class="text-center text-muted py-5">Error searching products: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
        return;
    }
    
    // Check stock for a specific product
    if ($ajax_action === 'check_stock') {
        $product_id = $_GET['product_id'] ?? 0;
        $requested_quantity = $_GET['quantity'] ?? 0;
        
        try {
            $product = db_fetch_one("
                SELECT p.*, c.category_id 
                FROM pos_products p
                LEFT JOIN pos_categories c ON p.category_id = c.category_id
                WHERE p.product_id = ?
            ", [$product_id]);
            
            if (!$product) {
                json_response(['status' => 'error', 'message' => 'Product not found']);
                return;
            }
            
            $track_stock = in_array($product['category_id'], $stock_tracked_categories);
            
            if (!$track_stock) {
                json_response(['status' => 'success', 'data' => ['available' => true, 'current_stock' => null]]);
                return;
            }
            
            $current_stock = $product['current_stock'] ?? 0;
            $available = $current_stock >= $requested_quantity;
            
            json_response([
                'status' => 'success', 
                'data' => [
                    'available' => $available,
                    'current_stock' => $current_stock
                ]
            ]);
        } catch (Exception $e) {
            json_response(['status' => 'error', 'message' => $e->getMessage()]);
        }
        return;
    }
    
    // Process checkout
    if ($ajax_action === 'checkout') {
        $data = json_decode($_POST['data'] ?? '{}', true);
        
        if (empty($data)) {
            json_response(['status' => 'error', 'message' => 'Invalid data']);
            return;
        }
        
        // Check if we have an active shift
        if (!$current_shift_id) {
            json_response(['status' => 'error', 'message' => 'No open shift found. Please open a shift first.']);
            return;
        }
        
        try {
            // Begin transaction
            begin_transaction();
            
            // Calculate values
            $subtotal = $data['subtotal'];
            $tax_amount = $subtotal * 0.18; // 18% tax
            $discount_value = $data['discount'];
            
            // Calculate discount amount
            $discount_amount = 0;
            if ($data['discount_type'] === 'percentage') {
                $discount_amount = ($subtotal * $discount_value) / 100;
            } else {
                $discount_amount = $discount_value;
            }
            
            $total_amount = $subtotal + $tax_amount - $discount_amount;
            
            // Generate receipt number
            $receipt_number = 'RCP-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
            
            // Current timestamp
            $current_datetime = date('Y-m-d H:i:s');
            
            // Insert into pos_sales table
            $sale_data = [
                'receipt_number' => $receipt_number,
                'shift_id' => $current_shift_id,
                'user_id' => $user_id,
                'outlet_id' => $data['outlet_id'],
                'guest_id' => $data['guest_id'] ?? null,
                'customer_name' => $data['customer_name'] ?? 'Walk-in Customer',
                'subtotal' => $subtotal,
                'tax_amount' => $tax_amount,
                'discount_amount' => $discount_amount,
                'discount_type' => $data['discount_type'],
                'discount_value' => $data['discount'],
                'total_amount' => $total_amount,
                'payment_status' => 'completed',
                'sale_time' => $current_datetime,
                'created_at' => $current_datetime
            ];
            
            $sale_id = db_insert('pos_sales', $sale_data);
            
            if (!$sale_id) {
                throw new Exception('Failed to create sale');
            }
            
            // Insert sale items
            foreach ($data['items'] as $item) {
                // Check if enough stock ONLY for tracked categories
                if ($item['trackStock'] == 1) {
                    $product = db_fetch_one("SELECT current_stock FROM pos_products WHERE product_id = ?", [$item['id']]);
                    if (!$product || $product['current_stock'] < $item['quantity']) {
                        throw new Exception("Insufficient stock for product: " . $item['name']);
                    }
                }
                
                $item_data = [
                    'sale_id' => $sale_id,
                    'product_id' => $item['id'],
                    'quantity' => $item['quantity'],
                    'unit_price' => $item['price'],
                    'total_amount' => $item['price'] * $item['quantity'],
                    'is_voided' => 0
                ];
                
                db_insert('pos_sale_items', $item_data);
                
                // Update product stock ONLY for tracked categories
                if ($item['trackStock'] == 1) {
                    db_query("UPDATE pos_products SET current_stock = current_stock - ? WHERE product_id = ?", 
                            [$item['quantity'], $item['id']]);
                }
            }
            
            // Create kitchen order
            $kitchen_order_data = [
                'order_number' => generate_kitchen_order_number(),
                'sale_id' => $sale_id,
                'outlet_id' => $data['outlet_id'],
                'status' => 'pending',
                'created_by' => $user_id,
                'created_at' => $current_datetime
            ];
            
            db_insert('kitchen_orders', $kitchen_order_data);
            
            // Commit transaction
            commit_transaction();
            
            json_response([
                'status' => 'success', 
                'data' => [
                    'sale_id' => $sale_id,
                    'receipt_number' => $receipt_number
                ]
            ]);
            
        } catch (Exception $e) {
            rollback_transaction();
            json_response(['status' => 'error', 'message' => $e->getMessage()]);
        }
        return;
    }
    
    // Process add to existing receipt
    if ($ajax_action === 'add_to_existing') {
        $data = json_decode($_POST['data'] ?? '{}', true);
        
        if (empty($data)) {
            json_response(['status' => 'error', 'message' => 'Invalid data']);
            return;
        }
        
        try {
            // Begin transaction
            begin_transaction();
            
            // Get existing sale
            $sale = db_fetch_one("SELECT * FROM pos_sales WHERE sale_id = ?", [$data['sale_id']]);
            if (!$sale) {
                throw new Exception('Sale not found');
            }
            
            // Calculate new totals
            $additional_subtotal = 0;
            foreach ($data['items'] as $item) {
                $additional_subtotal += $item['price'] * $item['quantity'];
            }
            
            $additional_tax = $additional_subtotal * 0.18;
            $additional_total = $additional_subtotal + $additional_tax;
            
            // Update sale totals
            $new_subtotal = $sale['subtotal'] + $additional_subtotal;
            $new_tax = $sale['tax_amount'] + $additional_tax;
            $new_total = $sale['total_amount'] + $additional_total;
            
            db_update('pos_sales', [
                'subtotal' => $new_subtotal,
                'tax_amount' => $new_tax,
                'total_amount' => $new_total,
                'updated_at' => date('Y-m-d H:i:s')
            ], 'sale_id = ?', [$data['sale_id']]);
            
            // Insert additional sale items
            foreach ($data['items'] as $item) {
                // Check if enough stock ONLY for tracked categories
                if ($item['trackStock'] == 1) {
                    $product = db_fetch_one("SELECT current_stock FROM pos_products WHERE product_id = ?", [$item['id']]);
                    if (!$product || $product['current_stock'] < $item['quantity']) {
                        throw new Exception("Insufficient stock for product: " . $item['name']);
                    }
                }
                
                $item_data = [
                    'sale_id' => $data['sale_id'],
                    'product_id' => $item['id'],
                    'quantity' => $item['quantity'],
                    'unit_price' => $item['price'],
                    'total_amount' => $item['price'] * $item['quantity'],
                    'is_voided' => 0
                ];
                
                db_insert('pos_sale_items', $item_data);
                
                // Update product stock ONLY for tracked categories
                if ($item['trackStock'] == 1) {
                    db_query("UPDATE pos_products SET current_stock = current_stock - ? WHERE product_id = ?", 
                            [$item['quantity'], $item['id']]);
                }
            }
            
            // Commit transaction
            commit_transaction();
            
            json_response([
                'status' => 'success', 
                'data' => [
                    'sale_id' => $data['sale_id'],
                    'receipt_number' => $sale['receipt_number']
                ]
            ]);
            
        } catch (Exception $e) {
            rollback_transaction();
            json_response(['status' => 'error', 'message' => $e->getMessage()]);
        }
        return;
    }
    
    // Process room charge
    if ($ajax_action === 'room_charge') {
        $data = json_decode($_POST['data'] ?? '{}', true);
        
        if (empty($data)) {
            json_response(['status' => 'error', 'message' => 'Invalid data']);
            return;
        }
        
        // Check if we have an active shift
        if (!$current_shift_id) {
            json_response(['status' => 'error', 'message' => 'No open shift found. Please open a shift first.']);
            return;
        }
        
        try {
            // Begin transaction
            begin_transaction();
            
            // Calculate values
            $subtotal = $data['subtotal'];
            $tax_amount = $subtotal * 0.18; // 18% tax
            $discount_value = $data['discount'];
            
            // Calculate discount amount
            $discount_amount = 0;
            if ($data['discount_type'] === 'percentage') {
                $discount_amount = ($subtotal * $discount_value) / 100;
            } else {
                $discount_amount = $discount_value;
            }
            
            $total_amount = $subtotal + $tax_amount - $discount_amount;
            
            // Generate receipt number
            $receipt_number = 'RM-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
            
            // Generate transaction code for folio
            $transaction_code = generate_transaction_code('FOL');
            
            // Current timestamp
            $current_datetime = date('Y-m-d H:i:s');
            
            // Get reservation details to get guest_id
            $reservation = db_fetch_one("SELECT guest_id FROM reservations WHERE reservation_id = ?", [$data['reservation_id']]);
            
            // Insert into pos_sales table
            $sale_data = [
                'receipt_number' => $receipt_number,
                'shift_id' => $current_shift_id,
                'user_id' => $user_id,
                'outlet_id' => $data['outlet_id'],
                'guest_id' => $reservation['guest_id'] ?? null,
                'reservation_id' => $data['reservation_id'],
                'customer_name' => 'Room Charge',
                'subtotal' => $subtotal,
                'tax_amount' => $tax_amount,
                'discount_amount' => $discount_amount,
                'discount_type' => $data['discount_type'],
                'discount_value' => $data['discount'],
                'total_amount' => $total_amount,
                'payment_status' => 'completed',
                'sale_time' => $current_datetime,
                'created_at' => $current_datetime
            ];
            
            $sale_id = db_insert('pos_sales', $sale_data);
            
            if (!$sale_id) {
                throw new Exception('Failed to create sale');
            }
            
            // Insert sale items
            foreach ($data['items'] as $item) {
                // Check if enough stock ONLY for tracked categories
                if ($item['trackStock'] == 1) {
                    $product = db_fetch_one("SELECT current_stock FROM pos_products WHERE product_id = ?", [$item['id']]);
                    if (!$product || $product['current_stock'] < $item['quantity']) {
                        throw new Exception("Insufficient stock for product: " . $item['name']);
                    }
                }
                
                $item_data = [
                    'sale_id' => $sale_id,
                    'product_id' => $item['id'],
                    'quantity' => $item['quantity'],
                    'unit_price' => $item['price'],
                    'total_amount' => $item['price'] * $item['quantity'],
                    'is_voided' => 0
                ];
                
                db_insert('pos_sale_items', $item_data);
                
                // Update product stock ONLY for tracked categories
                if ($item['trackStock'] == 1) {
                    db_query("UPDATE pos_products SET current_stock = current_stock - ? WHERE product_id = ?", 
                            [$item['quantity'], $item['id']]);
                }
            }
            
            // Create folio charge for the reservation
            $folio_data = [
                'reservation_id' => $data['reservation_id'],
                'transaction_code' => $transaction_code,
                'charge_type' => 'fnb',
                'description' => 'Room charge from POS',
                'quantity' => 1,
                'unit_price' => $total_amount,
                'amount' => $total_amount,
                'tax_amount' => $tax_amount,
                'posted_by' => $user_id,
                'posted_at' => $current_datetime,
                'is_voided' => 0
            ];
            
            db_insert('folio_charges', $folio_data);
            
            // Commit transaction
            commit_transaction();
            
            json_response([
                'status' => 'success', 
                'data' => [
                    'sale_id' => $sale_id,
                    'receipt_number' => $receipt_number
                ]
            ]);
            
        } catch (Exception $e) {
            rollback_transaction();
            json_response(['status' => 'error', 'message' => $e->getMessage()]);
        }
        return;
    }
    
    // Default response
    json_response(['status' => 'error', 'message' => 'Invalid action']);
}

/**
 * Helper function for JSON responses
 */
function json_response($data) {
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}
?>