in this codes (<?php
// public/orders/view_orders.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 and database connection **before** any output
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';

// Helper Functions

/**
 * Sanitize input to prevent XSS and other injections.
 *
 * @param string $input The input string to sanitize.
 * @return string The sanitized string.
 */
function sanitize_input($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Build a query string while preserving existing parameters.
 *
 * @param array $new_params Associative array of new parameters to add or update.
 * @return string The resulting query string.
 */
function build_query($new_params = []) {
    $current_params = $_GET;
    foreach ($new_params as $key => $value) {
        if ($value !== null) { // Only set if value is not null
            $current_params[$key] = $value;
        } else {
            unset($current_params[$key]); // Remove if value is null
        }
    }
    // Remove parameters that shouldn't persist
    unset($current_params['page']);
    $query = http_build_query($current_params);
    return $query ? '?' . $query : '';
}

/**
 * Get the appropriate sort icon based on current sorting.
 *
 * @param string $column The column to check.
 * @param string $current_sort_by The current column being sorted by.
 * @param string $current_sort_order The current sort order ('ASC' or 'DESC').
 * @return string The HTML for the sort icon.
 */
function get_sort_icon($column, $current_sort_by, $current_sort_order) {
    if ($current_sort_by === $column) {
        if ($current_sort_order === 'ASC') {
            return '<i class="bi bi-arrow-up sort-icon" aria-label="Ascending"></i>';
        } else {
            return '<i class="bi bi-arrow-down sort-icon" aria-label="Descending"></i>';
        }
    }
    return '';
}

/**
 * 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 Egypt country code (+20). Adjust as needed.
    if (substr($digits, 0, 2) !== '20') {
        $digits = '20' . $digits;
    }
    
    return "https://wa.me/" . $digits;
}

/**
 * Calculate totals for a given set of order items.
 *
 * @param array $order_items The array of order items.
 * @return array An associative array containing total_before_discounts, total_discounts, and final_total.
 */
function calculate_order_totals($order_items) {
    $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;

    return [
        'total_before_discounts' => $total_before_discounts,
        'total_discounts' => $total_discounts,
        'final_total' => $final_total
    ];
}

// Handle Actions Before Including Header

if (isset($_GET['action'])) {
    if ($_GET['action'] === 'update_status') {
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        $new_status = isset($_GET['new_status']) ? sanitize_input($_GET['new_status']) : '';

        // Validate new_status
        $valid_statuses = ['Pending', 'Completed', 'Delivered'];
        if ($order_id > 0 && in_array($new_status, $valid_statuses)) {
            // If setting to 'Delivered', ensure delivery_datetime is set
            if ($new_status === 'Delivered') {
                $check_sql = "SELECT delivery_datetime FROM orders WHERE id = ?";
                $check_stmt = $conn->prepare($check_sql);
                if ($check_stmt) {
                    $check_stmt->bind_param("i", $order_id);
                    $check_stmt->execute();
                    $check_result = $check_stmt->get_result();
                    if ($check_result->num_rows == 1) {
                        $order = $check_result->fetch_assoc();
                        if (empty($order['delivery_datetime'])) {
                            header("Location: view_orders.php?error=3"); // Delivery datetime not set
                            exit();
                        }
                    }
                    $check_stmt->close();
                } else {
                    header("Location: view_orders.php?error=2");
                    exit();
                }
            }

            // Update status using prepared statement
            $update_sql = "UPDATE orders SET status = ? WHERE id = ?";
            $stmt = $conn->prepare($update_sql);
            if ($stmt) {
                $stmt->bind_param("si", $new_status, $order_id);
                if ($stmt->execute()) {
                    $stmt->close();
                    header("Location: view_orders.php?success=1");
                    exit();
                } else {
                    $stmt->close();
                    header("Location: view_orders.php?error=1");
                    exit();
                }
            } else {
                header("Location: view_orders.php?error=2");
                exit();
            }
        } else {
            header("Location: view_orders.php?error=2");
            exit();
        }
    } elseif ($_GET['action'] === 'export') {
        // Implement export functionality here
        // For brevity, this is left as a placeholder
        // You can generate CSV or PDF based on current filters
        // Redirect back with success message
        header("Location: view_orders.php?export=1");
        exit();
    }
}

// Now include the header after handling actions
require_once __DIR__ . '/../../includes/header.php';

// Constants for pagination
define('ORDERS_PER_PAGE_DEFAULT', 10);

// Handle Filters, Sorting, and Pagination
$filter = isset($_GET['filter']) ? sanitize_input($_GET['filter']) : 'all';
$status_filter = isset($_GET['status_filter']) ? sanitize_input($_GET['status_filter']) : 'all';
$priority_filter = isset($_GET['priority_filter']) ? sanitize_input($_GET['priority_filter']) : 'all';
$search = isset($_GET['search']) ? sanitize_input($_GET['search']) : '';
$sort_by = isset($_GET['sort_by']) ? sanitize_input($_GET['sort_by']) : 'order_date';
$sort_order = isset($_GET['sort_order']) ? sanitize_input($_GET['sort_order']) : 'DESC';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$orders_per_page = isset($_GET['orders_per_page']) ? intval($_GET['orders_per_page']) : ORDERS_PER_PAGE_DEFAULT;

// Handle Date Range Filters
$from_date = isset($_GET['from_date']) ? sanitize_input($_GET['from_date']) : '';
$to_date = isset($_GET['to_date']) ? sanitize_input($_GET['to_date']) : '';

// Validate orders_per_page
$allowed_orders_per_page = [10, 20, 50];
if (!in_array($orders_per_page, $allowed_orders_per_page)) {
    $orders_per_page = ORDERS_PER_PAGE_DEFAULT;
}

// Validate sort_by and sort_order
$allowed_sort_columns = ['id', 'customer_name', 'contact', 'status', 'priority', 'order_date', 'delivery_datetime'];
if (!in_array($sort_by, $allowed_sort_columns)) {
    $sort_by = 'order_date';
}

$allowed_sort_orders = ['ASC', 'DESC'];
if (!in_array($sort_order, $allowed_sort_orders)) {
    $sort_order = 'DESC';
}

// Initialize where conditions
$where_conditions = [];
$parameters = [];
$param_types = "";

// Status Filter
if ($status_filter !== 'all') {
    $where_conditions[] = "o.status = ?";
    $parameters[] = $status_filter;
    $param_types .= "s";
}

// Priority Filter
if ($priority_filter !== 'all') {
    $where_conditions[] = "o.priority = ?";
    $parameters[] = $priority_filter;
    $param_types .= "s";
}

// Search Filter
if (!empty($search)) {
    $where_conditions[] = "(c.name LIKE ? OR o.id LIKE ? OR c.contact LIKE ?)";
    $search_term = "%" . $search . "%";
    $parameters[] = $search_term;
    $parameters[] = $search_term;
    $parameters[] = $search_term;
    $param_types .= "sss";
}

// Date Range Filter on order_date
if (!empty($from_date)) {
    $where_conditions[] = "o.order_date >= ?";
    $parameters[] = $from_date . " 00:00:00";
    $param_types .= "s";
}

if (!empty($to_date)) {
    $where_conditions[] = "o.order_date <= ?";
    $parameters[] = $to_date . " 23:59:59";
    $param_types .= "s";
}

// Combine all where conditions
$where_clause = "";
if (count($where_conditions) > 0) {
    $where_clause = "WHERE " . implode(" AND ", $where_conditions);
}

// Sorting
// To prevent SQL injection in ORDER BY, use a mapping
$sort_column_map = [
    'id' => 'o.id',
    'customer_name' => 'c.name',
    'contact' => 'c.contact',
    'status' => 'o.status',
    'priority' => 'o.priority',
    'order_date' => 'o.order_date',
    'delivery_datetime' => 'o.delivery_datetime'
];
$sort_column = isset($sort_column_map[$sort_by]) ? $sort_column_map[$sort_by] : 'o.order_date';
$order_clause = "ORDER BY $sort_column $sort_order";

// Pagination Calculations
$offset = ($page - 1) * $orders_per_page;

// Fetch total number of orders for pagination
$count_sql = "
    SELECT COUNT(DISTINCT o.id) as total 
    FROM orders o
    JOIN customers c ON o.customer_id = c.id
    $where_clause
";
$count_stmt = $conn->prepare($count_sql);
if ($count_stmt) {
    if (!empty($where_clause)) {
        $count_stmt->bind_param($param_types, ...$parameters);
    }
    $count_stmt->execute();
    $count_result = $count_stmt->get_result();
    $total_orders = $count_result->fetch_assoc()['total'];
    $count_stmt->close();
} else {
    // Handle SQL preparation error
    die("Failed to prepare the count query: " . $conn->error);
}

// Calculate total pages
$total_pages = ceil($total_orders / $orders_per_page);

// Fetch orders with customer details based on filters and sorting
$orders_sql = "
    SELECT 
        o.id AS order_id,
        o.status,
        o.priority,
        o.order_date,
        o.delivery_datetime,
        c.name AS customer_name,
        c.contact,
        c.delivery_address
    FROM 
        orders o
    JOIN 
        customers c ON o.customer_id = c.id
    $where_clause
    $order_clause
    LIMIT ?, ?
";
$orders_stmt = $conn->prepare($orders_sql);
if ($orders_stmt) {
    // Bind parameters
    if (!empty($where_clause)) {
        // 'ii' for offset and limit
        $types = $param_types . "ii";
        $values = array_merge($parameters, [$offset, $orders_per_page]);
        $orders_stmt->bind_param($types, ...$values);
    } else {
        $orders_stmt->bind_param("ii", $offset, $orders_per_page);
    }
    $orders_stmt->execute();
    $orders_result = $orders_stmt->get_result();
} else {
    // Handle SQL preparation error
    die("Failed to prepare the orders query: " . $conn->error);
}

// Fetch order items for all orders
$order_ids = [];
if ($orders_result && $orders_result->num_rows > 0) {
    while ($order = $orders_result->fetch_assoc()) {
        $order_ids[] = $order['order_id'];
    }
    // Reset result pointer
    $orders_result->data_seek(0);
}

$order_items = [];
if (!empty($order_ids)) {
    $placeholders = implode(',', array_fill(0, count($order_ids), '?'));
    $types = str_repeat('i', count($order_ids));
    $order_items_sql = "
        SELECT 
            oi.order_id,
            oi.product_id,
            oi.quantity,
            oi.packaging_preferences,
            oi.discount_percentage,
            oi.discount_reason,
            p.name AS product_name,
            p.size AS product_size,
            p.price AS product_price
        FROM 
            order_items oi
        JOIN 
            products p ON oi.product_id = p.id
        WHERE
            oi.order_id IN ($placeholders)
    ";
    $items_stmt = $conn->prepare($order_items_sql);
    if ($items_stmt) {
        $items_stmt->bind_param($types, ...$order_ids);
        $items_stmt->execute();
        $order_items_result = $items_stmt->get_result();
        while ($item = $order_items_result->fetch_assoc()) {
            $order_items[$item['order_id']][] = $item;
        }
        $items_stmt->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Orders - Kaak Alia Management System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&family=Lora:wght@400;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">
    
    <!-- Flatpickr CSS for Date Picker -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <!-- Custom Styles -->
    <style>
        /* ---------------------------------------------------
           1. CSS Variables for Consistent Design
        ---------------------------------------------------- */
        :root {
            --light-brown: #E8D8C3; /* Input Field Border */
            --warm-accent: #374151; /* Updated Accent Color */
            --cream: #F9F4EC; /* Containers and Boxes Background */
            --dark-brown: #3A2F1B; /* Titles and Main Text */
            --mid-gray: #555555; /* Input Text */
            --placeholder-gray: #AAAAAA; /* Placeholder Text */
            --border-radius: 10px; /* Consistent Border Radius */
            --shadow-light: 0px 2px 4px rgba(0,0,0,0.1); /* Soft Shadow */
            --shadow-deep: 0px 4px 8px rgba(0,0,0,0.2); /* Deeper Shadow for Boxes */
            --button-hover: #c76c39; /* Button Hover Color */
            
            --header-bg: #F5F5F5; /* Header Background */
            --footer-bg: #F5F5F5; /* Footer Background */
            --text-color: var(--dark-brown);
            --title-color: var(--dark-brown);
            --badge-pending: #FFD166;
            --badge-completed: #06D6A0;
            --badge-delivered: #EF476F;
        }

        /* ---------------------------------------------------
           2. Global Styles
        ---------------------------------------------------- */
        body, html {
            margin: 0;
            padding: 0;
            font-family: 'Nunito', sans-serif;
            background-color: #FFFFFF;
            color: var(--text-color);
        }

        .container-body {
            padding: 30px;
            box-sizing: border-box;
            background-color: #FFFFFF;
        }

        /* ---------------------------------------------------
           3. Header Styles
        ---------------------------------------------------- */
        .header {
            padding: 20px 30px;
            background-color: var(--header-bg);
            border-bottom: 1px solid var(--light-brown);
            text-align: center;
            margin-bottom: 30px;
            color: var(--dark-brown);
            font-size: 28px;
            font-weight: 700;
            font-family: 'Lora', serif;
            box-shadow: var(--shadow-light);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        /* ---------------------------------------------------
           4. Success and Error Alerts
        ---------------------------------------------------- */
        .alert-success-custom {
            background-color: var(--badge-completed);
            color: #FFFFFF;
            border-radius: var(--border-radius);
            padding: 15px 20px;
            margin-bottom: 20px;
            text-align: center;
            width: 70%;
            margin: 20px auto;
            box-shadow: var(--shadow-deep);
            animation: fadeIn 0.5s ease-in-out;
            font-family: 'Nunito', sans-serif;
            font-size: 16px;
        }

        .alert-error-custom {
            background-color: var(--badge-delivered);
            color: #FFFFFF;
            border-radius: var(--border-radius);
            padding: 15px 20px;
            margin-bottom: 20px;
            text-align: center;
            width: 70%;
            margin: 20px auto;
            box-shadow: var(--shadow-deep);
            animation: fadeIn 0.5s ease-in-out;
            font-family: 'Nunito', sans-serif;
            font-size: 16px;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        /* ---------------------------------------------------
           5. Recent Orders Section
        ---------------------------------------------------- */
        .recent-orders-section {
            background-color: var(--cream);
            border-radius: var(--border-radius);
            padding: 30px;
            box-shadow: var(--shadow-deep);
            max-width: 1200px;
            margin: 0 auto;
            font-family: 'Nunito', sans-serif;
        }

        .recent-orders-section h4 {
            font-size: 28px;
            font-weight: 700;
            color: var(--title-color);
            margin-bottom: 25px;
            border-bottom: 3px solid var(--warm-accent);
            padding-bottom: 10px;
            font-family: 'Lora', serif;
        }

        /* ---------------------------------------------------
           6. Filter and Search Section
        ---------------------------------------------------- */
        .filter-search-section {
            margin-bottom: 25px;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
            gap: 15px;
        }

        .filter-search-section > div {
            display: flex;
            align-items: center;
        }

        /* Enhanced Styles for Search Input */
        .filter-search-section .search-group input {
            margin-left: 5px;
            width: 250px;
            padding: 12px;
            border-radius: var(--border-radius);
            border: 1px solid var(--light-brown);
            box-shadow: var(--shadow-light);
            font-size: 16px;
            color: var(--mid-gray);
            font-family: 'Nunito', sans-serif;
            transition: border-color 0.3s, box-shadow 0.3s;
        }

        .filter-search-section .search-group input:focus {
            border-color: var(--warm-accent);
            box-shadow: 0px 2px 4px var(--shadow-light), 0px 0px 8px var(--warm-accent);
            outline: none;
        }

        /* Enhanced Styles for Search Button */
        .filter-search-section .search-group button {
            background-color: var(--warm-accent);
            color: #FFFFFF;
            border: none;
            padding: 12px 20px;
            border-radius: var(--border-radius);
            margin-left: 10px;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.3s;
            display: flex;
            align-items: center;
            font-size: 16px;
            font-family: 'Nunito', sans-serif;
        }

        .filter-search-section .search-group button:hover {
            background-color: var(--button-hover);
            transform: scale(1.05);
        }

        /* Status Filter Dropdown */
        .filter-search-section .status-filter-group label {
            margin-right: 10px;
            font-weight: 600;
            font-family: 'Nunito', sans-serif;
        }

        .filter-search-section .status-filter-group select {
            padding: 12px;
            border-radius: var(--border-radius);
            border: 1px solid var(--light-brown);
            box-shadow: var(--shadow-light);
            transition: border-color 0.3s, box-shadow 0.3s;
            width: 180px;
            font-size: 16px;
            color: var(--mid-gray);
            font-family: 'Nunito', sans-serif;
            background-color: #FFFFFF;
        }

        .filter-search-section .status-filter-group select:focus {
            border-color: var(--warm-accent);
            box-shadow: 0px 2px 4px var(--shadow-light), 0px 0px 8px var(--warm-accent);
            outline: none;
        }

        /* Priority Filter Dropdown */
        .filter-search-section .priority-filter-group label {
            margin-right: 10px;
            font-weight: 600;
            font-family: 'Nunito', sans-serif;
        }

        .filter-search-section .priority-filter-group select {
            padding: 12px;
            border-radius: var(--border-radius);
            border: 1px solid var(--light-brown);
            box-shadow: var(--shadow-light);
            transition: border-color 0.3s, box-shadow 0.3s;
            width: 180px;
            font-size: 16px;
            color: var(--mid-gray);
            font-family: 'Nunito', sans-serif;
            background-color: #FFFFFF;
        }

        .filter-search-section .priority-filter-group select:focus {
            border-color: var(--warm-accent);
            box-shadow: 0px 2px 4px var(--shadow-light), 0px 0px 8px var(--warm-accent);
            outline: none;
        }

        /* Entries Per Page Dropdown */
        .filter-search-section .entries-per-page-group label {
            margin-right: 10px;
            font-weight: 600;
            font-family: 'Nunito', sans-serif;
        }

        .filter-search-section .entries-per-page-group select {
            padding: 12px;
            border-radius: var(--border-radius);
            border: 1px solid var(--light-brown);
            box-shadow: var(--shadow-light);
            transition: border-color 0.3s, box-shadow 0.3s;
            width: 120px;
            font-size: 16px;
            color: var(--mid-gray);
            font-family: 'Nunito', sans-serif;
            background-color: #FFFFFF;
        }

        .filter-search-section .entries-per-page-group select:focus {
            border-color: var(--warm-accent);
            box-shadow: 0px 2px 4px var(--shadow-light), 0px 0px 8px var(--warm-accent);
            outline: none;
        }

        /* Date Filter Dropdown */
        .filter-search-section .date-filter-group label {
            margin-right: 10px;
            font-weight: 600;
            font-family: 'Nunito', sans-serif;
        }

        .filter-search-section .date-filter-group input {
            padding: 12px;
            border-radius: var(--border-radius);
            border: 1px solid var(--light-brown);
            box-shadow: var(--shadow-light);
            transition: border-color 0.3s, box-shadow 0.3s;
            width: 180px;
            font-size: 16px;
            color: var(--mid-gray);
            font-family: 'Nunito', sans-serif;
            background-color: #FFFFFF;
        }

        .filter-search-section .date-filter-group input:focus {
            border-color: var(--warm-accent);
            box-shadow: 0px 2px 4px var(--shadow-light), 0px 0px 8px var(--warm-accent);
            outline: none;
        }

        .filter-search-section .date-filter-group button {
            background-color: var(--warm-accent);
            color: #FFFFFF;
            border: none;
            padding: 12px 20px;
            border-radius: var(--border-radius);
            margin-left: 10px;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.3s;
            font-size: 16px;
            font-family: 'Nunito', sans-serif;
            display: flex;
            align-items: center;
        }

        .filter-search-section .date-filter-group button:hover {
            background-color: var(--button-hover);
            transform: scale(1.05);
        }

        /* ---------------------------------------------------
           7. Orders Table Styles
        ---------------------------------------------------- */
        .orders-table {
            width: 100%;
            border-collapse: collapse;
            border: 2px solid var(--light-brown);
            font-size: 16px;
            font-family: 'Nunito', sans-serif;
        }

        .orders-table th, 
        .orders-table td {
            padding: 15px;
            text-align: left;
            font-size: 16px;
            vertical-align: middle;
            border: 1px solid var(--light-brown);
        }

        .orders-table th {
            background-color: var(--warm-accent);
            color: #FFFFFF;
            font-weight: 700;
            cursor: pointer;
            position: relative;
            user-select: none;
            transition: background-color 0.3s, color 0.3s;
            border-radius: var(--border-radius);
        }

        .orders-table th:hover {
            background-color: var(--button-hover);
            color: #FFFFFF;
        }

        .orders-table th .sort-icon {
            margin-left: 5px;
            font-size: 16px;
        }

        .orders-table tbody tr:nth-child(even) {
            background-color: #FAF3EB;
        }

        .orders-table tbody tr:hover {
            background-color: #FFF0E6;
            transition: background-color 0.3s;
        }

        .orders-table td {
            font-size: 16px;
            color: black;
            position: relative;
        }

        /* Center-align numeric columns */
        .orders-table td.number,
        .orders-table td.price,
        .orders-table td.quantity,
        .orders-table td.discount_percentage,
        .orders-table td.discount_amount,
        .orders-table td.total_after_discount {
            text-align: center;
            font-weight: bold;
        }

        /* Badge Styles with Icons */
        .badge-status-pending {
            background-color: var(--badge-pending);
            color: #FFFFFF;
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
        }

        .badge-status-completed {
            background-color: var(--badge-completed);
            color: #FFFFFF;
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
        }

        .badge-status-delivered {
            background-color: var(--badge-delivered);
            color: #FFFFFF;
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
        }

        /* Highlight New Order IDs */
        .new-order {
            color: var(--warm-accent);
            font-weight: bold;
        }

        /* ---------------------------------------------------
           8. Action Buttons Styles
        ---------------------------------------------------- */
        .action-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .action-buttons .btn {
            padding: 10px 20px;
            font-size: 16px;
            border-radius: var(--border-radius);
            transition: transform 0.3s, background-color 0.3s;
            font-family: 'Nunito', sans-serif;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .action-buttons .btn-edit {
            background-color: #3B82F6; /* Blue */
            color: #FFFFFF;
            border: none;
        }

        .action-buttons .btn-edit:hover {
            background-color: #2563EB;
            transform: scale(1.05);
        }

        .action-buttons .btn-change-status {
            background-color: #F59E0B; /* Amber */
            color: #FFFFFF;
            border: none;
        }

        .action-buttons .btn-change-status:hover {
            background-color: #D97706;
            transform: scale(1.05);
        }

        .action-buttons .btn-delete {
            background-color: #EF4444; /* Red */
            color: #FFFFFF;
            border: none;
        }

        .action-buttons .btn-delete:hover {
            background-color: #DC2626;
            transform: scale(1.05);
        }

        .action-buttons .btn-view {
            background-color: #10B981; /* Green */
            color: #FFFFFF;
            border: none;
        }

        .action-buttons .btn-view:hover {
            background-color: #059669;
            transform: scale(1.05);
        }

        /* ---------------------------------------------------
           9. Pagination Styles
        ---------------------------------------------------- */
        .pagination .page-link {
            border-radius: 50%;
            width: 40px;
            height: 40px;
            line-height: 38px;
            text-align: center;
            font-size: 16px;
            color: var(--warm-accent);
            border: 1px solid var(--warm-accent);
            transition: background-color 0.3s, color 0.3s;
        }

        .pagination .page-item.active .page-link {
            background-color: var(--warm-accent);
            color: #FFFFFF;
            border-color: var(--warm-accent);
        }

        .pagination .page-link:hover {
            background-color: var(--warm-accent);
            color: #FFFFFF;
        }

        .pagination .page-item.disabled .page-link {
            color: #6c757d;
            background-color: transparent;
            border-color: #dee2e6;
            cursor: not-allowed;
        }

        /* ---------------------------------------------------
           10. Action Modal Styles
        ---------------------------------------------------- */
        /* Adjust modal size if needed */
        .modal-dialog {
            max-width: 500px;
        }

        .modal-content {
            border: 2px solid var(--warm-accent); /* Solid Border */
            border-radius: var(--border-radius);
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }

        .modal-header {
            background-color: var(--warm-accent);
            border-bottom: none;
            border-top-left-radius: var(--border-radius);
            border-top-right-radius: var(--border-radius);
            color: #FFFFFF;
        }

        .modal-title {
            font-size: 1.5rem;
            font-weight: 700;
            font-family: 'Lora', serif;
        }

        .modal-body {
            font-size: 1rem;
            color: var(--dark-brown);
            font-family: 'Nunito', sans-serif;
        }

        .modal-footer {
            background-color: #F3F4F6;
            border-top: none;
            border-bottom-left-radius: var(--border-radius);
            border-bottom-right-radius: var(--border-radius);
        }

        .modal-footer .btn-secondary {
            background-color: #6B7280; /* Gray */
            border: none;
            color: #FFFFFF;
        }

        .modal-footer .btn-danger {
            background-color: #EF4444;
            border: none;
            color: #FFFFFF;
        }

        .modal-footer .btn-secondary:hover {
            background-color: #4B5563;
        }

        .modal-footer .btn-danger:hover {
            background-color: #DC2626;
        }

        /* ---------------------------------------------------
           11. Change Status Controls Styles
        ---------------------------------------------------- */
        .change-status-controls {
            display: none;
            flex-direction: column;
            gap: 10px;
            margin-top: 10px;
        }

        .change-status-controls.active {
            display: flex;
        }

        .change-status-controls .form-select {
            width: 100%;
            padding: 12px;
            border-radius: var(--border-radius);
            border: 1px solid var(--light-brown);
            transition: border-color 0.3s, box-shadow 0.3s;
            font-size: 16px;
            color: var(--mid-gray);
            font-family: 'Nunito', sans-serif;
            background-color: #FFFFFF;
        }

        .change-status-controls .form-select:focus {
            border-color: var(--warm-accent);
            box-shadow: 0px 2px 4px var(--shadow-light), 0px 0px 8px var(--warm-accent);
            outline: none;
        }

        .change-status-controls .action-buttons-inline {
            display: flex;
            gap: 10px;
        }

        .change-status-controls .action-buttons-inline .btn {
            flex: 1;
        }

        /* ---------------------------------------------------
           12. Discount Styles
        ---------------------------------------------------- */
        .discount-info {
            margin-top: 5px;
            font-size: 14px;
            color: #EF476F;
            font-family: 'Nunito', sans-serif;
        }

        /* ---------------------------------------------------
           13. Responsive Design Enhancements
        ---------------------------------------------------- */
        @media (max-width: 992px) {
            .filter-search-section {
                flex-direction: column;
                align-items: flex-start;
            }

            .filter-search-section > div {
                width: 100%;
                justify-content: space-between;
                margin-bottom: 10px;
            }

            .orders-table th, .orders-table td {
                font-size: 16px;
            }
        }

        @media (max-width: 768px) {
            /* Adjust filter and search input widths */
            .filter-search-section .search-group input,
            .filter-search-section .status-filter-group select,
            .filter-search-section .priority-filter-group select,
            .filter-search-section .entries-per-page-group select,
            .filter-search-section .date-filter-group input {
                width: 100%;
                margin: 5px 0;
            }

            .filter-search-section .search-group button,
            .filter-search-section .date-filter-group button {
                width: 100%;
                margin-top: 10px;
            }

            .orders-table {
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }

            .orders-table th, .orders-table td {
                padding: 10px;
                font-size: 14px;
            }

            .action-buttons .btn-edit,
            .action-buttons .btn-change-status,
            .action-buttons .btn-delete,
            .action-buttons .btn-view {
                font-size: 14px;
                padding: 8px 16px;
            }
        }

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

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

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

            .filter-search-section .search-group input,
            .filter-search-section .status-filter-group select,
            .filter-search-section .priority-filter-group select,
            .filter-search-section .entries-per-page-group select,
            .filter-search-section .date-filter-group input {
                width: 100%;
                margin: 5px 0;
            }

            .filter-search-section .search-group button,
            .filter-search-section .date-filter-group button {
                width: 100%;
                margin-top: 10px;
            }

            .orders-table th, .orders-table td {
                padding: 8px;
                font-size: 14px;
            }

            .action-buttons .btn-edit,
            .action-buttons .btn-change-status,
            .action-buttons .btn-delete,
            .action-buttons .btn-view {
                font-size: 12px;
                padding: 6px 12px;
            }
        }

        /* Additional Styles for Modal Animation */
        .modal.fade .modal-dialog {
            transition: transform 0.3s ease-in-out;
            transform: translateY(-50px);
        }

        .modal.show .modal-dialog {
            transform: translateY(0);
        }

        /* ---------------------------------------------------
           14. Footer Styles
        ---------------------------------------------------- */
        .footer {
            padding: 20px;
            background-color: var(--footer-bg);
            text-align: center;
            color: var(--dark-brown);
            font-family: 'Nunito', sans-serif;
            font-size: 14px;
            margin-top: 30px;
            border-top: 1px solid var(--light-brown);
            box-shadow: var(--shadow-light);
            border-radius: var(--border-radius);
        }
    </style>

    <!-- Additional JavaScript for Print Functionality -->
    <script>
        function printOrders() {
            window.print();
        }

        function exportOrders() {
            window.location.href = 'view_orders.php?action=export';
        }

        // Prevent modal from showing on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Removed modal initialization as it's no longer used
        });
    </script>
</head>
<body>
<main class='container-body'>
    <!-- Header Already Included via header.php -->

    <!-- Display Success or Error Messages -->
    <?php if (isset($_GET['success'])): ?>
        <?php if ($_GET['success'] == 1): ?>
            <div class="alert-success-custom" role="alert">
                Order status updated successfully!
            </div>
        <?php elseif ($_GET['success'] == 2): ?>
            <div class="alert-success-custom" role="alert">
                Order deleted successfully!
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <?php if (isset($_GET['error'])): ?>
        <?php if ($_GET['error'] == 1): ?>
            <div class="alert-error-custom" role="alert">
                Failed to update order status.
            </div>
        <?php elseif ($_GET['error'] == 2): ?>
            <div class="alert-error-custom" role="alert">
                Invalid status selected.
            </div>
        <?php elseif ($_GET['error'] == 3): ?>
            <div class="alert-error-custom" role="alert">
                Cannot set status to Delivered without a delivery date and time.
            </div>
        <?php elseif ($_GET['error'] == 4): ?>
            <div class="alert-error-custom" role="alert">
                Failed to delete the order. Please try again.
            </div>
        <?php elseif ($_GET['error'] == 5): ?>
            <div class="alert-error-custom" role="alert">
                Invalid order ID provided.
            </div>
        <?php endif; ?>
    <?php endif; ?>


    <!-- Container -->
    <div class="recent-orders-section">
        <h4>All Orders</h4>

        <!-- Filter and Search Section -->
        <div class="filter-search-section">
            <!-- Status Filter Dropdown -->
            <div class="status-filter-group">
                <label for="statusFilter"><i class="bi bi-filter-circle"></i> Status:</label>
                <select id="statusFilter" onchange="applyFilters()">
                    <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All</option>
                    <option value="Pending" <?php echo $status_filter === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="Completed" <?php echo $status_filter === 'Completed' ? 'selected' : ''; ?>>Completed</option>
                    <option value="Delivered" <?php echo $status_filter === 'Delivered' ? 'selected' : ''; ?>>Delivered</option>
                </select>
            </div>

            <!-- Priority Filter Dropdown -->
            <div class="priority-filter-group">
                <label for="priorityFilter"><i class="bi bi-filter-circle"></i> Priority:</label>
                <select id="priorityFilter" onchange="applyFilters()">
                    <option value="all" <?php echo $priority_filter === 'all' ? 'selected' : ''; ?>>All</option>
                    <option value="Quick" <?php echo $priority_filter === 'Quick' ? 'selected' : ''; ?>>Quick</option>
                    <option value="Important" <?php echo $priority_filter === 'Important' ? 'selected' : ''; ?>>Important</option>
                    <option value="Default" <?php echo $priority_filter === 'Default' ? 'selected' : ''; ?>>Default</option>
                </select>
            </div>

            <!-- Search Group -->
            <div class="search-group">
                <form method="GET" action="view_orders.php" class="d-flex align-items-center flex-wrap">
                    <input type="hidden" name="filter" value="<?php echo sanitize_input($filter); ?>">
                    <input type="hidden" name="status_filter" value="<?php echo sanitize_input($status_filter); ?>">
                    <input type="hidden" name="priority_filter" value="<?php echo sanitize_input($priority_filter); ?>">
                    <input type="hidden" name="from_date" value="<?php echo sanitize_input($from_date); ?>">
                    <input type="hidden" name="to_date" value="<?php echo sanitize_input($to_date); ?>">
                    <input type="hidden" name="sort_by" value="<?php echo sanitize_input($sort_by); ?>">
                    <input type="hidden" name="sort_order" value="<?php echo sanitize_input($sort_order); ?>">
                    <input type="text" name="search" class="form-control me-2 mb-2" placeholder="🔍 Search by Customer, ID, or Contact" value="<?php echo sanitize_input($search); ?>">
                    <button type="submit" class="btn btn-primary mb-2"><i class="bi bi-search"></i> Search</button>
                    <?php if (!empty($search)): ?>
                        <a href="view_orders.php<?php echo build_query(['search' => null, 'page' => 1]); ?>" class="btn btn-outline-secondary ms-2 mb-2 btn-reset"><i class="bi bi-x-circle"></i> Reset</a>
                    <?php endif; ?>
                </form>
            </div>

            <!-- Date Range Filter -->
            <div class="date-filter-group">
                <label for="fromDate"><i class="bi bi-calendar-check-fill"></i> From:</label>
                <input type="text" id="fromDate" name="from_date" class="form-control me-2 mb-2" placeholder="YYYY-MM-DD" value="<?php echo sanitize_input($from_date); ?>">
                
                <label for="toDate"><i class="bi bi-calendar-check-fill"></i> To:</label>
                <input type="text" id="toDate" name="to_date" class="form-control me-2 mb-2" placeholder="YYYY-MM-DD" value="<?php echo sanitize_input($to_date); ?>">
                
                <button class="btn btn-secondary mb-2" onclick="applyDateFilters()"><i class="bi bi-calendar-fill"></i> Apply</button>
            </div>

            <!-- Entries Per Page Dropdown -->
            <div class="entries-per-page-group">
                <label for="entriesPerPage"><i class="bi bi-layout-split"></i> Show:</label>
                <select id="entriesPerPage" onchange="applyFilters()">
                    <option value="10" <?php echo $orders_per_page == 10 ? 'selected' : ''; ?>>10</option>
                    <option value="20" <?php echo $orders_per_page == 20 ? 'selected' : ''; ?>>20</option>
                    <option value="50" <?php echo $orders_per_page == 50 ? 'selected' : ''; ?>>50</option>
                </select>
                <span class="ms-2">entries</span>
            </div>
        </div>

        <!-- Pagination Information -->
        <div class="pagination-info mb-3">
            <?php
                if ($total_orders == 0) {
                    $start_order = 0;
                    $end_order = 0;
                } else {
                    $start_order = ($page - 1) * $orders_per_page + 1;
                    $end_order = min($page * $orders_per_page, $total_orders);
                }
                echo "Showing <strong>$start_order</strong> to <strong>$end_order</strong> of <strong>$total_orders</strong> orders";
            ?>
        </div>

        <!-- Orders Table -->
        <div class="table-responsive">
            <table class="table table-hover orders-table">
                <thead>
                    <tr>
                        <th onclick="sortTable('id')">
                            ID
                            <?php echo get_sort_icon('id', $sort_by, $sort_order); ?>
                        </th>
                        <th onclick="sortTable('customer_name')">
                            Customer
                            <?php echo get_sort_icon('customer_name', $sort_by, $sort_order); ?>
                        </th>
                        <th>
                            Contact
                        </th>
                        <th>
                            Delivery Address
                        </th>
                        <th>
                            Products
                        </th>
                        <th onclick="sortTable('status')">
                            Status
                            <?php echo get_sort_icon('status', $sort_by, $sort_order); ?>
                        </th>
                        <th onclick="sortTable('priority')">
                            Priority
                            <?php echo get_sort_icon('priority', $sort_by, $sort_order); ?>
                        </th>
                        <th onclick="sortTable('order_date')">
                            Order Date
                            <?php echo get_sort_icon('order_date', $sort_by, $sort_order); ?>
                        </th>
                        <th onclick="sortTable('delivery_datetime')">
                            Delivery DateTime
                            <?php echo get_sort_icon('delivery_datetime', $sort_by, $sort_order); ?>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($orders_result && $orders_result->num_rows > 0): ?>
                        <?php while($order = $orders_result->fetch_assoc()): ?>
                            <?php
                                // Check if the order is new (created within last 24 hours)
                                $is_new = (strtotime($order['order_date']) >= strtotime('-1 day'));
                                // Generate WhatsApp link
                                $whatsapp_link = generate_whatsapp_link($order['contact']);

                                // Determine badge class based on status
                                switch ($order['status']) {
                                    case 'Pending':
                                        $badge_class = 'badge-status-pending';
                                        $icon = 'hourglass-split';
                                        break;
                                    case 'Completed':
                                        $badge_class = 'badge-status-completed';
                                        $icon = 'check-circle-fill';
                                        break;
                                    case 'Delivered':
                                        $badge_class = 'badge-status-delivered';
                                        $icon = 'box-seam';
                                        break;
                                    default:
                                        $badge_class = 'badge bg-light text-dark';
                                        $icon = 'info-circle';
                                }

                                // Fetch order items
                                $items = isset($order_items[$order['order_id']]) ? $order_items[$order['order_id']] : [];

                                // Calculate order totals
                                $totals = calculate_order_totals($items);
                            ?>
                            <!-- Main Row -->
                            <tr>
                                <td class="<?php echo $is_new ? 'new-order' : ''; ?>" data-bs-toggle="collapse" data-bs-target="#orderDetails<?= htmlspecialchars($order['order_id']) ?>" aria-expanded="false" aria-controls="orderDetails<?= htmlspecialchars($order['order_id']) ?>">
                                    <?= htmlspecialchars($order['order_id']) ?>
                                    <?php if ($is_new): ?>
                                        <span class="badge-status-pending ms-1"><i class="bi bi-star-fill"></i> New</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?= htmlspecialchars($order['customer_name']) ?>
                                </td>
                                <td>
                                    <a href="<?= $whatsapp_link ?>" target="_blank" class="text-decoration-none">
                                        <i class="bi bi-whatsapp" style="color: #25D366;"></i> <?= htmlspecialchars($order['contact']) ?>
                                    </a>
                                </td>
                                <td><?= nl2br(htmlspecialchars($order['delivery_address'])) ?></td>
                                <td>
                                    <?php if (!empty($items)): ?>
                                        <?php foreach ($items as $item): ?>
                                            <div class="mb-2">
                                                <strong><?= htmlspecialchars($item['product_name']) ?></strong><br>
                                                Size: <?= htmlspecialchars($item['product_size']) ?><br>
                                                Price: <?= number_format($item['product_price'], 2) ?> KD<br>
                                                Qty: <?= htmlspecialchars($item['quantity']) ?><br>
                                                Packaging: <?= htmlspecialchars($item['packaging_preferences']) ?><br>
                                                <?php if (floatval($item['discount_percentage']) > 0): ?>
                                                    <div class="discount-info">
                                                        <i class="bi bi-tags-fill"></i> Discount: <?= htmlspecialchars($item['discount_percentage']) ?>%<br>
                                                        <small>Reason: <?= htmlspecialchars($item['discount_reason']) ?></small>
                                                    </div>
                                                <?php endif; ?>
                                                <?php
                                                    $total = ($item['product_price'] * $item['quantity']);
                                                    if ($item['discount_percentage'] > 0) {
                                                        $total -= ($total * ($item['discount_percentage'] / 100));
                                                    }
                                                    $total = $total < 0 ? 0 : $total;
                                                ?>
                                                <strong>Total: <?= number_format($total, 2) ?> KD</strong>
                                            </div>
                                            <hr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <span class='text-muted'>No products found.</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="<?= $badge_class ?>"><i class="bi bi-<?= $icon ?>"></i> <?= htmlspecialchars($order['status']) ?></span>
                                </td>
                                <td>
                                    <?= htmlspecialchars($order['priority']) ?>
                                </td>
                                <td><?= date("d M Y, h:i A", strtotime($order['order_date'])) ?></td>
                                <td><?= $order['delivery_datetime'] ? date("d M Y, h:i A", strtotime($order['delivery_datetime'])) : 'N/A' ?></td>
                            </tr>

                            <!-- Action Row -->
                            <tr class="collapse" id="orderDetails<?= htmlspecialchars($order['order_id']) ?>">
                                <td colspan="9">
                                    <div class="action-buttons">
                                        <!-- Edit Order -->
                                        <button class="btn btn-edit" onclick="editOrder(<?= htmlspecialchars($order['order_id']) ?>)" title="Edit Order" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Edit Order">
                                            <i class="bi bi-pencil-fill"></i> Edit
                                        </button>
                                        
                                        <!-- Change Status -->
                                        <button class="btn btn-change-status" onclick="toggleChangeStatus(<?= htmlspecialchars($order['order_id']) ?>)" title="Change Status" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Change Status">
                                            <i class="bi bi-arrow-repeat"></i> Change Status
                                        </button>
                                        
                                        <!-- Delete Order -->
                                        <button class="btn btn-delete" onclick="confirmDelete(<?= htmlspecialchars($order['order_id']) ?>)" title="Delete Order" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Delete Order">
                                            <i class="bi bi-trash-fill"></i> Delete
                                        </button>
                                            
                                        <!-- View Customer Order -->
                                        <a href="view_order_customer.php?order_id=<?= htmlspecialchars($order['order_id']) ?>" class="btn btn-view" title="View Customer Order" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="View Customer Order">
                                            <i class="bi bi-eye-fill"></i> View
                                        </a>
                                    </div>
                                    
                                    <!-- Change Status Controls -->
                                    <div class="change-status-controls" id="changeStatusControls<?= htmlspecialchars($order['order_id']) ?>">
                                        <label for="newStatus<?= htmlspecialchars($order['order_id']) ?>" class="form-label"><i class="bi bi-arrow-repeat"></i> Change Order Status</label>
                                        <select class="form-select" id="newStatus<?= htmlspecialchars($order['order_id']) ?>" onchange="validateChangeStatus(<?= htmlspecialchars($order['order_id']) ?>)">
                                            <option value="" selected disabled>Choose status...</option>
                                            <option value="Pending">Pending</option>
                                            <option value="Completed">Completed</option>
                                            <option value="Delivered">Delivered</option>
                                        </select>
                                        <div class="action-buttons-inline">
                                            <button class="btn btn-primary" id="confirmChangeStatusBtn<?= htmlspecialchars($order['order_id']) ?>" onclick="confirmChangeStatus(<?= htmlspecialchars($order['order_id']) ?>)" disabled>Change Status</button>
                                            <button class="btn btn-secondary" onclick="cancelChangeStatus(<?= htmlspecialchars($order['order_id']) ?>)">Cancel</button>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="text-center">No orders found.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <nav aria-label="Order pagination">
                <ul class="pagination justify-content-center">
                    <!-- Previous -->
                    <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="view_orders.php<?php
                            $prev_page = max($page - 1, 1);
                            $query_params = array_merge($_GET, ['page' => $prev_page]);
                            echo http_build_query($query_params) ? '?' . http_build_query($query_params) : '';
                        ?>" tabindex="-1" aria-disabled="<?php echo ($page <= 1) ? 'true' : 'false'; ?>">Previous</a>
                    </li>

                    <!-- Page Numbers -->
                    <?php
                        // Determine the range of pages to show
                        $max_links = 5;
                        $start = max($page - floor($max_links / 2), 1);
                        $end = min($start + $max_links - 1, $total_pages);
                        if ($end - $start < $max_links - 1) {
                            $start = max($end - $max_links + 1, 1);
                        }
                    ?>
                    <?php for ($i = $start; $i <= $end; $i++): ?>
                        <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                            <a class="page-link" href="view_orders.php<?php
                                $query_params = array_merge($_GET, ['page' => $i]);
                                echo http_build_query($query_params) ? '?' . http_build_query($query_params) : '';
                            ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>

                    <!-- Next -->
                    <li class="page-item <?php echo ($page >= $total_pages) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="view_orders.php<?php
                            $next_page = min($page + 1, $total_pages);
                            $query_params = array_merge($_GET, ['page' => $next_page]);
                            echo http_build_query($query_params) ? '?' . http_build_query($query_params) : '';
                        ?>">Next</a>
                    </li>
                </ul>
            </nav>
        <?php endif; ?>


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

<!-- Delete Confirmation Modal -->
<!-- Removed as per the request -->

</main>
    <!-- Bootstrap JS Bundle -->
    <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <!-- Flatpickr JS for Date Picker -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <!-- Bootstrap Tooltip and Popover Initialization -->
    <script>
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
        })
    </script>

    <!-- Custom JS for Sorting, Deletion, and Filtering -->
    <script>
        // Initialize Flatpickr for date inputs if present
        flatpickr("#fromDate", {
            dateFormat: "Y-m-d",
            maxDate: "today"
        });

        flatpickr("#toDate", {
            dateFormat: "Y-m-d",
            maxDate: "today"
        });

        // Function to handle sorting
        function sortTable(column) {
            const urlParams = new URLSearchParams(window.location.search);
            let currentSortBy = urlParams.get('sort_by') || 'order_date';
            let currentSortOrder = urlParams.get('sort_order') || 'DESC';

            if (currentSortBy === column) {
                // Toggle sort order
                currentSortOrder = currentSortOrder === 'ASC' ? 'DESC' : 'ASC';
            } else {
                currentSortBy = column;
                currentSortOrder = 'ASC';
            }

            urlParams.set('sort_by', currentSortBy);
            urlParams.set('sort_order', currentSortOrder);
            // Reset to first page if pagination is implemented
            urlParams.set('page', 1);

            window.location.search = urlParams.toString();
        }

        // Function to confirm deletion using browser confirm dialog
        function confirmDelete(orderId) {
            if (window.confirm("Are you sure you want to delete this order? This action cannot be undone.")) {
                window.location.href = 'delete_order.php?order_id=' + orderId;
            }
        }

        // Function to toggle Change Status Controls
        function toggleChangeStatus(orderId) {
            const controls = document.getElementById('changeStatusControls' + orderId);
            const originalButtons = controls.previousElementSibling; // action-buttons div

            if (controls.classList.contains('active')) {
                controls.classList.remove('active');
                originalButtons.style.display = 'flex';
            } else {
                // Hide other change status controls
                document.querySelectorAll('.change-status-controls.active').forEach(function(el) {
                    el.classList.remove('active');
                    const siblings = el.previousElementSibling;
                    if (siblings) {
                        siblings.style.display = 'flex';
                    }
                });
                controls.classList.add('active');
                originalButtons.style.display = 'none';
            }
        }

        // Function to confirm status change
        function confirmChangeStatus(orderId) {
            const newStatus = document.getElementById('newStatus' + orderId).value;
            if (newStatus) {
                window.location.href = `view_orders.php?action=update_status&order_id=${orderId}&new_status=${newStatus}`;
            }
        }

        // Function to cancel status change
        function cancelChangeStatus(orderId) {
            const controls = document.getElementById('changeStatusControls' + orderId);
            const originalButtons = controls.previousElementSibling; // action-buttons div

            controls.classList.remove('active');
            originalButtons.style.display = 'flex';
        }

        // Function to validate Change Status button
        function validateChangeStatus(orderId) {
            const newStatus = document.getElementById('newStatus' + orderId).value;
            const confirmBtn = document.getElementById('confirmChangeStatusBtn' + orderId);
            if (newStatus) {
                confirmBtn.disabled = false;
            } else {
                confirmBtn.disabled = true;
            }
        }

        // Function to edit order
        function editOrder(orderId) {
            window.location.href = `edit_order.php?id=${orderId}`;
        }

        // Function to apply filters (on status change, priority change, date filters, and records per page)
        function applyFilters() {
            const urlParams = new URLSearchParams(window.location.search);
            const statusFilter = document.getElementById('statusFilter').value;
            const priorityFilter = document.getElementById('priorityFilter').value;
            const ordersPerPage = document.getElementById('entriesPerPage').value;
            const fromDate = document.getElementById('fromDate').value;
            const toDate = document.getElementById('toDate').value;

            urlParams.set('status_filter', statusFilter);
            urlParams.set('priority_filter', priorityFilter);
            urlParams.set('orders_per_page', ordersPerPage);
            urlParams.set('from_date', fromDate);
            urlParams.set('to_date', toDate);
            urlParams.set('page', 1); // Reset to first page

            window.location.search = urlParams.toString();
        }

        // Function to apply date filters separately
        function applyDateFilters() {
            applyFilters();
        }

        // Close action rows when clicking outside the table
        document.addEventListener('click', function(event) {
            const isClickInside = event.target.closest('.orders-table');
            if (!isClickInside) {
                document.querySelectorAll('.change-status-controls.active').forEach(function(el) {
                    el.classList.remove('active');
                    const siblings = el.previousElementSibling;
                    if (siblings) {
                        siblings.style.display = 'flex';
                    }
                });
            }
        });
    </script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>) change it totaly and use this styles (    <!-- Custom Styles -->
    <style>
        /* ---------------------------------------------------
           1. CSS Variables for Consistent Design
        ---------------------------------------------------- */
        :root {
            /* Primary Colors */
            --background-color: #FFFFFF; /* Crisp White */
            --light-grey: #F5F5F5;
            --medium-grey: #CCCCCC;
            --dark-grey: #333333;
            --charcoal: #4A4A4A;

            /* Accent Colors */
            --accent-blue: #4A90E2;
            --accent-green: #50C878;
            --accent-red: #FF6B6B;
            --accent-teal: #20B2AA;
            --accent-soft-blue: #A3D2CA;
            --accent-purple: #8A65FF;
            --accent-orange: #FFA500;

            /* Text Colors */
            --primary-text: var(--dark-grey);
            --secondary-text: #666666;

            /* UI Elements */
            --input-border: var(--medium-grey);
            --input-focus-border: var(--accent-teal);
            --box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            --box-border-radius: 12px;
            --hover-shadow: rgba(0, 0, 0, 0.1);

            /* Button Colors */
            --button-add-order: #6C63FF;
            --button-view-orders: #FFA500;
            --button-manage-products: #20B2AA;
            --button-manage-users: #4B0082;
            --button-generate-reports: #FF6B6B;

            /* Status Badge Colors */
            --badge-pending: #FFD166;
            --badge-in-progress: #6A4C93;
            --badge-completed: #4CAF50;
            --badge-delivered: #20B2AA;
        }

        /* ---------------------------------------------------
           2. Global Styles
        ---------------------------------------------------- */
        body {
            font-family: 'Roboto', sans-serif;
            background-color: var(--light-grey);
            margin: 0;
            padding: 0;
            color: var(--primary-text);
        }

        .container-body {
            max-width: 1200px;
            margin: 40px auto;
            padding: 40px 20px;
            box-sizing: border-box;
            background-color: var(--background-color);
            box-shadow: var(--box-shadow);
            border-radius: var(--box-border-radius);
            font-family: 'Roboto', sans-serif;
            transition: all 0.3s ease;
        }

        /* ---------------------------------------------------
           3. Header Styles
        ---------------------------------------------------- */
        .header {
            padding: 20px 30px;
            background-color: var(--background-color);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 30px;
            border-bottom: 1px solid var(--light-grey);
        }

        .header h1 {
            color: var(--charcoal);
            font-size: 32px;
            font-weight: 700;
            font-family: 'Inter', sans-serif;
            position: relative;
        }

        /* Decorative Line Under Header */
        .header h1::after {
            content: "";
            display: block;
            width: 80px;
            height: 4px;
            background: linear-gradient(90deg, var(--accent-teal), var(--accent-soft-blue));
            margin: 8px auto 0;
            border-radius: 2px;
        }

        /* ---------------------------------------------------
           4. Welcome Section
        ---------------------------------------------------- */
        .welcome-section {
            background-color: var(--background-color);
            box-shadow: var(--box-shadow);
            border-radius: var(--box-border-radius);
            padding: 30px;
            text-align: center;
            margin-bottom: 30px;
            font-family: 'Inter', sans-serif;
        }

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

        .welcome-section p {
            font-size: 16px;
            color: var(--secondary-text);
            margin: 0;
        }

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

        .stat-card {
            background-color: var(--background-color);
            box-shadow: var(--box-shadow);
            border-radius: var(--box-border-radius);
            padding: 20px;
            display: flex;
            align-items: center;
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: default;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .stat-icon {
            font-size: 36px;
            margin-right: 20px;
            /* Default color */
            color: var(--accent-blue);
        }

        /* Different colors for each stat icon */
        .stat-icon.orders { color: var(--accent-blue); } /* Blue */
        .stat-icon.pending { color: var(--badge-pending); } /* Yellow */
        .stat-icon.completed { color: var(--badge-completed); } /* Green */
        .stat-icon.delivered { color: var(--badge-delivered); } /* Teal */
        .stat-icon.sales { color: var(--accent-red); } /* Red */

        .stat-info h5 {
            font-size: 18px;
            color: var(--primary-text);
            margin-bottom: 8px;
            font-family: 'Inter', sans-serif;
            font-weight: 600;
        }

        .stat-info p {
            font-size: 26px;
            font-weight: 700;
            color: var(--charcoal);
            margin: 0;
        }

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

        .action-button {
            display: flex;
            align-items: center;
            justify-content: center;
            flex: 1 1 200px;
            height: 60px;
            font-size: 16px;
            font-weight: 600;
            color: #FFFFFF;
            border: none;
            border-radius: 30px;
            padding: 0 20px;
            cursor: pointer;
            transition: background-color 0.3s, box-shadow 0.3s;
            text-decoration: none;
            text-align: center;
            font-family: 'Inter', sans-serif;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
            position: relative;
            overflow: hidden;
        }

        .action-button::before {
            content: "";
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(45deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0));
            transition: left 0.3s;
        }

        .action-button:hover::before {
            left: 100%;
        }

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

        .action-button:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        .action-button i {
            margin-right: 10px;
            font-size: 20px;
            color: #FFFFFF;
        }

        /* ---------------------------------------------------
           7. Recent Orders Section
        ---------------------------------------------------- */
        .recent-orders-section {
            background-color: var(--background-color);
            border-radius: var(--box-border-radius);
            padding: 30px;
            box-shadow: var(--box-shadow);
        }

        .recent-orders-section h4 {
            font-size: 24px;
            font-weight: 700;
            color: var(--charcoal);
            margin-bottom: 20px;
            font-family: 'Inter', sans-serif;
        }

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

        .recent-orders-section table {
            width: 100%;
            border-collapse: collapse;
            font-family: 'Roboto', sans-serif;
        }

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

        .recent-orders-section th {
            background-color: var(--light-grey);
            color: var(--charcoal);
            font-weight: 700;
            border-bottom: 2px solid var(--medium-grey);
            font-family: 'Inter', sans-serif;
            position: relative;
        }

        /* Underline for headers */
        .recent-orders-section th::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 2px;
            background-color: var(--medium-grey);
        }

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

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

        .recent-orders-section td {
            color: var(--secondary-text);
        }

        .recent-orders-section .view-all {
            display: block;
            text-align: right;
            margin-top: 15px;
            font-size: 16px;
            color: var(--accent-teal);
            font-weight: 600;
            text-decoration: none;
            font-family: 'Inter', sans-serif;
            transition: color 0.3s;
        }

        .recent-orders-section .view-all:hover {
            color: var(--accent-soft-blue);
        }

        /* Badge Styles */
        .badge-status-pending {
            background-color: var(--badge-pending);
            color: #FFFFFF;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-status-in-progress {
            background-color: var(--badge-in-progress);
            color: #FFFFFF;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-status-completed {
            background-color: var(--badge-completed);
            color: #FFFFFF;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-status-delivered {
            background-color: var(--badge-delivered);
            color: #FFFFFF;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        /* ---------------------------------------------------
           8. Footer Styles
        ---------------------------------------------------- */
        .footer {
            background-color: var(--background-color);
            color: var(--secondary-text);
            padding: 20px;
            text-align: center;
            border-radius: var(--box-border-radius);
            font-size: 14px;
            line-height: 22px;
            margin-top: 40px;
            font-family: 'Roboto', sans-serif;
            box-shadow: var(--box-shadow);
        }

        /* ---------------------------------------------------
           9. Responsive Design Enhancements
        ---------------------------------------------------- */
        @media (max-width: 768px) {
            .header h1 {
                font-size: 24px;
            }

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

            .stats-section {
                grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
                gap: 20px;
            }

            .stat-icon {
                font-size: 30px;
            }

            .stat-info p {
                font-size: 22px;
            }

            .action-button {
                flex: 1 1 100%;
                height: 50px;
                font-size: 14px;
            }

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

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

        @media (max-width: 480px) {
            .container-body {
                padding: 20px 10px;
            }

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

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

            .stat-info p {
                font-size: 20px;
            }

            .action-button {
                height: 45px;
                font-size: 13px;
            }

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

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

    </style>
) and type full codes and make it clean codes