<?php
session_start();
$tablePosition = "table";
if (!isset($_SESSION['cart'])) {
  $_SESSION['cart'] = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title id="shopname">Hotel POS System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Premium Hotel Point of Sale System">
    
    <!-- Favicon -->
    <link href="img/favicon.ico" rel="icon">
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600&display=swap" rel="stylesheet">
    
    <!-- Icons -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
    
    <!-- SweetAlert -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.5.7/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #e74c3c;
            --light-color: #f8f9fa;
            --dark-color: #212529;
            --success-color: #28a745;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
            --bg-gradient: linear-gradient(135deg, #2c3e50 0%, #4ca1af 100%);
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background: var(--bg-gradient);
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            color: var(--dark-color);
            min-height: 100vh;
        }
        
        .navbar {
            background: rgba(44, 62, 80, 0.98) !important;
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            padding: 0.8rem 1rem;
        }
        
        .navbar-brand {
            font-family: 'Playfair Display', serif;
            font-weight: 700;
            font-size: 1.5rem;
            letter-spacing: 0.5px;
        }
        
        .menu-container {
            background: rgba(255, 255, 255, 0.98);
            border-radius: 12px;
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.12);
            backdrop-filter: blur(8px);
            margin-top: 30px;
            padding: 2rem;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .section-title {
            font-family: 'Playfair Display', serif;
            color: var(--primary-color);
            position: relative;
            display: inline-block;
            font-size: 2.2rem;
            margin-bottom: 1.5rem;
        }
        
        .section-title:after {
            content: '';
            position: absolute;
            width: 40%;
            height: 4px;
            background: var(--secondary-color);
            bottom: -12px;
            left: 30%;
            border-radius: 2px;
        }
        
        .nav-pills {
            flex-wrap: wrap;
            justify-content: center;
            gap: 8px;
            margin-bottom: 2rem;
        }
        
        .nav-pills .nav-link {
            border-radius: 10px;
            padding: 12px 20px;
            transition: all 0.3s ease;
            color: var(--dark-color);
            background: rgba(236, 240, 241, 0.7);
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
            border: 1px solid rgba(0,0,0,0.05);
        }
        
        .nav-pills .nav-link.active {
            background: var(--secondary-color);
            color: white;
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(52, 152, 219, 0.3);
        }
        
        .nav-pills .nav-link i {
            font-size: 1.2rem;
        }
        
        .food-card {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 25px;
            border: none;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        
        .food-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
        }
        
        .food-img-container {
            height: 180px;
            overflow: hidden;
            position: relative;
        }
        
        .food-img {
            height: 100%;
            width: 100%;
            object-fit: cover;
            transition: transform 0.5s ease;
        }
        
        .food-card:hover .food-img {
            transform: scale(1.05);
        }
        
        .food-info {
            padding: 20px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        
        .food-name {
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 8px;
            font-size: 1.1rem;
        }
        
        .food-price {
            color: var(--accent-color);
            font-weight: 700;
            font-size: 1.2rem;
            margin-bottom: 10px;
        }
        
        .food-desc {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 15px;
            flex-grow: 1;
        }
        
        .add-to-cart-btn {
            background: var(--secondary-color);
            color: white;
            border: none;
            border-radius: 50px;
            padding: 10px 25px;
            transition: all 0.3s ease;
            font-weight: 500;
            align-self: flex-start;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .add-to-cart-btn:hover {
            background: var(--primary-color);
            transform: scale(1.05);
            box-shadow: 0 5px 15px rgba(44, 62, 80, 0.2);
        }
        
        .cart-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            font-size: 0.7rem;
            min-width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        /* Modal Styles */
        .modal-content {
            border-radius: 15px;
            border: none;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }
        
        .modal-header {
            background: var(--primary-color);
            color: white;
            padding: 1.2rem 1.5rem;
        }
        
        .modal-title {
            font-weight: 600;
        }
        
        .cart-item {
            border-left: 4px solid var(--secondary-color);
            transition: all 0.3s ease;
        }
        
        .cart-item:hover {
            background-color: rgba(52, 152, 219, 0.05);
        }
        
        /* Search Styles */
        #searchInput {
            border-radius: 50px;
            padding: 12px 25px;
            border: 2px solid #eee;
            box-shadow: none;
            font-size: 1rem;
        }
        
        #searchInput:focus {
            border-color: var(--secondary-color);
            box-shadow: 0 0 0 0.25rem rgba(52, 152, 219, 0.25);
        }
        
        /* Button Styles */
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }
        
        .btn-primary:hover {
            background-color: #2980b9;
            border-color: #2980b9;
            transform: translateY(-2px);
        }
        
        .btn-success {
            background-color: var(--success-color);
            border-color: var(--success-color);
        }
        
        .btn-warning {
            background-color: var(--warning-color);
            border-color: var(--warning-color);
            color: var(--dark-color);
        }
        
        .btn-danger {
            background-color: var(--accent-color);
            border-color: var(--accent-color);
        }
        
        /* Badge Styles */
        .badge {
            padding: 6px 10px;
            font-weight: 500;
            letter-spacing: 0.5px;
        }
        
        /* Pagination Styles */
        .pagination .page-item.active .page-link {
            background: var(--secondary-color);
            border-color: var(--secondary-color);
        }
        
        .pagination .page-link {
            color: var(--dark-color);
            border-radius: 8px;
            margin: 0 5px;
            border: none;
            padding: 8px 15px;
        }
        
        /* Responsive Adjustments */
        @media (max-width: 992px) {
            .menu-container {
                padding: 1.5rem;
            }
            
            .section-title {
                font-size: 1.8rem;
            }
        }
        
        @media (max-width: 768px) {
            .nav-pills .nav-link {
                padding: 10px 15px;
                font-size: 0.9rem;
            }
            
            .food-card {
                margin-bottom: 20px;
            }
            
            .section-title {
                font-size: 1.6rem;
            }
        }
        
        @media (max-width: 576px) {
            .menu-container {
                padding: 1rem;
                border-radius: 8px;
            }
            
            .section-title {
                font-size: 1.4rem;
            }
            
            .nav-pills .nav-link {
                padding: 8px 12px;
                font-size: 0.8rem;
            }
        }
        
        /* Animation Classes */
        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* Loading Spinner */
        #spinner {
            background: rgba(255, 255, 255, 0.9);
            z-index: 9999;
        }
        
        .spinner-grow {
            width: 4rem;
            height: 4rem;
        }
        
        /* Back to Top Button */
        .back-to-top {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            z-index: 99;
        }
        
        .back-to-top.active {
            opacity: 1;
            visibility: visible;
        }
    </style>
</head>

<body>
    <!-- Loading Spinner -->
   

    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark px-4 px-lg-5 py-3 py-lg-0 fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand d-flex align-items-center" href="#">
                <i class="fas fa-utensils me-2"></i>
                <span id="shopname1" class="fw-bold">Hotel POS</span>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item">
                        <a class="nav-link active" href="menu.php"><i class="fas fa-list me-1"></i> Menu</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="index.php"><i class="fas fa-home me-1"></i> Home</a>
                    </li>
                </ul>
                <div class="d-flex align-items-center">
                    <div class="position-relative me-3">
                        <a href="#" class="btn btn-primary rounded-circle p-2" data-bs-toggle="modal" data-bs-target="#pending-bills-modal">
                            <i class="fas fa-file-invoice"></i>
                            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger cart-badge" id="pending-bills-count">0</span>
                        </a>
                    </div>
                    <div class="position-relative">
                        <a href="#" class="btn btn-primary rounded-circle p-2" data-bs-toggle="modal" data-bs-target="#cart-modal">
                            <i class="fas fa-shopping-cart"></i>
                            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger cart-badge" id="cart-items-count">0</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="container my-5 pt-5">
        <div class="menu-container p-4 p-lg-5">
            <div class="text-center mb-5 wow fadeInUp" data-wow-delay="0.1s">
                <h5 class="section-title ff-secondary text-center fw-normal">Food & Beverages Menu</h5>
                <p class="text-muted">Select from our exquisite menu offerings</p>
            </div>
            
            <!-- Search Bar -->
            <div class="row justify-content-center mb-4">
                <div class="col-md-8">
                    <div class="input-group">
                        <span class="input-group-text bg-primary text-white"><i class="fas fa-search"></i></span>
                        <input type="text" id="searchInput" class="form-control" placeholder="Search menu items...">
                    </div>
                    <div id="searchResults" class="mt-2"></div>
                </div>
            </div>
            
            <!-- Menu Tabs -->
            <div class="tab-class text-center wow fadeInUp" data-wow-delay="0.1s">
                <ul class="nav nav-pills d-inline-flex justify-content-center border-bottom mb-5 flex-wrap">
                    <li class="nav-item"><a class="nav-link active" data-bs-toggle="pill" href="#tab-1"><i class="fas fa-coffee"></i> Breakfast</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-2"><i class="fas fa-concierge-bell"></i> Lunch & Dinner</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-3"><i class="fas fa-pizza-slice"></i> Pizzas</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-4"><i class="fas fa-cheese"></i> Beef Wraps</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-5"><i class="fas fa-drumstick-bite"></i> Chicken Wraps</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-6"><i class="fas fa-carrot"></i> Vegetables</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-7"><i class="fas fa-fish"></i> Fish</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-8"><i class="fas fa-wine-bottle"></i> Drinks</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-10"><i class="fas fa-cocktail"></i> Cocktails</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-9"><i class="fas fa-piggy-bank"></i> Pork</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="pill" href="#tab-11"><i class="fas fa-smoking"></i> Cigarettes</a></li>
                </ul>
                
                <div class="tab-content">
                    <!-- Breakfast Tab -->
                    <div id="tab-1" class="tab-pane fade show active" role="tabpanel">
                        <div class="row g-4" id="BreakfastItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="BreakfastPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Lunch & Dinner Tab -->
                    <div id="tab-2" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="LunchItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="LunchPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Pizzas Tab -->
                    <div id="tab-3" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="PizzaItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="PizzaPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Beef Wraps Tab -->
                    <div id="tab-4" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="BeefItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="BeefPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Chicken Wraps Tab -->
                    <div id="tab-5" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="ChickenItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="ChickenPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Vegetables Tab -->
                    <div id="tab-6" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="VegetableItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="VegetablePagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Fish Tab -->
                    <div id="tab-7" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="FishItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="FishPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Drinks Tab -->
                    <div id="tab-8" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="BeveragesItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="BeveragesItemsPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Cocktails Tab -->
                    <div id="tab-10" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="totsItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="totsPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Pork Tab -->
                    <div id="tab-9" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="PorkItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="PorkPagination"></ul>
                        </nav>
                    </div>
                    
                    <!-- Cigarettes Tab -->
                    <div id="tab-11" class="tab-pane fade" role="tabpanel">
                        <div class="row g-4" id="CigarettesItemsContainer"></div>
                        <nav aria-label="Page navigation" class="mt-4">
                            <ul class="pagination justify-content-center" id="CigarettesPagination"></ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Cart Modal -->
    <div class="modal fade" id="cart-modal" tabindex="-1" aria-labelledby="cartModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fas fa-shopping-cart me-2"></i> Current Order</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="table-responsive">
                        <table class="table align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th width="40%">Item</th>
                                    <th width="20%">Quantity</th>
                                    <th width="20%">Price</th>
                                    <th width="20%">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="cart-items">
                                <!-- Cart items will be populated here -->
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="row mt-4">
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-body">
                                    <h5 class="card-title text-primary mb-3">Order Summary</h5>
                                    <div class="d-flex justify-content-between mb-2">
                                        <span class="text-muted">Subtotal:</span>
                                        <span id="subtotal" class="fw-bold">Ksh 0.00</span>
                                    </div>
                                    <div class="d-flex justify-content-between mb-3">
                                        <span class="text-muted">Tax (0%):</span>
                                        <span id="tax" class="fw-bold">Ksh 0.00</span>
                                    </div>
                                    <hr>
                                    <div class="d-flex justify-content-between">
                                        <span class="fw-bold">Total:</span>
                                        <span id="total" class="fw-bold fs-5 text-primary">Ksh 0.00</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm h-100">
                                <div class="card-body">
                                    <h5 class="card-title text-primary mb-3">Order Notes</h5>
                                    <textarea class="form-control mb-3" rows="3" placeholder="Add special instructions..."></textarea>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="urgentOrder">
                                        <label class="form-check-label" for="urgentOrder">
                                            <i class="fas fa-bolt text-warning me-1"></i> Urgent Order
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-arrow-left me-1"></i> Continue Shopping
                    </button>
                    <button type="button" class="btn btn-outline-danger" id="clear-cart-button">
                        <i class="fas fa-trash-alt me-1"></i> Clear Order
                    </button>
                    <button type="button" class="btn btn-warning" id="saveSessionBtn">
                        <i class="fas fa-save me-1"></i> Save Order
                    </button>
                    <button type="button" class="btn btn-success" id="submit-order">
                        <i class="fas fa-paper-plane me-1"></i> Submit Order
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Pending Bills Modal -->
    <div class="modal fade" id="pending-bills-modal" tabindex="-1" aria-labelledby="pendingBillsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="pendingBillsModalLabel"><i class="fas fa-file-invoice me-2"></i> Pending Orders</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="sessions-table">
                            <thead class="table-light">
                                <tr>
                                    <th>ID</th>
                                    <th>Order Name</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody id="sessions-table-body"></tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Save Session Modal -->
    <div class="modal fade" id="saveSessionModal" tabindex="-1" aria-labelledby="saveSessionModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="saveSessionModalLabel"><i class="fas fa-save me-2"></i> Save Current Order</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="saveSessionForm">
                        <div class="mb-3">
                            <label for="sessionNameInput" class="form-label">Order Name</label>
                            <input type="text" class="form-control" id="sessionNameInput" placeholder="e.g., Table 5 - Lunch Order" required>
                            <div class="form-text">Give this order a descriptive name for easy retrieval.</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" id="saveSessionBtnConfirm" class="btn btn-primary">Save Order</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Back to Top Button -->
    <a href="#" class="btn btn-lg btn-primary btn-lg-square back-to-top"><i class="fas fa-arrow-up"></i></a>

    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- JavaScript Libraries -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="lib/wow/wow.min.js"></script>
    <script src="lib/easing/easing.min.js"></script>
    <script src="lib/waypoints/waypoints.min.js"></script>
    <script src="lib/counterup/counterup.min.js"></script>
    <script src="lib/owlcarousel/owl.carousel.min.js"></script>
    <script src="lib/tempusdominus/js/moment.min.js"></script>
    <script src="lib/tempusdominus/js/moment-timezone.min.js"></script>
    <script src="lib/tempusdominus/js/tempusdominus-bootstrap-4.min.js"></script>
    <!-- Include SweetAlert2 JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script>



    <!-- Template Javascript -->
    <script src="js/main.js"></script>
    
    <script>
  document.addEventListener('DOMContentLoaded', () => {
    const addToCartBtns = document.querySelectorAll('.add-to-cart-btn');

    addToCartBtns.forEach(btn => {
      btn.addEventListener('click', (event) => {
        event.preventDefault();
        const foodId = btn.getAttribute('data-food-id');
        const foodName = btn.getAttribute('data-food-name');
        const foodPrice = btn.getAttribute('data-food-price');

        // Set the values of the hidden input fields in the form
        document.getElementById('food-id').value = foodId;
        document.getElementById('food-name').value = foodName;
        document.getElementById('food-price').value = foodPrice;

        // Submit the form to add the item to the cart
        document.getElementById('add-to-cart-btn').click();
      });
    });
  });
  </script>
  
 
<script>

 document.addEventListener('DOMContentLoaded', () => {
  const cartItemsContainer = document.getElementById('cart-items');
  const subtotalElement = document.getElementById('subtotal');
  const totalElement = document.getElementById('total');
  const cartItemsCountElement = document.getElementById('cart-items-count');
  const clearCartButton = document.getElementById('clear-cart-btn');

  // Function to update the cart items count in the round icon
  function updateCartItemsCount(count) {
    cartItemsCountElement.textContent = count;
  }

 // Function to display the cart items, subtotal, and total
// Function to display the cart items, subtotal, and total
function displayCartItems() {
  // Clear the cart items container
  cartItemsContainer.innerHTML = '';

  // Retrieve the cart items from the PHP session
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'gearbox/get_cart_items.kts.php', true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {
        const cartItemsJSON = xhr.responseText;
        const items = JSON.parse(cartItemsJSON) || [];

        let subtotal = 0;

        // Loop through the cart items and create HTML elements for each item
        items.forEach((item) => {
          const row = document.createElement('tr');
          row.className = 'cart-item align-middle';
          row.innerHTML = `
            <td>
              <div class="d-flex align-items-center">
                <span class="fw-medium">${item.food_name}</span>
              </div>
            </td>
            <td>
              <div class="d-flex align-items-center">
                <button class="btn btn-sm btn-outline-secondary decrease-quantity" data-food-id="${item.food_id}">
                  <i class="fas fa-minus"></i>
                </button>
                <span class="mx-2 fw-medium">${item.quantity}</span>
                <button class="btn btn-sm btn-outline-secondary increase-quantity" data-food-id="${item.food_id}">
                  <i class="fas fa-plus"></i>
                </button>
              </div>
            </td>
            <td class="fw-medium">Ksh ${parseFloat(item.food_price).toFixed(2)}</td>
            <td>
              <button class="btn btn-sm btn-outline-danger remove-item" data-food-id="${item.food_id}">
                <i class="fas fa-trash-alt"></i>
              </button>
            </td>
          `;
          cartItemsContainer.appendChild(row);

          subtotal += parseFloat(item.food_price) * item.quantity;
        });

        // Update the subtotal and total elements
        subtotalElement.textContent = `Ksh ${subtotal.toFixed(2)}`;
        totalElement.textContent = `Ksh ${subtotal.toFixed(2)}`;

        // Update the cart items count
        updateCartItemsCount(items.length);

        // Add event listeners to the quantity buttons
        const increaseButtons = document.querySelectorAll('.increase-quantity');
        const decreaseButtons = document.querySelectorAll('.decrease-quantity');
        const removeButtons = document.querySelectorAll('.remove-item');

        increaseButtons.forEach((button) => {
          button.addEventListener('click', () => {
            const foodId = button.getAttribute('data-food-id');
            changeCartItemQuantity(foodId, +1);
          });
        });

        decreaseButtons.forEach((button) => {
          button.addEventListener('click', () => {
            const foodId = button.getAttribute('data-food-id');
            changeCartItemQuantity(foodId, -1);
          });
        });

        removeButtons.forEach((button) => {
          button.addEventListener('click', () => {
            const foodId = button.getAttribute('data-food-id');
            removeCartItem(foodId);
          });
        });

        // Add event listener to clear cart button
        const clearCartButton = document.getElementById('clear-cart-button');
        if (clearCartButton) {
          clearCartButton.addEventListener('click', clearCart);
        }

      } else {
        console.error('Error retrieving cart items:', xhr.status);
        // Show error to user
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to load cart items. Please try again.',
        });
      }
    }
  };
  xhr.onerror = function() {
    console.error('Request failed');
    Swal.fire({
      icon: 'error',
      title: 'Connection Error',
      text: 'Unable to connect to server. Please check your connection.',
    });
  };
  xhr.send();
}
function changeCartItemQuantity(foodId, quantityChange) {
  console.log('Change cart item quantity:', foodId, quantityChange);

  fetch('gearbox/update_cart_items.kts.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ foodId: parseInt(foodId), quantityChange: parseInt(quantityChange) }),
  })
    .then((response) => {
      if (response.ok) {
        // Update the cart items and display them
        displayCartItems();
      } else {
        console.error('Error updating cart item:', response.status);
      }
    })
    .catch((error) => {
      console.error('Error updating cart item:', error);
    });
}


  // Function to remove a cart item
  function removeCartItem(foodId) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'gearbox/remove_cart_item.kts.php', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
          // Update the cart items in the PHP session
          displayCartItems();
        } else {
          console.error('Error removing cart item:', xhr.status);
        }
      }
    };
    xhr.send(JSON.stringify({ foodId }));
  }

  // Function to clear the cart
  function clearCart() {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'gearbox/clear_cart.kts.php', true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
          // Display an empty cart
          displayCartItems();
        } else {
          console.error('Error clearing cart:', xhr.status);
        }
      }
    };
    xhr.send();
  }

  // Call the displayCartItems function to initially display the cart items
  displayCartItems();

  // Update the cart items count whenever the cart items change
  window.addEventListener('storage', (event) => {
    if (event.key === 'cart') {
      displayCartItems();
    }
  });
});


</script>
<script>
$(document).ready(function() {
    // Event handler for price option change (for beverages)
    $(document).on('change', 'select[name="price_option"]', function() {
        const selectedPrice = $(this).val(); // Get the selected price from the dropdown
        const productId = $(this).closest('tr').find('.add-to-cart-btn').data('product-id'); // Get the product ID

        console.log('Selected price:', selectedPrice, 'for product ID:', productId);

        // Call updatePrice function passing selectedPrice and productId
        updatePrice(selectedPrice, productId);
    });

    // Function to update UI elements based on selected price
    function updatePrice(selectedPrice, productId) {
        console.log('Updating price for product ID:', productId, 'to:', selectedPrice);
        // Optionally, update UI elements to reflect the selected price
    }

    // Event handler for add-to-cart button (for both food and beverages)
    $(document).on('click', '.add-to-cart-btn', function(e) {
        e.preventDefault(); // Prevent the default action of the anchor tag

        const productId = $(this).data('product-id'); // Get the product ID from data attribute
        const productName = $(this).data('product-name'); // Get the product name from data attribute
        let sellingPrice = $(this).data('selling-price'); // Get the default selling price from data attribute
        const cat = $(this).data('cat'); // Get the category (cat) from data attribute

        // For beverages, check if there's a selected price from the dropdown
        if ($(this).closest('tr').find('select[name="price_option"]').length > 0) {
            sellingPrice = $(this).closest('tr').find('select[name="price_option"]').val();
        }

        console.log('Add to cart clicked for product k ID:', productId, 'with price:', sellingPrice);

        // Validate that sellingPrice is defined
        if (typeof sellingPrice === 'undefined') {
            console.error('Selected price is undefined.');
            return;
        }

        // Create an object with the required data
        const requestData = {
            productId: productId,
            productName: productName,
            sellingPrice: sellingPrice,
            cat: cat,
            quantityChange: 1 // Assuming you want to add 1 quantity to the cart
        };

        // Send the AJAX request to add the item to the cart
        fetch('gearbox/add_to_cart.kts.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        })
        .then(response => response.json())
        .then(data => {
            location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
            // Perform any additional actions if needed
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });
});

</script>

<script>
$(document).ready(function() {
  // Check if button was recently clicked (using sessionStorage)
  if (sessionStorage.getItem('buttonDisabled')) {
    var disabledTime = parseInt(sessionStorage.getItem('buttonDisabled'));
    var currentTime = new Date().getTime();
    var timeDiff = currentTime - disabledTime;
    
    // If less than 15 seconds have passed, keep button disabled
    if (timeDiff < 15000) {
      disableButton();
      var remainingTime = Math.ceil((15000 - timeDiff) / 1000);
      startCountdown(remainingTime);
    } else {
      // Clear the storage if time has passed
      sessionStorage.removeItem('buttonDisabled');
    }
  }

  $("#submit-order").click(function() {
    // Disable the button immediately
    disableButton();
    
    // Store the current time in sessionStorage
    sessionStorage.setItem('buttonDisabled', new Date().getTime());
    
    // Start countdown
    startCountdown(15);

    // Perform AJAX request
    $.ajax({
      url: "gearbox/proccess_order.kts.php",
      method: "POST",
      success: function(response) {
        try {
          var jsonResponse = (typeof response === 'object') ? response : JSON.parse(response);

          if (jsonResponse.success) {
            Swal.fire({
              icon: 'success',
              title: 'Success',
              text: jsonResponse.message,
              showConfirmButton: true
            }).then(() => {
              // Clear the disabled state before redirecting
              sessionStorage.removeItem('buttonDisabled');
              window.location.href = "print.php";
            });
          } else {
            Swal.fire({
              icon: 'error',
              title: 'Error',
              text: jsonResponse.message + "\n" + jsonResponse.error
            });
            console.log("Error: " + jsonResponse.error);
          }
        } catch (e) {
          console.error("Parsing error: ", e);
          console.log("Response: ", response);
          Swal.fire({
            icon: 'error',
            title: 'Parsing Error',
            text: 'An error occurred while processing the response.'
          });
        }
      },
      error: function(xhr, status, error) {
        console.log("AJAX Error: " + error);
        Swal.fire({
          icon: 'error',
          title: 'AJAX Error',
          text: 'An error occurred during the AJAX request.'
        });
      }
    });
  });

  function disableButton() {
    var $button = $("#submit-order");
    $button.prop('disabled', true);
    $button.addClass('disabled-button');
  }

  function enableButton() {
    var $button = $("#submit-order");
    $button.prop('disabled', false);
    $button.removeClass('disabled-button');
    $button.text('Submit Order'); // Reset button text
    sessionStorage.removeItem('buttonDisabled');
  }

  function startCountdown(seconds) {
    var $button = $("#submit-order");
    var remaining = seconds;
    
    $button.text('Please wait (' + remaining + 's)');
    
    var countdown = setInterval(function() {
      remaining--;
      $button.text('Please wait (' + remaining + 's)');
      
      if (remaining <= 0) {
        clearInterval(countdown);
        enableButton();
      }
    }, 1000);
  }
});
</script>



<script>
    $(document).ready(function() {
        var currentPage = 1;

        // Function to fetch and display Tots items based on the current page
        function fetchTotsItems(page) {
            $.ajax({
                type: 'GET',
                url: 'gearbox/fetch_tot_items.kts.php',
                data: { page: page },
                dataType: 'json',
                success: function(response) {
                    // Clear previous content
                    $('#totsItemsContainer').empty();

                    if (response && response.items && response.items.length > 0) {
                        // Display fetched Tots items
                        $.each(response.items, function(index, item) {
                            var itemHtml = '<div class="col-lg-6">' +
                                '<div class="d-flex align-items-center">' +
                                '<img class="flex-shrink-0 img-fluid rounded" src="./uploaded/' + item.image + '" alt="" style="width: 80px;">' +
                                '<div class="w-100 d-flex flex-column text-start ps-4">' +
                                '<h5 class="d-flex justify-content-between border-bottom pb-2">' +
                                '<span>' + item.name + '</span>' +
                                '<span class="text-primary">Ksh' + item.price + '</span>' +
                                '</h5>' +
                                '<p class="d-flex justify-content-between border-bottom pb-2">' +
                                '<small class="fst-italic">' + item.description + '</small>' +
                                '<span>' +
                                '<a href="#" class="btn2 btn-primary py-2 px-3 me-3 animated slideInLeft add-to-cart-btn1" ' + 
                                'data-food-id="' + item.food_id + '" ' +
                                'data-food-name="' + item.name + '" ' +
                                'data-food-price="' + item.price + '" ' +
                                'data-cat="' + item.cat + '">' +
                                '<i class="fas fa-shopping-cart"></i>' +
                                '</a>' +
                                '</span>' +
                                '</p>' +
                                '</div>' +
                                '</div>' +
                                '</div>';
                            $('#totsItemsContainer').append(itemHtml);
                        });

                        // Update pagination buttons
                        updatePagination(response.pagination);
                    } else {
                        console.log('No Tots items found.');
                    }
                },
                error: function(xhr, status, error) {
                    console.log('Error fetching Tots items:', error);
                }
            });
        }

        // Function to update pagination buttons
        function updatePagination(pagination) {
            var paginationContainer = $('#totsItemsContainer_pagination ul');
            paginationContainer.empty(); // Clear previous pagination buttons

            // Previous button
            var prevButton = '<li class="page-item ' + (pagination.currentPage === 1 ? 'disabled' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + (pagination.currentPage - 1) + '">Previous</a>' +
                '</li>';
            paginationContainer.append(prevButton);

            // Page numbers
            for (var i = 1; i <= pagination.totalPages; i++) {
                var pageButton = '<li class="page-item ' + (pagination.currentPage === i ? 'active' : '') + '">' +
                    '<a class="page-link" href="#" data-page="' + i + '">' + i + '</a>' +
                    '</li>';
                paginationContainer.append(pageButton);
            }

            // Next button
            var nextButton = '<li class="page-item ' + (pagination.currentPage === pagination.totalPages ? 'disabled' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + (pagination.currentPage + 1) + '">Next</a>' +
                '</li>';
            paginationContainer.append(nextButton);

            // Log pagination data for debugging
            console.log('Pagination:', pagination);
        }

        // Initial fetch of Tots items on page load
        fetchTotsItems(currentPage);

        // Event handler for pagination buttons
        $(document).on('click', '.pagination .page-link', function(e) {
            e.preventDefault();
            var page = parseInt($(this).data('page'));
            if (page !== currentPage) {
                currentPage = page;
                fetchTotsItems(currentPage);
            }
        });

        // Event handler for add-to-cart buttons
        $(document).on('click', '.add-to-cart-btn1', function(e) {
            e.preventDefault();
            var productId = $(this).data('food-id');
            var productName = $(this).data('food-name');
            var productPrice = $(this).data('food-price');
            var cat = $(this).data('cat'); // Get the category from data attribute

            console.log('Add to cart clicked for product ID:', productId, 'with price:', productPrice, 'and category:', cat);
            if (productId === undefined || productPrice === undefined || cat === undefined) {
                console.log('Product ID, Price, or Category is undefined');
            } else {
                const requestData = {
                    productId: productId,
                    productName: productName,
                    sellingPrice: productPrice,
                    cat: cat, // Use the category fetched from data attribute
                    quantityChange: 1 // Assuming you want to add 1 quantity to the cart
                };

                // Send the AJAX request to add the item to the cart
                fetch('gearbox/add_to_cart.kts.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                .then(response => response.json())
                .then(data => {
                   location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
                    // Perform any additional actions if needed
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            }
        });
    });
</script>
    
    
    
<script>
$(document).ready(function() {
    // Function to fetch and display items based on the current page and category
    function fetchItems(page, category, containerId, paginationId) {
        $.ajax({
            type: 'GET',
            url: 'gearbox/fetch_items.kts.php',
            data: { page: page, category: category },
            dataType: 'json',
            success: function(response) {
                console.log('Response:', response); // Log the response data
                var container = $('#' + containerId);
                container.empty(); // Clear previous content in the container

                // Check if response has valid items
                if (response && response[category] && response[category].items.length > 0) {
                    // Iterate over items and append them to the container
                    $.each(response[category].items, function(index, item) {
                        console.log('Item:', item); // Log each item data
                        var itemHtml = '<div class="col-lg-6">' +
                            '<div class="d-flex align-items-center">' +
                            '<img class="flex-shrink-0 img-fluid rounded" src="uploaded/' + item.image + '" alt="" style="width: 80px;">' +
                            '<div class="w-100 d-flex flex-column text-start ps-4">' +
                            '<h5 class="d-flex justify-content-between border-bottom pb-2">' +
                            '<span>' + item.product_name + '</span>' +
                            '<span class="text-primary">Ksh' + item.selling_price + '</span>' +
                            '</h5>' +
                            '<p class="d-flex justify-content-between border-bottom pb-2">' +
                            '<small class="fst-italic">' + item.description + '</small>' +
                            '<span>' +
                            '<a href="#" class="btn2 btn-primary py-2 px-3 me-3 animated slideInLeft add-to-cart-btn-items" ' +
                            'data-food-id="' + item.product_id + '" ' +
                            'data-food-name="' + item.product_name + '" ' +
                            'data-food-price="' + item.selling_price + '" ' +
                            'data-cat="' + category + '">' +
                            '<i class="fas fa-shopping-cart"></i>' +
                            '</a>' +
                            '</span>' +
                            '</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        container.append(itemHtml); // Append each item
                    });

                    // Update pagination buttons
                    updatePagination(response[category].total_pages, page, category, paginationId);
                } else {
                    console.log('No items found for category: ' + category);
                    container.html('<p>No items available for this category.</p>'); // Display message when no items
                }
            },
            error: function(xhr, status, error) {
                console.log('Error fetching items for category ' + category + ':', error);
            }
        });
    }

    // Function to update pagination buttons
    function updatePagination(totalPages, currentPage, category, paginationId) {
        var paginationContainer = $('#' + paginationId);
        paginationContainer.empty(); // Clear previous pagination buttons

        // Previous button
        var prevButton = '<li class="page-item ' + (currentPage === 1 ? 'disabled' : '') + '">' +
            '<a class="page-link" href="#" data-page="' + (currentPage - 1) + '" data-category="' + category + '" data-container="' + paginationId + '">Previous</a>' +
            '</li>';
        paginationContainer.append(prevButton);

        // Page numbers
        for (var i = 1; i <= totalPages; i++) {
            var pageButton = '<li class="page-item ' + (currentPage === i ? 'active' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + i + '" data-category="' + category + '" data-container="' + paginationId + '">' + i + '</a>' +
                '</li>';
            paginationContainer.append(pageButton);
        }

        // Next button
        var nextButton = '<li class="page-item ' + (currentPage === totalPages ? 'disabled' : '') + '">' +
            '<a class="page-link" href="#" data-page="' + (currentPage + 1) + '" data-category="' + category + '" data-container="' + paginationId + '">Next</a>' +
            '</li>';
        paginationContainer.append(nextButton);

        console.log('Pagination updated:', { totalPages: totalPages, currentPage: currentPage });
    }

    // Event handler for pagination buttons
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        var page = parseInt($(this).data('page'));
        var category = $(this).data('category');
        var paginationId = $(this).data('container');
       
        // Validate if the page number is valid
        if (!isNaN(page)) {
            fetchItems(page, category, category + 'ItemsContainer', paginationId);
        }
    });

    // List of categories and their corresponding containers and pagination ids
    var categories = [
        { category: 'Breakfast', containerId: 'BreakfastItemsContainer', paginationId: 'BreakfastItemsPagination' },
        { category: 'Lunch', containerId: 'LunchItemsContainer', paginationId: 'LunchItemsPagination' },
        { category: 'Pizza', containerId: 'PizzaItemsContainer', paginationId: 'PizzaItemsPagination' },
        { category: 'Beef', containerId: 'BeefItemsContainer', paginationId: 'BeefItemsPagination' },
        { category: 'Chicken', containerId: 'ChickenItemsContainer', paginationId: 'ChickenItemsPagination' },
        { category: 'Vegetables', containerId: 'VegetableItemsContainer', paginationId: 'VegetableItemsPagination' },
        { category: 'Fish', containerId: 'FishItemsContainer', paginationId: 'FishItemsPagination' },
        { category: 'Beverages', containerId: 'BeveragesItemsContainer', paginationId: 'BeveragesItemsPagination' },
        { category: 'Pork', containerId: 'PorkItemsContainer', paginationId: 'PorkItemsPagination' },
        { category: 'Cigarettes', containerId: 'CigarettesItemsContainer', paginationId: 'CigarettesItemsPagination' }
    ];

    // Fetch items for all categories initially (default to page 1)
    categories.forEach(function(categoryData) {
        fetchItems(1, categoryData.category, categoryData.containerId, categoryData.paginationId);
    });

    // Event handler for add-to-cart buttons
    $(document).on('click', '.add-to-cart-btn-items', function(e) {
        e.preventDefault();
        var productId = $(this).data('food-id');
        var productName = $(this).data('food-name');
        var productPrice = $(this).data('food-price');
        var productCat = $(this).data('cat');

        console.log('Add to cart clicked for product ID:', productId, 'with price:', productPrice, 'and category:', productCat);
        if (productId === undefined || productPrice === undefined || productCat === undefined) {
            console.log('Product ID, Price, or Category is undefined');
        } else {
            const requestData = {
                productId: productId,
                productName: productName,
                sellingPrice: productPrice,
                cat: productCat,
                quantityChange: 1 // Assuming you want to add 1 quantity to the cart
            };

            // Send the AJAX request to add the item to the cart
            fetch('gearbox/add_to_cart.kts.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
                // Perform any additional actions if needed
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    });
});


</script>

<script>
$(document).ready(function() {
    $('#searchInput').on('input', function() {
        var searchQuery = $(this).val().trim();

        // Check if search query is empty
        if (searchQuery === '') {
            // If empty, clear the search results
            $('#searchResults').empty();
            return; // Exit the function early
        }

        // Send AJAX request to fetch search results
        $.ajax({
            url: './gearbox/search.kts.php',
            method: 'POST',
            data: { query: searchQuery },
            success: function(response) {
                $('#searchResults').html(response);
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
            }
        });
    });
});
</script>


<script>
    // JavaScript code to fetch data and display it
    function fetchBusinessDetails() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', './database/fetch_business.kts.php', true);
        xhr.onload = function() {
            if (this.status === 200) {
                var data = JSON.parse(this.responseText);
                
                console.log(data);  // Check if contact2 is present in the response
                
                // Check if no error
                if (!data.error) {
                    // Update the span elements with the fetched data
                    document.getElementById('shopname').innerText = data.shop_name || '';
                    document.getElementById('shopname1').innerText = data.shop_name || '';
                    document.getElementById('location').innerText = data.location || '';
                    document.getElementById('quote').innerText = data.quote || '';
                    document.getElementById('street').innerText = data.street || '';
                    document.getElementById('address').innerText = data.address || '';
                    document.getElementById('pin').innerText = data.pin || '';
                    document.getElementById('contact1').innerText = data.contact1 || '';
                    document.getElementById('contact2').innerText = data.contact2 || ''; // This should populate contact2
                } else {
                    console.error("Error: " + data.error);
                }
            } else {
                console.error("Failed to fetch data");
            }
        };
        xhr.send();
    }

    // Call the function as soon as the DOM is fully loaded
    document.addEventListener('DOMContentLoaded', fetchBusinessDetails);
</script>
<script>
document.getElementById("saveSessionBtn").addEventListener("click", function () {
    // Open the modal
    const saveSessionModal = new bootstrap.Modal(document.getElementById("saveSessionModal"));
    saveSessionModal.show();

    // Clear input field
    document.getElementById("sessionNameInput").value = "";

    // Add click event for the confirm button
    document.getElementById("saveSessionBtnConfirm").addEventListener("click", function () {
        const sessionNameInput = document.getElementById("sessionNameInput");
        const sessionName = sessionNameInput.value.trim();

        // Validate input
        if (!sessionName) {
            Swal.fire({
                title: 'Validation Error',
                text: 'Please enter a session name!',
                icon: 'warning',
                confirmButtonText: 'OK'
            });
            sessionNameInput.focus();
            return;
        }

        // Assuming 'cart' is your cart data array
        const cart = []; // Replace with actual cart data

        // Prepare data to send
        const data = {
            sessionName: sessionName,
            cart: cart
        };

        // Send data to the server
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "./gearbox/save_session.kts.php", true);
        xhr.setRequestHeader("Content-Type", "application/json");

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        // SweetAlert for success
                        Swal.fire({
                            title: 'Success!',
                            text: 'Session saved successfully.',
                            icon: 'success',
                            confirmButtonText: 'OK'
                        });
                    } else {
                        // SweetAlert for error
                        Swal.fire({
                            title: 'Error!',
                            text: response.message,
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                } else {
                    // SweetAlert for unexpected server error
                    Swal.fire({
                        title: 'Server Error!',
                        text: 'Unable to save the session. Please try again later.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            }
        };

        xhr.send(JSON.stringify(data));

        // Hide the modal after initiating the save process
        saveSessionModal.hide();
    });
});


</script>
<script>
    document.addEventListener("DOMContentLoaded", () => {
        // Fetch all sessions and populate the table
        document.querySelector('[data-bs-target="#pending-bills-modal"]').addEventListener("click", () => {
            fetchSessions();
        });

        // Retrieve button click handler
        document.getElementById("sessions-table").addEventListener("click", (e) => {
            if (e.target.classList.contains("btn-retrieve")) {
                const sessionId = e.target.getAttribute("data-session-id");
                retrieveSessionData(sessionId);
            }
        });
    });

    // Fetch all sessions
    function fetchSessions() {
        fetch("./gearbox/fetch_sessions.kts.php")
            .then((response) => response.json())
            .then((data) => {
                if (data.success) {
                    const tableBody = document.getElementById("sessions-table-body");
                    tableBody.innerHTML = ""; // Clear previous rows

                    data.sessions.forEach((session) => {
                        const row = document.createElement("tr");
                        row.innerHTML = `
                            <td>${session.id}</td>
                            <td>${session.session_name}</td>
                            <td>
                                <button class="btn btn-primary btn-retrieve" data-session-id="${session.id}">Retrieve</button>
                            </td>
                        `;
                        tableBody.appendChild(row);
                    });
                } else {
                    Swal.fire({
                        icon: "error",
                        title: "Error",
                        text: data.message || "Failed to fetch sessions.",
                    });
                }
            })
            .catch((error) => {
                console.error("Error fetching sessions:", error);
                Swal.fire({
                    icon: "error",
                    title: "Error",
                    text: "An unexpected error occurred while fetching sessions.",
                });
            });
    }

    // Retrieve session data and store in session cart
    function retrieveSessionData(sessionId) {
        fetch("./gearbox/retrieve_session_items.kts.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ sessionId }),
        })
            .then((response) => response.json())
            .then((data) => {
                if (data.success) {
                    Swal.fire({
                        icon: "success",
                        title: "Success",
                        text: "Session data retrieved successfully.",
                        confirmButtonText: "OK",
                    }).then(() => {
                        // Reload the page after the user clicks "OK"
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: "error",
                        title: "Error",
                        text: data.message || "Failed to retrieve session data.",
                    });
                }
            })
            .catch((error) => {
                console.error("Error retrieving session data:", error);
                Swal.fire({
                    icon: "error",
                    title: "Error",
                    text: "An unexpected error occurred while retrieving session data.",
                });
            });
    }
</script>


</body>

</html>