based on view_order_customer.php (<?php
// public/orders/view_order_customer.php

// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start output buffering to prevent "headers already sent" errors
ob_start();

// Include authentication, database connection, and functions
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Include the functions.php for sanitize_input()

// Helper Function: Generate WhatsApp link
/**
 * Generate a WhatsApp link from a contact number.
 *
 * @param string $contact The contact number.
 * @return string The WhatsApp URL.
 */
function generate_whatsapp_link($contact) {
    // Remove any non-digit characters
    $digits = preg_replace('/\D+/', '', $contact);
    
    // Assuming Kuwait country code (+965). Adjust as needed.
    if (substr($digits, 0, 3) !== '965') {
        $digits = '965' . $digits;
    }
    
    return "https://wa.me/" . $digits;
}

// Check if order_id is given
$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

if ($order_id <= 0) {
    header("Location: view_orders.php?error=6"); // Invalid order ID
    exit();
}

// Fetch order details along with customer information
$order_sql = "
    SELECT 
        orders.id AS order_id,
        orders.status,
        orders.priority,
        orders.order_date,
        orders.delivery_datetime,
        customers.name AS customer_name,
        customers.contact,
        customers.delivery_address
    FROM 
        orders
    JOIN 
        customers ON orders.customer_id = customers.id
    WHERE 
        orders.id = ?
";
$order_stmt = $conn->prepare($order_sql);
if (!$order_stmt) {
    die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
}
$order_stmt->bind_param("i", $order_id);
$order_stmt->execute();
$order_result = $order_stmt->get_result();
$order = $order_result->fetch_assoc();
$order_stmt->close();

if (!$order) {
    header("Location: view_orders.php?error=7"); // Order not found
    exit();
}

// Fetch order items with product details
$order_items_sql = "
    SELECT 
        order_items.id AS item_id,
        order_items.product_id,
        order_items.quantity,
        order_items.packaging_preferences,
        order_items.discount_percentage,
        order_items.discount_reason,
        products.name AS product_name,
        products.size AS product_size,
        products.price AS product_price
    FROM 
        order_items
    JOIN 
        products ON order_items.product_id = products.id
    WHERE 
        order_items.order_id = ?
";
$item_stmt = $conn->prepare($order_items_sql);
if (!$item_stmt) {
    die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
}
$item_stmt->bind_param("i", $order_id);
$item_stmt->execute();
$order_items_result = $item_stmt->get_result();
$order_items = [];
while ($item = $order_items_result->fetch_assoc()) {
    $order_items[] = $item;
}
$item_stmt->close();

// Calculate totals
$total_before_discounts = 0;
$total_discounts = 0;
$final_total = 0;

foreach ($order_items as &$item) {
    $item_total = $item['quantity'] * $item['product_price'];
    $discount_amount = ($item['discount_percentage'] / 100) * $item_total;
    $item['discount_amount'] = $discount_amount;
    $item['total_after_discount'] = $item_total - $discount_amount;

    $total_before_discounts += $item_total;
    $total_discounts += $discount_amount;
}
unset($item); // Break reference
$final_total = $total_before_discounts - $total_discounts;

// Currency formatting
function format_currency($amount) {
    return "KWD " . number_format($amount, 2);
}

// Now include the header AFTER form handling
require_once '../../includes/header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Order #<?= htmlspecialchars($order['order_id']) ?> Details - Kaak Alia Management System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
    
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="/kaak_alia_management_system/assets/bootstrap/css/bootstrap.min.css">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Custom Styles -->
    <style>
        /* ---------------------------------------------------
           1. CSS Variables for Consistent Design
        ---------------------------------------------------- */
        :root {
            --dark-gray: #333333; /* Header and Footer Background */
            --button-add-order: #e2a20c; /* Light Golden-Yellow */
            --button-view-orders: #118AB2; /* Blue */
            --button-manage-products: #06D6A0; /* Green */
            --button-manage-users: #F4A261; /* Orange */
            --button-generate-reports: #EF476F; /* Red-Pink */

            --main-text: #333333;
            --secondary-text: #666666;
            --white: #FFFFFF;
            --background-gradient: linear-gradient(to bottom, #f5f7fa, #c3cfe2);
            --divider-color: #FFD166;

            --hover-shadow: rgba(0, 0, 0, 0.2);
            --critical-highlight: #FFF9C4; /* Light Yellow-Orange */
            --section-border: #e0e0e0;
        }

        /* ---------------------------------------------------
           2. Global Styles
        ---------------------------------------------------- */
        .container-body {
            font-family: 'Cairo', sans-serif;
            background: var(--background-gradient);
            margin: 0;
            padding: 20px;
            box-sizing: border-box;
        }

        h1, h2, h3, h4, h5, p {
            margin: 0;
        }

        /* ---------------------------------------------------
           3. Header Styles
        ---------------------------------------------------- */
        .header {
            padding: 20px 30px;
            background-color: var(--dark-gray);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 30px;
        }

        .header h1 {
            color: var(--white);
            font-size: 28px;
            font-weight: bold;
        }

        /* ---------------------------------------------------
           4. Welcome Section
        ---------------------------------------------------- */
        .welcome-section {
            background-color: var(--white);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            padding: 25px;
            text-align: center;
            margin-bottom: 30px;
        }

        .welcome-section h3 {
            font-size: 24px;
            color: var(--main-text);
            margin-bottom: 10px;
        }

        .welcome-section hr {
            width: 60px;
            height: 4px;
            background-color: var(--button-add-order);
            border: none;
            margin: 10px auto;
            border-radius: 2px;
        }

        /* ---------------------------------------------------
           5. Order Information Section
        ---------------------------------------------------- */
        .order-info-section {
            background-color: var(--white);
            border-radius: 12px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            padding: 25px;
            margin-bottom: 30px;
        }

        .order-info-section h4 {
            font-size: 22px;
            font-weight: bold;
            color: var(--main-text);
            margin-bottom: 20px;
        }

        .order-info-section .info-label {
            font-weight: 600;
            color: var(--secondary-text);
            display: inline-block;
            width: 180px;
        }

        .order-info-section p {
            font-size: 16px;
            color: var(--main-text);
            margin-bottom: 10px;
        }

        /* Highlight Critical Information */
        .critical-info {
            background-color: var(--critical-highlight);
            padding: 10px;
            border-radius: 6px;
            display: inline-block;
            margin-left: 10px;
        }

        /* ---------------------------------------------------
           6. Order Items Table
        ---------------------------------------------------- */
        .recent-orders-section {
            background-color: var(--white);
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .recent-orders-section h4 {
            font-size: 22px;
            font-weight: bold;
            color: var(--main-text);
            margin-bottom: 20px;
        }

        /* Make table responsive */
        .table-responsive {
            overflow-x: auto;
        }

        .recent-orders-section table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }

        .recent-orders-section th, 
        .recent-orders-section td {
            padding: 15px;
            text-align: left;
            font-size: 16px;
            vertical-align: middle;
        }

        .recent-orders-section th {
            background-color: #333333;
            color: var(--white);
            font-weight: bold;
            position: sticky;
            top: 0;
            z-index: 1;
        }

        .recent-orders-section tr:nth-child(even) {
            background-color: #F9F9F9;
        }

        .recent-orders-section tr:hover {
            background-color: #e6f7ff;
        }

        .recent-orders-section td {
            font-size: 14px;
            color: #333333;
        }

        .recent-orders-section td.number {
            text-align: center;
        }

        .recent-orders-section td.price, 
        .recent-orders-section td.quantity, 
        .recent-orders-section td.discount_percentage, 
        .recent-orders-section td.discount_amount, 
        .recent-orders-section td.total_after_discount {
            text-align: center;
            font-weight: bold;
        }

        /* ---------------------------------------------------
           7. Order Summary Section
        ---------------------------------------------------- */
        .total-section {
            text-align: right;
            margin-top: 20px;
        }

        .total-section p {
            font-size: 18px;
            color: var(--main-text);
            margin-bottom: 8px;
        }

        .total-section p strong {
            font-size: 20px;
        }

        /* ---------------------------------------------------
           8. Action Buttons
        ---------------------------------------------------- */
        .action-buttons {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
        }

        .action-button {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 12px 20px;
            font-size: 16px;
            font-weight: bold;
            color: var(--white);
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            text-decoration: none;
        }

        .action-button.print-order { background-color: var(--button-view-orders); }
        .action-button.edit-order { background-color: var(--button-add-order); }

        .action-button:hover {
            transform: scale(1.02);
            box-shadow: 0 6px 12px var(--hover-shadow);
        }

        .action-button .bi {
            margin-right: 8px;
            font-size: 20px;
        }

        /* ---------------------------------------------------
           9. Footer Styles
        ---------------------------------------------------- */
        .footer {
            background-color: var(--dark-gray);
            color: var(--white);
            padding: 15px;
            text-align: center;
            border-radius: 8px;
            font-size: 14px;
            line-height: 20px;
            margin-top: 40px;
        }

        /* ---------------------------------------------------
           10. Responsive Design Enhancements
        ---------------------------------------------------- */
        @media (max-width: 768px) {
            .order-info-section .info-label {
                width: 140px;
            }

            .recent-orders-section table {
                min-width: 600px;
            }

            .action-buttons {
                flex-direction: column;
                align-items: stretch;
            }

            .action-button {
                width: 100%;
                justify-content: center;
            }
        }

        @media (max-width: 480px) {
            .header {
                padding: 15px 20px;
            }

            .header h1 {
                font-size: 22px;
            }

            .welcome-section h3 {
                font-size: 20px;
            }

            .recent-orders-section th, 
            .recent-orders-section td {
                padding: 10px;
                font-size: 12px;
            }

            .recent-orders-section h4 {
                font-size: 18px;
            }

            .action-button {
                font-size: 14px;
                padding: 10px 15px;
            }

            .action-button .bi {
                font-size: 18px;
                margin-right: 5px;
            }
        }
    </style>

    <!-- Additional JavaScript for Print Functionality -->
    <script>
        function printOrder() {
            window.print();
        }
    </script>
</head>
<body class="container-body">
    <!-- Header Already Included via header.php -->

    <main class='container-body'>
        <!-- Welcome Section -->
        <div class="welcome-section">
            <h3>Order #<?= htmlspecialchars($order['order_id']) ?></h3>
            <hr>
        </div>

        <!-- Order Information Section -->
        <div class="order-info-section">
            <h4>Order Information</h4>
            <div class="row mb-3">
                <div class="col-md-6 mb-3">
                    <p><span class="info-label">Status:</span> 
                        <?php
                            switch($order['status']) {
                                case 'Pending':
                                    echo '<span class="badge-status-pending critical-info">' . htmlspecialchars($order['status']) . '</span>';
                                    break;
                                case 'In Progress':
                                    echo '<span class="badge-status-in-progress critical-info">' . htmlspecialchars($order['status']) . '</span>';
                                    break;
                                case 'Completed':
                                    echo '<span class="badge-status-completed critical-info">' . htmlspecialchars($order['status']) . '</span>';
                                    break;
                                case 'Delivered':
                                    echo '<span class="badge-status-delivered critical-info">' . htmlspecialchars($order['status']) . '</span>';
                                    break;
                                default:
                                    echo htmlspecialchars($order['status']);
                            }
                        ?>
                    </p>
                    <p><span class="info-label">Priority:</span> <?= htmlspecialchars($order['priority']) ?></p>
                    <p><span class="info-label">Order Date:</span> <?= date("d M Y, h:i A", strtotime($order['order_date'])) ?></p>
                    <p><span class="info-label">Delivery Date & Time:</span> <?= $order['delivery_datetime'] ? date("d M Y, h:i A", strtotime($order['delivery_datetime'])) : 'N/A' ?></p>
                </div>
                <div class="col-md-6 mb-3">
                    <p><span class="info-label">Customer Name:</span> <?= htmlspecialchars($order['customer_name']) ?></p>
                    <p>
                        <span class="info-label">Contact:</span> 
                        <a href="<?= generate_whatsapp_link($order['contact']) ?>" target="_blank" class="d-inline-flex align-items-center">
                            <i class="bi bi-whatsapp" style="color: #25D366;"></i>
                            <span class="ms-2"><?= htmlspecialchars($order['contact']) ?></span>
                        </a>
                    </p>
                    <p><span class="info-label">Delivery Address:</span> <?= nl2br(htmlspecialchars($order['delivery_address'])) ?></p>
                </div>
            </div>
        </div>

        <!-- Order Items Table Section -->
        <div class="recent-orders-section">
            <h4>Order Items</h4>
            <div class="table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Product</th>
                            <th>Size</th>
                            <th>Price per Unit (KWD)</th>
                            <th>Quantity</th>
                            <th>Packaging Preferences</th>
                            <th>Discount (%)</th>
                            <th>Discount Amount (KWD)</th>
                            <th>Total (KWD)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($order_items as $index => $item): ?>
                            <tr>
                                <td class="number"><?= $index + 1 ?></td>
                                <td><?= htmlspecialchars($item['product_name']) ?></td>
                                <td><?= htmlspecialchars($item['product_size']) ?></td>
                                <td class="price"><?= format_currency($item['product_price']) ?></td>
                                <td class="quantity"><?= htmlspecialchars($item['quantity']) ?></td>
                                <td><?= htmlspecialchars($item['packaging_preferences']) ?: 'N/A' ?></td>
                                <td class="discount_percentage"><?= number_format($item['discount_percentage'], 2) ?>%</td>
                                <td class="discount_amount"><?= format_currency($item['discount_amount']) ?></td>
                                <td class="total_after_discount"><?= format_currency($item['total_after_discount']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Order Summary -->
            <div class="total-section">
                <p><strong>Total Before Discounts:</strong> <?= format_currency($total_before_discounts) ?></p>
                <p><strong>Total Discounts:</strong> <?= format_currency($total_discounts) ?></p>
                <hr>
                <p><strong>Final Total:</strong> <?= format_currency($final_total) ?></p>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="action-buttons">
            <button class="action-button print-order" onclick="printOrder()">
                <i class="bi bi-printer-fill"></i> Print Order
            </button>
            <a href="edit_order.php?id=<?= htmlspecialchars($order['order_id']) ?>" class="action-button edit-order">
                <i class="bi bi-pencil-square"></i> Edit Order
            </a>
        </div>

        <!-- Footer -->
        <div class="footer">
            &copy; 2024 Kaak Alia Bakery. All rights reserved.
        </div>
    </main>

    <!-- Bootstrap JS Bundle -->
    <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>) and this header (<?php
// includes/header.php

// Start the session
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include authentication and database connection
require_once 'auth.php';
require_once 'db_connect.php';

// Fetch the last pending order ID to initialize polling
$last_order_id = 0;
$initial_pending_sql = "
    SELECT o.id 
    FROM orders o
    WHERE o.status = 'Pending' 
    ORDER BY o.id DESC 
    LIMIT 1
";
$initial_result = $conn->query($initial_pending_sql);
if ($initial_result && $initial_result->num_rows > 0) {
    $row = $initial_result->fetch_assoc();
    $last_order_id = intval($row['id']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Meta Tags for Responsiveness and Accessibility -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    
    <!-- Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Bootstrap JS Bundle with Popper (Loaded Defer for Performance) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" defer></script>
    <!-- Alpine.js for Interactivity -->
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.10.3/dist/cdn.min.js" defer></script>
</head>
<body class="bg-background-gradient">

    <!-- Audio Element for New Order Alert -->
    <audio id="newOrderAudio" src="/assets/audio/you_have_a_new_order.mp3" preload="auto"></audio>

    <!-- Header -->
    <header class="admin-header fixed-top bg-gray-800 text-white py-4 border-b-4 border-yellow-400 shadow-lg z-50">
        <div class="container mx-auto px-4">
            <div class="flex justify-between items-center">
                <!-- Logo -->
                <div class="logo flex items-center">
                    <a href="/public/dashboard.php" class="flex items-center">
                        <img src="/assets/img/logo.png" alt="Kaak Alia Logo" class="h-12 w-auto transition-transform duration-300 hover:scale-105">
                        <span class="ml-2 text-xl font-bold">Admin Panel</span>
                    </a>
                </div>

                <!-- Navigation Links (Desktop) -->
                <nav class="hidden md:flex space-x-4">
                    <a href="/public/orders/add_order.php" class="flex items-center bg-yellow-400 text-gray-800 px-4 py-2 rounded-lg hover:bg-yellow-300 shadow transition-all duration-300">
                        <i class="bi bi-plus-circle-fill mr-2"></i> Add Order
                    </a>
                    <a href="/public/orders/view_orders.php" class="flex items-center bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-400 shadow transition-all duration-300">
                        <i class="bi bi-eye-fill mr-2"></i> View Orders
                    </a>
                    <a href="/public/products/manage_products.php" class="flex items-center bg-green-400 text-white px-4 py-2 rounded-lg hover:bg-green-300 shadow transition-all duration-300">
                        <i class="bi bi-box-seam-fill mr-2"></i> Manage Products
                    </a>
                    <a href="/public/users/manage_users.php" class="flex items-center bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-400 shadow transition-all duration-300">
                        <i class="bi bi-people-fill mr-2"></i> Manage Users
                    </a>
                    <a href="/public/reports/generate_reports.php" class="flex items-center bg-pink-500 text-white px-4 py-2 rounded-lg hover:bg-pink-400 shadow transition-all duration-300">
                        <i class="bi bi-bar-chart-fill mr-2"></i> Reports
                    </a>
                </nav>

                <!-- Right Side Icons -->
                <div class="flex items-center space-x-4">
                    <!-- Notifications Dropdown -->
                    <div class="relative" x-data="{ open: false }">
                        <button @click="open = !open" class="relative text-white hover:text-yellow-400 focus:outline-none" aria-haspopup="true" aria-expanded="false" aria-controls="notification-menu" aria-label="Notifications">
                            <i class="bi bi-bell-fill text-2xl"></i>
                            <?php if ($last_order_id > 0): ?>
                                <!-- Notification Badge -->
                                <span class="absolute top-0 right-0 inline-block w-3 h-3 bg-red-500 rounded-full"></span>
                            <?php endif; ?>
                        </button>
                        <!-- Dropdown Menu -->
                        <div x-show="open" @click.away="open = false" id="notification-menu" class="absolute right-0 mt-2 w-80 bg-gray-800 text-white rounded-lg shadow-lg z-50">
                            <div class="py-2 px-4 border-b border-yellow-400">
                                <h3 class="text-lg font-semibold">Notifications</h3>
                            </div>
                            <ul class="max-h-64 overflow-y-auto" id="notificationsList">
                                <?php
                                // Fetch the latest 5 pending orders with their items
                                $notifications_sql = "
                                    SELECT o.id, o.order_date, c.name AS customer_name, oi.quantity, p.name AS product_name
                                    FROM orders o
                                    JOIN customers c ON o.customer_id = c.id
                                    JOIN order_items oi ON oi.order_id = o.id
                                    JOIN products p ON oi.product_id = p.id
                                    WHERE o.status = 'Pending'
                                    ORDER BY o.id DESC
                                    LIMIT 5
                                ";
                                $notifications_result = $conn->query($notifications_sql);
                                if ($notifications_result && $notifications_result->num_rows > 0):
                                    while($notification = $notifications_result->fetch_assoc()):
                                ?>
                                        <li class="px-4 py-2 hover:bg-gray-700 cursor-pointer">
                                            <span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
                                            New Order: <?= htmlspecialchars($notification['customer_name'], ENT_QUOTES, 'UTF-8'); ?> ordered <?= htmlspecialchars($notification['product_name'], ENT_QUOTES, 'UTF-8'); ?> x<?= htmlspecialchars($notification['quantity'], ENT_QUOTES, 'UTF-8'); ?>
                                        </li>
                                <?php
                                    endwhile;
                                else:
                                ?>
                                    <li class="px-4 py-2 text-gray-400">No new notifications</li>
                                <?php endif; ?>
                            </ul>
                            <div class="py-2 px-4 border-t border-yellow-400 text-center">
                                <a href="/public/notifications.php" class="text-yellow-400 hover:underline">View All</a>
                            </div>
                        </div>
                    </div>

                    <!-- User Profile Dropdown -->
                    <div class="relative" x-data="{ open: false }">
                        <button @click="open = !open" class="flex items-center focus:outline-none" aria-haspopup="true" aria-expanded="false" aria-controls="profile-menu">
                            <img src="/assets/images/user-placeholder.png" alt="User Avatar" class="h-10 w-10 rounded-full border-2 border-white hover:border-yellow-400 transition-colors duration-300">
                            <span class="ml-2 hidden lg:inline-block">
                                <?php
                                    // Display the logged-in user's username
                                    echo isset($_SESSION['username']) ? htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8') : 'User';
                                ?>
                            </span>
                            <i class="bi bi-caret-down-fill ml-1 hidden lg:inline-block"></i>
                        </button>
                        <!-- Dropdown Menu -->
                        <div x-show="open" @click.away="open = false" id="profile-menu" class="absolute right-0 mt-2 w-48 bg-gray-800 text-white rounded-lg shadow-lg z-50">
                            <a href="/public/users/settings.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
                                <i class="bi bi-gear-fill mr-2"></i> Settings
                            </a>
                            <a href="/public/logout.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
                                <i class="bi bi-box-arrow-right mr-2"></i> Logout
                            </a>
                        </div>
                    </div>

                    <!-- Mobile Menu Button -->
                    <div class="md:hidden">
                        <button id="mobile-menu-button" class="text-white focus:outline-none" aria-label="Toggle Mobile Menu">
                            <i class="bi bi-list text-2xl"></i>
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- Mobile Navigation Menu -->
            <nav id="mobile-menu" class="hidden md:hidden mt-4">
                <ul class="flex flex-col space-y-2">
                    <li>
                        <a href="/public/orders/add_order.php" class="flex items-center bg-yellow-400 text-gray-800 px-4 py-2 rounded-lg hover:bg-yellow-300 transition-all duration-300">
                            <i class="bi bi-plus-circle-fill mr-2"></i> Add Order
                        </a>
                    </li>
                    <li>
                        <a href="/public/orders/view_orders.php" class="flex items-center bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-400 transition-all duration-300">
                            <i class="bi bi-eye-fill mr-2"></i> View Orders
                        </a>
                    </li>
                    <li>
                        <a href="/public/products/manage_products.php" class="flex items-center bg-green-400 text-white px-4 py-2 rounded-lg hover:bg-green-300 transition-all duration-300">
                            <i class="bi bi-box-seam-fill mr-2"></i> Manage Products
                        </a>
                    </li>
                    <li>
                        <a href="/public/users/manage_users.php" class="flex items-center bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-400 transition-all duration-300">
                            <i class="bi bi-people-fill mr-2"></i> Manage Users
                        </a>
                    </li>
                    <li>
                        <a href="/public/reports/generate_reports.php" class="flex items-center bg-pink-500 text-white px-4 py-2 rounded-lg hover:bg-pink-400 transition-all duration-300">
                            <i class="bi bi-bar-chart-fill mr-2"></i> Reports
                        </a>
                    </li>
                    <!-- Additional Mobile Links -->
                    <li>
                        <a href="/public/notifications.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
                            <i class="bi bi-bell-fill mr-2"></i> Notifications
                        </a>
                    </li>
                </ul>
            </nav>
        </header>

    <!-- JavaScript for Real-Time Notifications and Audio Alert -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const mobileMenuButton = document.getElementById('mobile-menu-button');
            const mobileMenu = document.getElementById('mobile-menu');

            // Toggle menu on button click
            mobileMenuButton.addEventListener('click', function() {
                mobileMenu.classList.toggle('hidden');
            });

            let lastOrderId = <?= $last_order_id ?>;
            const audio = document.getElementById('newOrderAudio');

            // Function to fetch new orders
            function fetchNewOrders() {
                fetch(`/includes/get_new_orders.php?last_order_id=${lastOrderId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.orders && data.orders.length > 0) {
                            data.orders.forEach(order => {
                                // Update lastOrderId
                                if (order.id > lastOrderId) {
                                    lastOrderId = order.id;
                                }

                                // Append to the notifications list
                                const notificationsList = document.getElementById('notificationsList');
                                const li = document.createElement('li');
                                li.className = 'px-4 py-2 hover:bg-gray-700 cursor-pointer';
                                li.innerHTML = `
                                    <span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
                                    New Order: ${sanitizeHTML(order.customer_name)} ordered ${sanitizeHTML(order.product_name)} x${sanitizeHTML(order.quantity)}
                                `;
                                // Insert the new notification at the top
                                notificationsList.insertBefore(li, notificationsList.firstChild);

                                // Play the audio alert
                                if (audio) {
                                    audio.play().catch(function(error) {
                                        console.log('Audio playback failed:', error);
                                    });
                                }

                                // Optionally, update the notification badge
                                const bellIcon = document.querySelector('header .bi-bell-fill');
                                const existingBadge = bellIcon.parentNode.querySelector('.notification-badge');
                                if (!existingBadge) {
                                    const badge = document.createElement('span');
                                    badge.className = 'notification-badge absolute top-0 right-0 inline-block w-3 h-3 bg-red-500 rounded-full';
                                    bellIcon.parentNode.appendChild(badge);
                                }
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching new orders:', error);
                    });
            }

            // Function to sanitize HTML to prevent XSS
            function sanitizeHTML(str) {
                var temp = document.createElement('div');
                temp.textContent = str;
                return temp.innerHTML;
            }

            // Poll every 10 seconds
            setInterval(fetchNewOrders, 10000); // 10000 ms = 10 seconds

            // Optional: Fetch immediately on page load
            fetchNewOrders();
        });
    </script>

    <!-- Remove Redundant Bootstrap JS Inclusion -->
    <!-- <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script> -->
</body>
</html>) and thsi info database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 09, 2024 at 01:37 PM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `u406552082_kaakalia`
--

-- --------------------------------------------------------

--
-- Table structure for table `customers`
--

CREATE TABLE `customers` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `contact` varchar(50) DEFAULT NULL,
  `delivery_address` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `orders`
--

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `customer_id` int(11) NOT NULL,
  `status` enum('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
  `priority` enum('Normal','Important','Quick') DEFAULT 'Normal',
  `order_date` datetime DEFAULT current_timestamp(),
  `delivery_datetime` datetime DEFAULT NULL,
  `delivery_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `order_items`
--

CREATE TABLE `order_items` (
  `id` int(11) NOT NULL,
  `order_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL DEFAULT 1,
  `packaging_preferences` varchar(255) DEFAULT NULL,
  `discount_percentage` decimal(5,2) DEFAULT 0.00,
  `discount_reason` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `size` varchar(50) DEFAULT NULL,
  `price` decimal(10,2) NOT NULL,
  `category` varchar(50) DEFAULT NULL,
  `thumbnail` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `role` enum('admin','staff') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
  ADD PRIMARY KEY (`id`),
  ADD KEY `customer_id` (`customer_id`),
  ADD KEY `idx_orders_customer_id` (`customer_id`);

--
-- Indexes for table `order_items`
--
ALTER TABLE `order_items`
  ADD PRIMARY KEY (`id`),
  ADD KEY `order_id` (`order_id`),
  ADD KEY `product_id` (`product_id`),
  ADD KEY `idx_order_items_order_id` (`order_id`),
  ADD KEY `idx_order_items_product_id` (`product_id`);

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `order_items`
--
ALTER TABLE `order_items`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
  ADD CONSTRAINT `fk_orders_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `order_items`
--
ALTER TABLE `order_items`
  ADD CONSTRAINT `fk_order_items_order_id` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_order_items_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `order_items_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;) when show notification order,  make it clickable go to this order the page (view_order_customer.php
) so add codes in header.php and type full codes and make it working well