make 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);

// Include authentication and database connection **before** including the header
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';

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

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

// Helper function to get product price
function get_product_price($conn, $product_id) {
    $price_sql = "SELECT price FROM products WHERE id = ? LIMIT 1";
    $price_stmt = $conn->prepare($price_sql);
    if (!$price_stmt) {
        return "0.00";
    }
    $price_stmt->bind_param("i", $product_id);
    $price_stmt->execute();
    $price_result = $price_stmt->get_result();
    if ($price_result->num_rows == 1) {
        $price = $price_result->fetch_assoc()['price'];
    } else {
        $price = "0.00";
    }
    $price_stmt->close();
    return $price;
}

// Function to build query string for filter buttons while preserving other parameters
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 : '';
}

// Function to get sort icon HTML based on current sorting
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"></i>';
        } else {
            return '<i class="bi bi-arrow-down sort-icon"></i>';
        }
    }
    return '';
}

// Function to sanitize input for SQL
function sanitize_input($input) {
    return htmlspecialchars(trim($input));
}

// Function to generate WhatsApp link from contact number
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;
}

// Handle status update
if (isset($_GET['action']) && $_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 (Removed 'In Progress')
    $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();
    }
}

// Handle Export
if (isset($_GET['action']) && $_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();
}

// 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';
$search = isset($_GET['search']) ? sanitize_input($_GET['search']) : '';
$from_date = isset($_GET['from_date']) ? sanitize_input($_GET['from_date']) : '';
$to_date = isset($_GET['to_date']) ? sanitize_input($_GET['to_date']) : '';
$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;

// 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 = ['order_id', 'customer_name', 'contact', 'status', '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 = "";

// Predefined Date Filters are removed as per the request
// Only Status Filter and Search Filter are retained

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

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

// 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 = [
    'order_id' => 'orders.id',
    'customer_name' => 'customers.name',
    'contact' => 'customers.contact',
    'status' => 'orders.status',
    'order_date' => 'orders.order_date',
    'delivery_datetime' => 'orders.delivery_datetime'
];
$sort_column = isset($sort_column_map[$sort_by]) ? $sort_column_map[$sort_by] : 'orders.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(*) as total 
    FROM orders
    JOIN customers ON orders.customer_id = customers.id
    JOIN products ON orders.product_id = products.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 and product details based on filters and sorting
$orders_sql = "
    SELECT 
        orders.id AS order_id,
        orders.status,
        orders.order_date,
        orders.delivery_datetime,
        customers.name AS customer_name,
        customers.contact,
        customers.delivery_address,
        orders.product_id AS primary_product_id,
        orders.quantity AS primary_quantity,
        orders.packaging_preferences AS primary_packaging_preferences,
        products.name AS primary_product_name,
        products.size AS primary_product_size
    FROM 
        orders
    JOIN 
        customers ON orders.customer_id = customers.id
    JOIN 
        products ON orders.product_id = products.id
    $where_clause
    $order_clause
    LIMIT ?, ?
";
$orders_stmt = $conn->prepare($orders_sql);
if ($orders_stmt) {
    // Bind parameters
    if (!empty($where_clause)) {
        // 'i' 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 
            order_items.order_id,
            order_items.product_id,
            order_items.quantity,
            order_items.packaging_preferences,
            products.name AS product_name,
            products.size AS product_size
        FROM 
            order_items
        JOIN 
            products ON order_items.product_id = products.id
        WHERE
            order_items.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=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
    
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="/kaak_alia_management_system/assets/bootstrap/css/bootstrap.min.css">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Flatpickr CSS for Date Picker -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <!-- Embedded Custom Styles -->
    <style>
        /* ---------------------------------------------------
           1. CSS Variables for Consistent Design
        ---------------------------------------------------- */
        :root {
            --dark-gray: #343a40; /* Header and Footer Background */
            --soft-brown: #FFD166; /* Button Background */
            --blue: #118AB2; /* Primary Button */
            --green: #06D6A0; /* Success Button */
            --orange: #F4A261; /* Warning Button */
            --red-pink: #EF476F; /* Danger Button */

            --main-text: #333333;
            --secondary-text: #666666;
            --white: #FFFFFF;
            --light-gray: #F9F9F9;
            --divider-color: #FFD166;

            --transition-speed: 0.3s;
            --hover-shadow: rgba(0, 0, 0, 0.2);
        }

        /* ---------------------------------------------------
           2. Global Styles
        ---------------------------------------------------- */
        body {
            font-family: 'Cairo', sans-serif;
            background: linear-gradient(to bottom, #f5f7fa, #c3cfe2);
            margin: 0;
            padding: 30px;
            box-sizing: border-box;
        }

        /* ---------------------------------------------------
           3. Header Styles
        ---------------------------------------------------- */
        .header {
            padding: 20px 30px;
            background-color: var(--dark-gray);
            border-radius: 8px;
            text-align: center;
            margin-bottom: 30px;
            color: var(--white);
            font-size: 28px;
            font-weight: bold;
            box-shadow: 0 4px 6px var(--hover-shadow);
        }

        /* ---------------------------------------------------
           4. Success and Error Alerts
        ---------------------------------------------------- */
        .alert-success-custom {
            background-color: var(--green);
            color: var(--white);
            border-radius: 8px;
            padding: 15px 20px;
            margin-bottom: 20px;
            text-align: center;
            width: 70%;
            margin: 20px auto;
            box-shadow: 0 4px 6px var(--hover-shadow);
        }

        .alert-error-custom {
            background-color: var(--red-pink);
            color: var(--white);
            border-radius: 8px;
            padding: 15px 20px;
            margin-bottom: 20px;
            text-align: center;
            width: 70%;
            margin: 20px auto;
            box-shadow: 0 4px 6px var(--hover-shadow);
        }

        /* ---------------------------------------------------
           5. 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);
            max-width: 1000px;
            margin: 0 auto;
        }

        .recent-orders-section h4 {
            font-size: 24px;
            font-weight: bold;
            color: var(--main-text);
            margin-bottom: 20px;
            border-bottom: 2px solid var(--divider-color);
            padding-bottom: 10px;
        }

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

        .filter-search-section .search-group,
        .filter-search-section .status-filter-group {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        /* Enhanced Styles for Search Input */
        .filter-search-section .search-group input {
            margin-left: 5px;
            width: 250px;
            padding: 8px 12px;
            border-radius: 5px;
            border: 1px solid #ced4da;
            transition: border-color var(--transition-speed), box-shadow var(--transition-speed);
        }

        .filter-search-section .search-group input:focus {
            border-color: var(--blue);
            box-shadow: 0 0 5px rgba(17, 138, 178, 0.5);
            outline: none;
        }

        /* Enhanced Styles for Search Button */
        .filter-search-section .search-group button {
            background-color: var(--blue);
            color: var(--white);
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            margin-left: 10px;
            cursor: pointer;
            transition: background-color var(--transition-speed), transform var(--transition-speed);
        }

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

        /* Status Filter Dropdown */
        .filter-search-section .status-filter-group label {
            margin-left: 5px;
            margin-right: 10px;
        }

        .filter-search-section .status-filter-group select {
            padding: 8px 12px;
            border-radius: 5px;
            border: 1px solid #ced4da;
            transition: border-color var(--transition-speed), box-shadow var(--transition-speed);
            width: 150px;
        }

        .filter-search-section .status-filter-group select:focus {
            border-color: var(--blue);
            box-shadow: 0 0 5px rgba(17, 138, 178, 0.5);
            outline: none;
        }

        /* ---------------------------------------------------
           7. Orders Table Styles
        ---------------------------------------------------- */
        .orders-table {
            width: 100%;
            border-collapse: collapse;
            border: 2px solid var(--dark-gray);
        }

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

        .orders-table th {
            background-color: var(--dark-gray);
            color: var(--white);
            font-weight: bold;
            cursor: pointer;
            position: relative;
            user-select: none;
        }

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

        .orders-table tr:nth-child(even) {
            background-color: var(--light-gray);
        }

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

        .orders-table td {
            font-size: 14px;
            color: var(--main-text);
            position: relative;
        }

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

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

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

        /* Highlight New Order IDs */
        .new-order {
            color: #EF476F;
            font-weight: bold;
        }

        /* ---------------------------------------------------
           8. Actions Column Styles
        ---------------------------------------------------- */
        .action-buttons .btn {
            margin-right: 5px;
            transition: transform var(--transition-speed);
        }

        .action-buttons .btn:hover {
            transform: scale(1.1);
        }

        /* Dropdown Styles */
        .dropdown-menu > a {
            cursor: pointer;
        }

        /* ---------------------------------------------------
           9. Footer Styles
        ---------------------------------------------------- */
        .footer {
            background-color: var(--dark-gray);
            color: var(--white);
            padding: 15px;
            text-align: center;
            border-radius: 8px;
            font-size: 14px;
            line-height: 20px;
            margin-top: 40px;
            box-shadow: 0 4px 6px var(--hover-shadow);
            max-width: 1000px;
            margin-left: auto;
            margin-right: auto;
        }

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

            .filter-search-section .search-group,
            .filter-search-section .status-filter-group {
                width: 100%;
                justify-content: space-between;
            }

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

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

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

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

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

        /* Additional Styles */
        .btn-reset {
            margin-left: 10px;
        }

        /* Toggle Action Rows */
        .action-row {
            display: none;
        }

        .action-row.show {
            display: table-row;
        }

        .action-row .action-cell {
            padding: 10px;
            background-color: var(--light-gray);
        }

        @media (max-width: 992px) {
            .action-row .action-cell {
                background-color: #f1f1f1;
            }
        }

        @media (max-width: 768px) {
            .action-row .action-cell {
                background-color: #f8f9fa;
            }
        }

        /* Make cursor pointer for main table rows */
        .orders-table tbody tr {
            cursor: pointer;
        }
    </style>
</head>
<body>

    <!-- Header -->
    <div class="header">
        View Orders
    </div>

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

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

    <?php if (isset($_GET['export']) && $_GET['export'] == 1): ?>
        <div class="alert alert-success alert-success-custom" role="alert">
            Orders exported successfully!
        </div>
    <?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 mb-3">
                <label for="statusFilter" class="me-2">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>

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

        <!-- Pagination Information -->
        <div class="pagination-info">
            <?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 $start_order-$end_order of $total_orders orders";
            ?>
        </div>

        <!-- Orders Table -->
        <div class="table-responsive">
            <table class="table table-hover orders-table">
                <thead>
                    <tr>
                        <th onclick="sortTable('order_id')">
                            ID
                            <?php echo get_sort_icon('order_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>Primary Product</th>
                        <th>Additional Products</th>
                        <th onclick="sortTable('status')">
                            Status
                            <?php echo get_sort_icon('status', $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>
                        <th>Actions</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']);
                            ?>
                            <!-- Main Row -->
                            <tr onclick="toggleActions(<?= htmlspecialchars($order['order_id']) ?>)" data-bs-toggle="collapse" data-bs-target="#actionRow<?= htmlspecialchars($order['order_id']) ?>" aria-expanded="false" aria-controls="actionRow<?= htmlspecialchars($order['order_id']) ?>">
                                <td class="<?php echo $is_new ? 'new-order' : ''; ?>">
                                    <?= htmlspecialchars($order['order_id']) ?>
                                </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>
                                    <strong><?= htmlspecialchars($order['primary_product_name']) ?></strong><br>
                                    Size: <?= htmlspecialchars($order['primary_product_size']) ?><br>
                                    Price: <?= number_format(get_product_price($conn, $order['primary_product_id']), 2) ?> KD<br>
                                    Qty: <?= htmlspecialchars($order['primary_quantity']) ?><br>
                                    Packaging: <?= htmlspecialchars($order['packaging_preferences']) ?>
                                </td>
                                <td>
                                    <?php
                                        if (isset($order_items[$order['order_id']])) {
                                            foreach ($order_items[$order['order_id']] as $item) {
                                                echo "<strong>" . htmlspecialchars($item['product_name']) . "</strong> - " . htmlspecialchars($item['product_size']) . "<br>";
                                                echo "Price: " . number_format(get_product_price($conn, $item['product_id']), 2) . " KD<br>";
                                                echo "Qty: " . htmlspecialchars($item['quantity']) . "<br>";
                                                echo "Packaging: " . htmlspecialchars($item['packaging_preferences']) . "<br><br>";
                                            }
                                        } else {
                                            echo "None";
                                        }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                        switch ($order['status']) {
                                            case 'Pending':
                                                echo '<span class="badge-status-pending"><i class="bi bi-hourglass-split"></i> Pending</span>';
                                                break;
                                            case 'Completed':
                                                echo '<span class="badge-status-completed"><i class="bi bi-check-circle-fill"></i> Completed</span>';
                                                break;
                                            case 'Delivered':
                                                echo '<span class="badge-status-delivered"><i class="bi bi-box-seam"></i> Delivered</span>';
                                                break;
                                            default:
                                                echo '<span class="badge bg-light text-dark">Unknown</span>';
                                        }
                                    ?>
                                </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>
                                <td></td>
                            </tr>
                            <!-- Action Buttons Row -->
                            <tr id="actionRow<?= htmlspecialchars($order['order_id']) ?>" class="action-row collapse">
                                <td colspan="10" class="action-cell">
                                    <div class="d-flex justify-content-start">
                                        <!-- Edit Order -->
                                        <a href="edit_order.php?id=<?= htmlspecialchars($order['order_id']) ?>" class="btn btn-sm btn-outline-secondary me-2" 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
                                        </a>
                                        
                                        <!-- Change Status Dropdown -->
                                        <div class="btn-group me-2" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-info dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" 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>
                                            <ul class="dropdown-menu">
                                                <li><a class="dropdown-item" href="?action=update_status&order_id=<?= htmlspecialchars($order['order_id']) ?>&new_status=Pending">Pending</a></li>
                                                <li><a class="dropdown-item" href="?action=update_status&order_id=<?= htmlspecialchars($order['order_id']) ?>&new_status=Completed">Completed</a></li>
                                                <li><a class="dropdown-item" href="?action=update_status&order_id=<?= htmlspecialchars($order['order_id']) ?>&new_status=Delivered">Delivered</a></li>
                                            </ul>
                                        </div>
                                        
                                        <!-- Delete Order -->
                                        <button type="button" class="btn btn-sm btn-outline-danger" title="Delete Order" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Delete Order" onclick="confirmDelete(<?= htmlspecialchars($order['order_id']) ?>)">
                                            <i class="bi bi-trash-fill"></i> Delete
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="10" 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);
                        ?>" tabindex="-1">Previous</a>
                    </li>

                    <!-- Page Numbers -->
                    <?php for ($i = 1; $i <= $total_pages; $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);
                            ?>"><?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);
                        ?>">Next</a>
                    </li>
                </ul>
            </nav>
        <?php endif; ?>

    </div>

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

    <!-- 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 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
        flatpickr("#from_date", {
            dateFormat: "Y-m-d",
            maxDate: "today"
        });

        flatpickr("#to_date", {
            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
        function confirmDelete(orderId) {
            if (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 apply filters (on status change and records per page)
        function applyFilters() {
            const urlParams = new URLSearchParams(window.location.search);
            const statusFilter = document.getElementById('statusFilter').value;
            const ordersPerPage = document.getElementById('ordersPerPage').value;

            urlParams.set('status_filter', statusFilter);
            urlParams.set('orders_per_page', ordersPerPage);
            urlParams.set('page', 1); // Reset to first page

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

        // Function to toggle action row
        function toggleActions(orderId) {
            const actionRow = document.getElementById(`actionRow${orderId}`);
            if (actionRow.classList.contains('show')) {
                actionRow.classList.remove('show');
            } else {
                // Hide any other open action rows
                const allActionRows = document.querySelectorAll('.action-row');
                allActionRows.forEach(row => {
                    row.classList.remove('show');
                });
                // Show the selected action row
                actionRow.classList.add('show');
            }
        }

        // Close action rows when clicking outside the table
        document.addEventListener('click', function(event) {
            const isClickInside = event.target.closest('.orders-table');
            if (!isClickInside) {
                const allActionRows = document.querySelectorAll('.action-row');
                allActionRows.forEach(row => {
                    row.classList.remove('show');
                });
            }
        });
    </script>
</body>
</html>
<?php
// No closing PHP tag to prevent unwanted output
?>) great ddesig and add more codes to make it cool design and make table readable table and type full codes and don't remove styles