i have system managment kaak alia, i wnat to update, and Workspace, this workspace purpose to management our everyhing about team, like make plans and management posts and stories in instagram and other platoforms, in thsi workspace includes calaneder and datatime to post or what we will type on this post and how it looks and other features to add and we won't add api, this workspace to remember our plan and notes and everythings, and this info our 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 */;) and this header.php (<?php
// includes/header.php

// Use require_once to prevent multiple inclusions
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/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>
    
    <!-- Custom Styles for Notification Links -->
    <style>
        .notification-link {
            display: block;
            color: inherit;
            text-decoration: none;
        }
        .notification-link:hover {
            background-color: #4a5568; /* Tailwind's gray-700 */
        }
        .notification-badge {
            position: absolute;
            top: 0;
            right: 0;
            width: 0.75rem;
            height: 0.75rem;
            background-color: #f56565; /* Tailwind's red-500 */
            border-radius: 9999px;
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0%, 100% { transform: scale(0.75); opacity: 1; }
            50% { transform: scale(1.25); opacity: 0.5; }
        }
    </style>
</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 DISTINCT o.id, o.order_date, c.name AS customer_name
                                    FROM orders o
                                    JOIN customers c ON o.customer_id = c.id
                                    JOIN order_items oi ON oi.order_id = o.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">
                                            <a href="/public/orders/view_order_customer.php?order_id=<?= htmlspecialchars($notification['id'], ENT_QUOTES, 'UTF-8') ?>" class="notification-link flex items-center">
                                                <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'); ?> placed on <?= date("d M Y, h:i A", strtotime($notification['order_date'])) ?>
                                            </a>
                                        </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;
                                }

                                // Create a new notification item
                                const notificationsList = document.getElementById('notificationsList');
                                const li = document.createElement('li');
                                li.className = 'px-4 py-2 hover:bg-gray-700 cursor-pointer';
                                
                                // Create a link to the order details page
                                const a = document.createElement('a');
                                a.href = `/public/orders/view_order_customer.php?order_id=${encodeURIComponent(order.id)}`;
                                a.className = 'notification-link flex items-center';
                                a.innerHTML = `
                                    <span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
                                    New Order: ${sanitizeHTML(order.customer_name)} placed on ${sanitizeHTML(order.order_date)}
                                `;

                                li.appendChild(a);
                                // 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';
                                    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 i created folder in (this url /public/workspace) this folder will include all files and update databse sql, and this dasboard of kaak alia management (<?php
// public/dashboard.php

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

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

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

// Now include the header
require_once '../includes/header.php';

/**
 * Fetch Quick Stats
 */

// Total Orders
$totalOrdersSql = "SELECT COUNT(*) AS total FROM orders";
$totalOrdersResult = $conn->query($totalOrdersSql);
$totalOrders = ($totalOrdersResult && $row = $totalOrdersResult->fetch_assoc()) ? (int)$row['total'] : 0;

// Pending Orders
$pendingOrdersSql = "SELECT COUNT(*) AS total FROM orders WHERE status = 'Pending'";
$pendingOrdersResult = $conn->query($pendingOrdersSql);
$pendingOrders = ($pendingOrdersResult && $row = $pendingOrdersResult->fetch_assoc()) ? (int)$row['total'] : 0;

// Completed Orders
$completedOrdersSql = "SELECT COUNT(*) AS total FROM orders WHERE status = 'Completed'";
$completedOrdersResult = $conn->query($completedOrdersSql);
$completedOrders = ($completedOrdersResult && $row = $completedOrdersResult->fetch_assoc()) ? (int)$row['total'] : 0;

// Delivered Orders
$deliveredOrdersSql = "SELECT COUNT(*) AS total FROM orders WHERE status = 'Delivered'";
$deliveredOrdersResult = $conn->query($deliveredOrdersSql);
$deliveredOrders = ($deliveredOrdersResult && $row = $deliveredOrdersResult->fetch_assoc()) ? (int)$row['total'] : 0;

// Total Sales from Completed and Delivered Orders considering discounts
$totalSalesSql = "
    SELECT 
        SUM(p.price * oi.quantity * (1 - (oi.discount_percentage / 100))) AS total_sales
    FROM 
        order_items oi
    JOIN 
        products p ON oi.product_id = p.id
    JOIN 
        orders o ON oi.order_id = o.id
    WHERE 
        o.status IN ('Completed', 'Delivered')
";
$totalSalesResult = $conn->query($totalSalesSql);
$totalSales = ($totalSalesResult && $row = $totalSalesResult->fetch_assoc()) ? (float)$row['total_sales'] : 0.00;

/**
 * Fetch Recent Orders
 */

// Fetch the 5 most recent orders
$recentOrdersSql = "
    SELECT 
        o.id AS order_id,
        c.name AS customer_name,
        c.contact,
        c.delivery_address,
        o.status,
        o.order_date,
        o.delivery_datetime,
        GROUP_CONCAT(
            CONCAT(
                p.name, ' - ', p.size, ' (', FORMAT(p.price, 2), ' KD) <br>',
                'Qty: ', oi.quantity, '<br>',
                'Packaging: ', IFNULL(oi.packaging_preferences, 'None'), '<br>',
                'Discount: ', oi.discount_percentage, '%<br>',
                'Reason: ', IFNULL(oi.discount_reason, 'N/A')
            ) SEPARATOR '<hr>'
        ) AS products_details
    FROM 
        orders o
    JOIN 
        customers c ON o.customer_id = c.id
    JOIN 
        order_items oi ON o.id = oi.order_id
    JOIN 
        products p ON oi.product_id = p.id
    GROUP BY 
        o.id
    ORDER BY 
        o.order_date DESC
    LIMIT 5
";

$recentOrdersResult = $conn->query($recentOrdersSql);
$recentOrders = ($recentOrdersResult && $recentOrdersResult->num_rows > 0) ? $recentOrdersResult : false;

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard - 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="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">
    
    <!-- Embedded 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);
        }

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

        h2, 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: 20px;
        }

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

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

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

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

        /* ---------------------------------------------------
           5. Statistics Section
        ---------------------------------------------------- */
        .stats-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .stat-card {
            background-color: var(--white);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            padding: 15px;
            display: flex;
            align-items: center;
            transition: transform 0.2s;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-icon {
            font-size: 24px;
            margin-right: 10px;
        }

        .stat-icon.total-orders { color: var(--secondary-text); }
        .stat-icon.pending-orders { color: var(--button-add-order); }
        .stat-icon.completed-orders { color: var(--button-view-orders); }
        .stat-icon.delivered-orders { color: var(--button-generate-reports); }
        .stat-icon.total-sales { color: var(--button-manage-products); }

        .stat-info h5 {
            font-size: 16px;
            color: var(--main-text);
            margin-bottom: 5px;
        }

        .stat-info p {
            font-size: 20px;
            font-weight: bold;
            color: var(--main-text);
        }

        /* ---------------------------------------------------
           6. Main Buttons Section
        ---------------------------------------------------- */
        .buttons-section {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
        }

        .action-button {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            max-width: 200px;
            height: 60px;
            font-size: 18px;
            font-weight: bold;
            color: var(--white);
            border: none;
            border-radius: 8px;
            padding: 10px 20px;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            text-decoration: none;
            text-align: center;
        }

        .action-button.add-order { background-color: var(--button-add-order); }
        .action-button.view-orders { background-color: var(--button-view-orders); }
        .action-button.manage-products { background-color: var(--button-manage-products); }
        .action-button.manage-users { background-color: var(--button-manage-users); }
        .action-button.generate-reports { background-color: var(--button-generate-reports); }

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

        /* ---------------------------------------------------
           7. Recent Orders Section
        ---------------------------------------------------- */
        .recent-orders-section {
            background-color: var(--white);
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

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

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

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

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

        .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 .view-all {
            display: block;
            text-align: right;
            margin-top: 10px;
            font-size: 14px;
            color: #118AB2;
            font-weight: bold;
            text-decoration: none;
        }

        .recent-orders-section .view-all:hover {
            color: #075985;
        }

        /* Badge Styles */
        .badge-status-pending {
            background-color: #FFD166;
            color: var(--white);
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .badge-status-in-progress {
            background-color: #118AB2;
            color: var(--white);
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .badge-status-completed {
            background-color: #06D6A0;
            color: var(--white);
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .badge-status-delivered {
            background-color: #EF476F;
            color: var(--white);
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

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

        /* ---------------------------------------------------
           9. Responsive Design Enhancements
        ---------------------------------------------------- */
        @media (min-width: 768px) {
            .buttons-section .action-button {
                width: 48%;
            }
        }

        @media (max-width: 767px) {
            .buttons-section .action-button {
                width: 100%;
            }

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

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

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

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

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

            .action-button {
                font-size: 16px;
                height: 50px;
            }

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

            .recent-orders-section h4 {
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
<main class='container-body'>
    <!-- Header -->
    <div class="header">
        <h1>Kaak Alia Dashboard</h1>
    </div>

    <!-- Welcome Section -->
    <div class="welcome-section">
        <h3>Welcome to the Kaak Alia Management System!</h3>
        <hr>
    </div>

    <!-- Statistics Section -->
    <div class="stats-section">
        <!-- Total Orders -->
        <div class="stat-card">
            <div class="stat-icon total-orders">
                <i class="bi bi-cart-fill"></i>
            </div>
            <div class="stat-info">
                <h5>Total Orders</h5>
                <p><?= number_format($totalOrders) ?></p>
            </div>
        </div>
        <!-- Pending Orders -->
        <div class="stat-card">
            <div class="stat-icon pending-orders">
                <i class="bi bi-hourglass-top"></i>
            </div>
            <div class="stat-info">
                <h5>Pending Orders</h5>
                <p><?= number_format($pendingOrders) ?></p>
            </div>
        </div>
        <!-- Completed Orders -->
        <div class="stat-card">
            <div class="stat-icon completed-orders">
                <i class="bi bi-check-circle-fill"></i>
            </div>
            <div class="stat-info">
                <h5>Completed Orders</h5>
                <p><?= number_format($completedOrders) ?></p>
            </div>
        </div>
        <!-- Delivered Orders -->
        <div class="stat-card">
            <div class="stat-icon delivered-orders">
                <i class="bi bi-truck"></i>
            </div>
            <div class="stat-info">
                <h5>Delivered Orders</h5>
                <p><?= number_format($deliveredOrders) ?></p>
            </div>
        </div>
        <!-- Total Sales -->
        <div class="stat-card">
            <div class="stat-icon total-sales">
                <i class="bi bi-cash-stack"></i>
            </div>
            <div class="stat-info">
                <h5>Total Sales (KD)</h5>
                <p><?= number_format($totalSales, 2) ?></p>
            </div>
        </div>
    </div>

    <!-- Main Buttons Section -->
    <div class="buttons-section">
        <a href="orders/add_order.php" class="action-button add-order">
            <i class="bi bi-plus-circle-fill me-2"></i>
            Add New Order
        </a>
        <a href="orders/view_orders.php" class="action-button view-orders">
            <i class="bi bi-eye-fill me-2"></i>
            View Orders
        </a>
        <a href="products/manage_products.php" class="action-button manage-products">
            <i class="bi bi-box-seam-fill me-2"></i>
            Manage Products
        </a>
        <a href="users/manage_users.php" class="action-button manage-users">
            <i class="bi bi-people-fill me-2"></i>
            Manage Users
        </a>
        <a href="reports/generate_reports.php" class="action-button generate-reports">
            <i class="bi bi-bar-chart-fill me-2"></i>
            Generate Reports
        </a>
    </div>

    <!-- Recent Orders Section -->
    <div class="recent-orders-section">
        <h4>Recent Orders</h4>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>#ID</th>
                        <th>Customer Name</th>
                        <th>Contact</th>
                        <th>Delivery Address</th>
                        <th>Products</th>
                        <th>Status</th>
                        <th>Order Date</th>
                        <th>Delivery DateTime</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($recentOrders && $recentOrders->num_rows > 0): ?>
                        <?php while($order = $recentOrders->fetch_assoc()): ?>
                            <tr>
                                <td><?= htmlspecialchars($order['order_id']) ?></td>
                                <td><?= htmlspecialchars($order['customer_name']) ?></td>
                                <td><?= htmlspecialchars($order['contact']) ?></td>
                                <td><?= nl2br(htmlspecialchars($order['delivery_address'])) ?></td>
                                <td>
                                    <?php
                                        // Display all products associated with the order
                                        echo $order['products_details'];
                                    ?>
                                </td>
                                <td>
                                    <?php
                                        switch ($order['status']) {
                                            case 'Pending':
                                                echo '<span class="badge-status-pending">Pending</span>';
                                                break;
                                            case 'In Progress':
                                                echo '<span class="badge-status-in-progress">In Progress</span>';
                                                break;
                                            case 'Completed':
                                                echo '<span class="badge-status-completed">Completed</span>';
                                                break;
                                            case 'Delivered':
                                                echo '<span class="badge-status-delivered">Delivered</span>';
                                                break;
                                            default:
                                                echo '<span class="badge bg-light text-dark">Unknown</span>';
                                        }
                                    ?>
                                </td>
                                <td><?= htmlspecialchars(date("d M Y, h:i A", strtotime($order['order_date']))) ?></td>
                                <td><?= $order['delivery_datetime'] ? htmlspecialchars(date("d M Y, h:i A", strtotime($order['delivery_datetime']))) : 'N/A' ?></td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="text-center">No recent orders.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <a href="orders/view_orders.php" class="view-all">View All Orders</a>
    </div>

    <!-- Footer -->
    <div class="footer">
        &copy; 2024 Kaak Alia Bakery. All rights reserved.
    </div>
</main>
    <!-- Embedded Bootstrap JS -->
    <script src="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
?>) but i don't want to change this dabaosrd but it help you to create workspace well and i make the workspace  don't effect with other tables in databse, make it separete workspace but make it connect with users to manage and make plans with others, so type full codes with guides and make it cool workspace