fix this codes (<?php
// 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';

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

// 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 : '';
}

/**
 * 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 except the plus sign
    $digits = preg_replace('/[^\d+]/', '', $contact);

    // Ensure the number starts with '+'
    if (strpos($digits, '+') !== 0) {
        $digits = '+' . $digits;
    }

    // Remove '+' for WhatsApp URL
    $digits = ltrim($digits, '+');

    return "https://wa.me/" . $digits;
}

/**
 * Calculate totals for a given set of order items.
 *
 * @param array $order_items The array of order items.
 * @param float $delivery_fee The delivery fee for the order.
 * @param int $free_shipping Indicates if free shipping is applied (1 for yes, 0 for no).
 * @param int $pickup Indicates if the order is for pickup (1 for yes, 0 for no).
 * @return array An associative array containing total_before_discounts, total_discounts, delivery_fee, and final_total.
 */
function calculate_order_totals($order_items, $delivery_fee, $free_shipping, $pickup) {
    $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;

    // Add delivery fee if not free shipping and not pickup
    if (!$free_shipping && !$pickup) {
        $final_total += $delivery_fee;
    }

    return [
        'total_before_discounts' => $total_before_discounts,
        'total_discounts' => $total_discounts,
        'delivery_fee' => (!$free_shipping && !$pickup) ? $delivery_fee : 0.00,
        'final_total' => $final_total
    ];
}

// Handle Actions (POST Requests)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        // Update Order Status
        if ($_POST['action'] === 'update_status') {
            $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
            $new_status = isset($_POST['new_status']) ? sanitize_input($_POST['new_status']) : '';

            // Validate new_status
            $valid_statuses = ['Pending', 'In Progress', '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'])) {
                                $check_stmt->close();
                                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();
            }
        }
        // Mark Order as Paid
        elseif ($_POST['action'] === 'mark_paid') {
            $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;

            if ($order_id > 0) {
                // Update is_paid to 1
                $update_sql = "UPDATE orders SET is_paid = 1 WHERE id = ?";
                $stmt = $conn->prepare($update_sql);
                if ($stmt) {
                    $stmt->bind_param("i", $order_id);
                    if ($stmt->execute()) {
                        $stmt->close();
                        header("Location: view_orders.php?success=3");
                        exit();
                    } else {
                        $stmt->close();
                        header("Location: view_orders.php?error=6");
                        exit();
                    }
                } else {
                    header("Location: view_orders.php?error=2");
                    exit();
                }
            } else {
                header("Location: view_orders.php?error=5");
                exit();
            }
        }
        // Delete Order
        elseif ($_POST['action'] === 'delete_order') {
            $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;

            if ($order_id > 0) {
                // Delete order items first to maintain referential integrity
                $delete_items_sql = "DELETE FROM order_items WHERE order_id = ?";
                $stmt_items = $conn->prepare($delete_items_sql);
                if ($stmt_items) {
                    $stmt_items->bind_param("i", $order_id);
                    if (!$stmt_items->execute()) {
                        $stmt_items->close();
                        header("Location: view_orders.php?error=4");
                        exit();
                    }
                    $stmt_items->close();
                } else {
                    header("Location: view_orders.php?error=2");
                    exit();
                }

                // Delete the order
                $delete_order_sql = "DELETE FROM orders WHERE id = ?";
                $stmt_order = $conn->prepare($delete_order_sql);
                if ($stmt_order) {
                    $stmt_order->bind_param("i", $order_id);
                    if ($stmt_order->execute()) {
                        $stmt_order->close();
                        header("Location: view_orders.php?success=2");
                        exit();
                    } else {
                        $stmt_order->close();
                        header("Location: view_orders.php?error=4");
                        exit();
                    }
                } else {
                    header("Location: view_orders.php?error=2");
                    exit();
                }
            } else {
                header("Location: view_orders.php?error=5");
                exit();
            }
        }
    }
}

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

// 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,
        o.delivery_fee,
        o.free_shipping,
        o.is_paid,
        o.pickup,
        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=Poppins:wght@400;600;700&family=Roboto:wght@400;500;700&family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    
    <!-- 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 for Scrollbars and Tooltips -->
    <style>
        /* Custom Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb {
            background: #20B2AA;
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #17a2b8;
        }

        /* Tooltip Styles */
        .tooltip {
            position: relative;
            display: inline-block;
            cursor: help;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: #333;
            color: #fff;
            text-align: left;
            border-radius: 6px;
            padding: 8px;
            position: absolute;
            z-index: 10;
            bottom: 125%; /* Position above the icon */
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 0.875rem;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }

        /* Enhanced Card Design */
        .order-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .order-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.15);
        }

        /* HR Styling */
        .custom-hr {
            border: none;
            border-top: 1px solid #e5e7eb;
            margin: 1.5rem 0;
        }
    </style>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Additional JavaScript for Modal Functionality -->
    <script>
        function editOrders() {
            // Placeholder for future editing functionalities
        }
    </script>
</head>
<body class="bg-gray-100 font-roboto">
<main class="max-w-7xl mx-auto p-6 bg-white shadow-lg rounded-lg mt-10">
    <!-- Display Success or Error Messages -->
    <?php if (isset($_GET['success'])): ?>
        <?php if ($_GET['success'] == 1): ?>
            <div class="flex items-center bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-check-circle-fill mr-2 text-xl"></i>
                <span>Order status updated successfully!</span>
            </div>
        <?php elseif ($_GET['success'] == 2): ?>
            <div class="flex items-center bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-check-circle-fill mr-2 text-xl"></i>
                <span>Order deleted successfully!</span>
            </div>
        <?php elseif ($_GET['success'] == 3): ?>
            <div class="flex items-center bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-cash-stack mr-2 text-xl"></i>
                <span>Order marked as paid successfully!</span>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <?php if (isset($_GET['error'])): ?>
        <?php if ($_GET['error'] == 1): ?>
            <div class="flex items-center bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-exclamation-triangle-fill mr-2 text-xl"></i>
                <span>Failed to update order status.</span>
            </div>
        <?php elseif ($_GET['error'] == 2): ?>
            <div class="flex items-center bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-exclamation-triangle-fill mr-2 text-xl"></i>
                <span>Invalid status selected.</span>
            </div>
        <?php elseif ($_GET['error'] == 3): ?>
            <div class="flex items-center bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-exclamation-triangle-fill mr-2 text-xl"></i>
                <span>Cannot set status to Delivered without a delivery date and time.</span>
            </div>
        <?php elseif ($_GET['error'] == 4): ?>
            <div class="flex items-center bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-exclamation-triangle-fill mr-2 text-xl"></i>
                <span>Failed to delete the order. Please try again.</span>
            </div>
        <?php elseif ($_GET['error'] == 5): ?>
            <div class="flex items-center bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-exclamation-triangle-fill mr-2 text-xl"></i>
                <span>Invalid order ID provided.</span>
            </div>
        <?php elseif ($_GET['error'] == 6): ?>
            <div class="flex items-center bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6" role="alert">
                <i class="bi bi-exclamation-triangle-fill mr-2 text-xl"></i>
                <span>Failed to mark the order as paid. Please try again.</span>
            </div>
        <?php endif; ?>
    <?php endif; ?>


    <!-- Recent Orders Section -->
    <div class="mb-8">
        <h2 class="text-3xl font-poppins font-bold text-teal-600 mb-6">All Orders</h2>

        <!-- Filter and Search Section -->
        <div class="flex flex-col md:flex-row md:justify-between mb-8 space-y-6 md:space-y-0">
            <!-- Filters -->
            <div class="flex flex-wrap items-center space-x-4">
                <!-- Status Filter -->
                <div class="flex items-center space-x-2">
                    <i class="bi bi-filter-circle-fill text-teal-600"></i>
                    <label for="statusFilter" class="font-medium text-gray-700">Status:</label>
                    <select id="statusFilter" onchange="applyFilters()" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500">
                        <option value="all" <?= $status_filter === 'all' ? 'selected' : ''; ?>>All</option>
                        <option value="Pending" <?= $status_filter === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="In Progress" <?= $status_filter === 'In Progress' ? 'selected' : ''; ?>>In Progress</option>
                        <option value="Completed" <?= $status_filter === 'Completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="Delivered" <?= $status_filter === 'Delivered' ? 'selected' : ''; ?>>Delivered</option>
                    </select>
                </div>

                <!-- Priority Filter -->
                <div class="flex items-center space-x-2">
                    <i class="bi bi-filter-circle-fill text-teal-600"></i>
                    <label for="priorityFilter" class="font-medium text-gray-700">Priority:</label>
                    <select id="priorityFilter" onchange="applyFilters()" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500">
                        <option value="all" <?= $priority_filter === 'all' ? 'selected' : ''; ?>>All</option>
                        <option value="Quick" <?= $priority_filter === 'Quick' ? 'selected' : ''; ?>>Quick</option>
                        <option value="Important" <?= $priority_filter === 'Important' ? 'selected' : ''; ?>>Important</option>
                        <option value="Normal" <?= $priority_filter === 'Normal' ? 'selected' : ''; ?>>Normal</option>
                    </select>
                </div>

                <!-- Entries Per Page -->
                <div class="flex items-center space-x-2">
                    <i class="bi bi-layout-split text-teal-600"></i>
                    <label for="entriesPerPage" class="font-medium text-gray-700">Show:</label>
                    <select id="entriesPerPage" onchange="applyFilters()" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500">
                        <option value="10" <?= $orders_per_page == 10 ? 'selected' : ''; ?>>10</option>
                        <option value="20" <?= $orders_per_page == 20 ? 'selected' : ''; ?>>20</option>
                        <option value="50" <?= $orders_per_page == 50 ? 'selected' : ''; ?>>50</option>
                    </select>
                    <span class="text-gray-700">entries</span>
                </div>

                <!-- Reset Filters Button -->
                <div class="flex items-center space-x-2">
                    <?php
                        // Build the reset URL with default filter values while preserving sort parameters
                        $reset_params = [
                            'filter' => 'all',
                            'status_filter' => 'all',
                            'priority_filter' => 'all',
                            'search' => null,
                            'from_date' => null,
                            'to_date' => null,
                            'sort_by' => $sort_by,
                            'sort_order' => $sort_order,
                            'orders_per_page' => $orders_per_page,
                            'page' => 1
                        ];
                    ?>
                    <a href="view_orders.php<?= build_query($reset_params); ?>" class="flex items-center space-x-1 bg-gray-500 text-white px-3 py-2 rounded-lg hover:bg-gray-600 transition duration-300">
                        <i class="bi bi-arrow-counterclockwise"></i>
                        <span>Reset Filters</span>
                    </a>
                </div>
            </div>

            <!-- Search Input Above the Table -->
            <div class="w-full md:w-1/3">
                <form method="GET" action="view_orders.php" class="flex items-center space-x-2">
                    <input type="hidden" name="filter" value="<?= sanitize_input($filter); ?>">
                    <input type="hidden" name="status_filter" value="<?= sanitize_input($status_filter); ?>">
                    <input type="hidden" name="priority_filter" value="<?= sanitize_input($priority_filter); ?>">
                    <input type="hidden" name="from_date" value="<?= sanitize_input($from_date); ?>">
                    <input type="hidden" name="to_date" value="<?= sanitize_input($to_date); ?>">
                    <input type="hidden" name="sort_by" value="<?= sanitize_input($sort_by); ?>">
                    <input type="hidden" name="sort_order" value="<?= sanitize_input($sort_order); ?>">
                    <input type="text" name="search" class="flex-1 border border-gray-300 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500" placeholder="🔍 Search by Customer, ID, or Contact" value="<?= sanitize_input($search); ?>">
                    <button type="submit" class="flex items-center space-x-1 bg-teal-500 text-white px-4 py-2 rounded-lg hover:bg-teal-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">
                        <i class="bi bi-search"></i>
                        <span>Search</span>
                    </button>
                    <?php if (!empty($search)): ?>
                        <a href="view_orders.php<?= build_query(['search' => null, 'page' => 1]); ?>" class="flex items-center space-x-1 bg-red-500 text-white px-3 py-2 rounded-lg hover:bg-red-600 transition duration-300">
                            <i class="bi bi-x-circle"></i>
                            <span>Reset</span>
                        </a>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <!-- Date Range Filter -->
        <div class="flex flex-wrap items-center space-x-4 mb-8">
            <div class="flex items-center space-x-2">
                <i class="bi bi-calendar-check-fill text-teal-600"></i>
                <label for="fromDate" class="font-medium text-gray-700">From:</label>
                <input type="text" id="fromDate" name="from_date" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500" placeholder="YYYY-MM-DD" value="<?= sanitize_input($from_date); ?>">
            </div>
            <div class="flex items-center space-x-2">
                <i class="bi bi-calendar-check-fill text-teal-600"></i>
                <label for="toDate" class="font-medium text-gray-700">To:</label>
                <input type="text" id="toDate" name="to_date" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500" placeholder="YYYY-MM-DD" value="<?= sanitize_input($to_date); ?>">
            </div>
            <button type="button" class="flex items-center space-x-1 bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-800 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500" onclick="applyDateFilters()">
                <i class="bi bi-calendar-fill"></i>
                <span>Apply</span>
            </button>
        </div>

        <!-- Pagination Information -->
        <div class="text-sm text-gray-600 mb-4">
            <?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 Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <?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 and card border based on status
                        switch ($order['status']) {
                            case 'Pending':
                                $badge_class = 'bg-yellow-400';
                                $icon = 'hourglass-split';
                                $border_class = 'border-yellow-400';
                                break;
                            case 'In Progress':
                                $badge_class = 'bg-indigo-500';
                                $icon = 'arrow-repeat';
                                $border_class = 'border-indigo-500';
                                break;
                            case 'Completed':
                                $badge_class = 'bg-green-500';
                                $icon = 'check-circle-fill';
                                $border_class = 'border-green-500';
                                break;
                            case 'Delivered':
                                $badge_class = 'bg-teal-500';
                                $icon = 'box-seam';
                                $border_class = 'border-teal-500';
                                break;
                            default:
                                $badge_class = 'bg-gray-400';
                                $icon = 'info-circle';
                                $border_class = 'border-gray-400';
                        }

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

                        // Calculate order totals, including delivery fee if applicable
                        $totals = calculate_order_totals($items, $order['delivery_fee'], $order['free_shipping'], $order['pickup']);
                        
                        // Determine if it's a pickup order
                        $is_pickup = $order['pickup'] == 1;
                    ?>
                    <div class="bg-white shadow-lg rounded-lg p-6 border-l-4 <?= $border_class; ?> order-card <?= $is_pickup ? 'bg-indigo-50' : ''; ?>">
                        <!-- Header -->
                        <div class="flex justify-between items-center mb-4">
                            <div>
                                <h3 class="text-2xl font-poppins font-bold text-teal-600">Order #<?= htmlspecialchars($order['order_id']) ?></h3>
                                <?php if ($is_new): ?>
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-teal-500 text-white mt-1">New</span>
                                <?php endif; ?>
                            </div>
                            <div>
                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold <?= $badge_class; ?> text-white">
                                    <i class="bi bi-<?= $icon ?> mr-1"></i> <?= htmlspecialchars($order['status']) ?>
                                </span>
                            </div>
                        </div>

                        <hr class="custom-hr">

                        <!-- Customer Info -->
                        <div class="mb-4">
                            <h4 class="text-lg font-semibold text-gray-700 mb-2">Customer Details</h4>
                            <p class="text-gray-600">
                                <strong>Name:</strong> <?= htmlspecialchars($order['customer_name']) ?><br>
                                <strong>Contact:</strong> <a href="<?= $whatsapp_link ?>" target="_blank" class="text-teal-500 hover:underline"><i class="bi bi-whatsapp"></i> <?= htmlspecialchars($order['contact']) ?></a><br>
                                <?php if (!$is_pickup): ?>
                                    <strong>Address:</strong> <?= nl2br(htmlspecialchars($order['delivery_address'])) ?>
                                <?php else: ?>
                                    <strong>Address:</strong> <?= htmlspecialchars($order['delivery_address']) ?><br>
                                    <strong>Pickup Location:</strong> <span class="text-indigo-600">Our Storefront</span>
                                <?php endif; ?>
                            </p>
                        </div>

                        <hr class="custom-hr">

                        <!-- Delivery Date and Time -->
                        <div class="mb-4">
                            <h4 class="text-lg font-semibold text-gray-700 mb-2">Delivery Date & Time</h4>
                            <?php if (!empty($order['delivery_datetime'])): ?>
                                <p class="text-gray-600">
                                    <?= date("l, d M Y, h:i A", strtotime($order['delivery_datetime'])); ?>
                                </p>
                            <?php else: ?>
                                <?php if ($is_pickup): ?>
                                    <p class="text-gray-500">Pickup scheduled below.</p>
                                <?php else: ?>
                                    <p class="text-gray-500">N/A</p>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                        <hr class="custom-hr">

                        <!-- Delivery Location for Pickup Orders -->
                        <?php if ($is_pickup): ?>
                            <div class="mb-4">
                                <h4 class="text-lg font-semibold text-gray-700 mb-2">Pickup Location</h4>
                                <p class="text-indigo-600">
                                    Our Storefront
                                </p>
                            </div>
                            <hr class="custom-hr">
                        <?php endif; ?>

                        <!-- Products -->
                        <div class="mb-4">
                            <h4 class="text-lg font-semibold text-gray-700 mb-2">Products</h4>
                            <?php if (!empty($items)): ?>
                                <ul class="list-disc list-inside text-gray-600">
                                    <?php foreach ($items as $item): ?>
                                        <li>
                                            <strong><?= htmlspecialchars($item['product_name']) ?></strong>
                                            <?php if (!empty($item['product_size'])): ?>
                                                (<?= htmlspecialchars($item['product_size']) ?>)
                                            <?php endif; ?> -
                                            <?= htmlspecialchars($item['quantity']) ?> x <?= number_format($item['product_price'], 2) ?> KD
                                            <?php if (floatval($item['discount_percentage']) > 0): ?>
                                                <span class="text-red-500">-<?= htmlspecialchars($item['discount_percentage']) ?>%</span>
                                                (<?= htmlspecialchars($item['discount_reason']) ?>)
                                            <?php endif; ?>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php else: ?>
                                <p class="text-gray-500">No products found.</p>
                            <?php endif; ?>
                        </div>

                        <hr class="custom-hr">

                        <!-- Totals -->
                        <div class="mb-4">
                            <h4 class="text-lg font-semibold text-gray-700 mb-2">Totals</h4>
                            <p class="text-gray-600">
                                <strong>Total Before Discounts:</strong> <?= number_format($totals['total_before_discounts'], 2) ?> KD<br>
                                <strong>Total Discounts:</strong> <?= number_format($totals['total_discounts'], 2) ?> KD<br>
                                <?php if (!$is_pickup): ?>
                                    <strong>Delivery Fee:</strong> <?= $order['free_shipping'] ? 'Free' : number_format($order['delivery_fee'], 2) . ' KD' ?><br>
                                <?php endif; ?>
                                <strong class="text-xl"><?= number_format($totals['final_total'], 2) ?> KD</strong>
                                <?php if($order['is_paid']): ?>
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-500 text-white ml-2">Paid</span>
                                <?php else: ?>
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-500 text-white ml-2">Unpaid</span>
                                <?php endif; ?>
                            </p>
                        </div>

                        <hr class="custom-hr">

                        <!-- Actions -->
                        <div class="flex flex-wrap space-x-2">
                            <!-- Edit Order -->
                            <button onclick="editOrder(<?= htmlspecialchars($order['order_id']) ?>)" class="flex items-center space-x-1 bg-teal-500 text-white px-3 py-2 rounded-lg hover:bg-teal-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">
                                <i class="bi bi-pencil-fill"></i>
                                <span>Edit</span>
                            </button>
                            
                            <!-- Change Status -->
                            <button onclick="openStatusModal(<?= htmlspecialchars($order['order_id']) ?>, '<?= htmlspecialchars($order['status']) ?>')" class="flex items-center space-x-1 bg-indigo-500 text-white px-3 py-2 rounded-lg hover:bg-indigo-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">
                                <i class="bi bi-arrow-repeat"></i>
                                <span>Status</span>
                            </button>
                            
                            <!-- Mark as Paid -->
                            <?php if(!$order['is_paid']): ?>
                                <button onclick="markPaid(<?= htmlspecialchars($order['order_id']) ?>)" class="flex items-center space-x-1 bg-green-500 text-white px-3 py-2 rounded-lg hover:bg-green-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">
                                    <i class="bi bi-cash-stack"></i>
                                    <span>Mark Paid</span>
                                </button>
                            <?php endif; ?>
                            
                            <!-- Delete Order -->
                            <button onclick="confirmDelete(<?= htmlspecialchars($order['order_id']) ?>)" class="flex items-center space-x-1 bg-red-500 text-white px-3 py-2 rounded-lg hover:bg-red-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">
                                <i class="bi bi-trash-fill"></i>
                                <span>Delete</span>
                            </button>
                            
                            <!-- View Customer Order -->
                            <a href="view_order_customer.php?order_id=<?= htmlspecialchars($order['order_id']) ?>" class="flex items-center space-x-1 bg-teal-500 text-white px-3 py-2 rounded-lg hover:bg-teal-600 transition duration-300" target="_blank">
                                <i class="bi bi-eye-fill"></i>
                                <span>View</span>
                            </a>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div class="col-span-1 md:col-span-2 text-center text-gray-500 py-4">
                    No orders found.
                </div>
            <?php endif; ?>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="flex justify-center mt-6">
                <nav aria-label="Order pagination">
                    <ul class="inline-flex -space-x-px">
                        <!-- Previous -->
                        <li>
                            <a href="view_orders.php<?= build_query([
                                'filter' => $filter,
                                'status_filter' => $status_filter,
                                'priority_filter' => $priority_filter,
                                'search' => $search,
                                'from_date' => $from_date,
                                'to_date' => $to_date,
                                'sort_by' => $sort_by,
                                'sort_order' => $sort_order,
                                'orders_per_page' => $orders_per_page,
                                'page' => max($page - 1, 1)
                            ]); ?>" class="py-2 px-3 mr-1 leading-tight text-gray-500 bg-white border border-gray-300 rounded-l-lg hover:bg-teal-100 hover:text-teal-600">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>
                                <a href="view_orders.php<?= build_query([
                                    'filter' => $filter,
                                    'status_filter' => $status_filter,
                                    'priority_filter' => $priority_filter,
                                    'search' => $search,
                                    'from_date' => $from_date,
                                    'to_date' => $to_date,
                                    'sort_by' => $sort_by,
                                    'sort_order' => $sort_order,
                                    'orders_per_page' => $orders_per_page,
                                    'page' => $i
                                ]); ?>" class="py-2 px-3 leading-tight <?= ($page == $i) ? 'text-white bg-teal-500 border-teal-500' : 'text-gray-500 bg-white border-gray-300'; ?> border hover:bg-teal-100 hover:text-teal-600">
                                    <?= $i; ?>
                                </a>
                            </li>
                        <?php endfor; ?>

                        <!-- Next -->
                        <li>
                            <a href="view_orders.php<?= build_query([
                                'filter' => $filter,
                                'status_filter' => $status_filter,
                                'priority_filter' => $priority_filter,
                                'search' => $search,
                                'from_date' => $from_date,
                                'to_date' => $to_date,
                                'sort_by' => $sort_by,
                                'sort_order' => $sort_order,
                                'orders_per_page' => $orders_per_page,
                                'page' => min($page + 1, $total_pages)
                            ]); ?>" class="py-2 px-3 ml-1 leading-tight text-gray-500 bg-white border border-gray-300 rounded-r-lg hover:bg-teal-100 hover:text-teal-600">Next</a>
                        </li>
                    </ul>
                </nav>
            </div>
        <?php endif; ?>

        <!-- Footer -->
        <div class="text-center text-gray-600 mt-8">
            &copy; <?= date("Y") ?> Kaak Alia Bakery. All rights reserved.
        </div>
    </div>

    <!-- Change Status Modal -->
    <div id="statusModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-lg w-80">
            <div class="p-4 border-b">
                <h3 class="text-lg font-semibold text-teal-600">Change Order Status</h3>
            </div>
            <form id="statusForm" method="POST" action="view_orders.php">
                <div class="p-4">
                    <input type="hidden" name="action" value="update_status">
                    <input type="hidden" id="modal_order_id" name="order_id" value="">
                    <label for="newStatus" class="block text-gray-700 font-medium mb-2">Select New Status:</label>
                    <select id="newStatus" name="new_status" class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-teal-500" required>
                        <option value="">-- Select Status --</option>
                        <option value="Pending">Pending</option>
                        <option value="In Progress">In Progress</option>
                        <option value="Completed">Completed</option>
                        <option value="Delivered">Delivered</option>
                    </select>
                </div>
                <div class="flex justify-end p-4 border-t">
                    <button type="button" onclick="closeStatusModal()" class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">Cancel</button>
                    <button type="submit" class="bg-teal-500 text-white px-4 py-2 rounded-lg hover:bg-teal-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">Update</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-lg w-80">
            <div class="p-4 border-b">
                <h3 class="text-lg font-semibold text-red-600">Confirm Deletion</h3>
            </div>
            <div class="p-4">
                <p class="text-gray-700">Are you sure you want to delete this order? This action cannot be undone.</p>
            </div>
            <div class="flex justify-end p-4 border-t">
                <button onclick="closeDeleteModal()" class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">Cancel</button>
                <form id="deleteForm" method="POST" action="view_orders.php">
                    <input type="hidden" name="action" value="delete_order">
                    <input type="hidden" id="delete_order_id" name="order_id" value="">
                    <button type="submit" class="bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition duration-300 focus:outline-none focus:ring-2 focus:ring-teal-500">Delete</button>
                </form>
            </div>
        </div>
    </div>
</main>
    <!-- Flatpickr JS for Date Picker -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <!-- Bootstrap Icons JS (optional if interactivity is needed) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.js"></script>

    <!-- UnoCSS Runtime (ensure it's loaded) -->
    <script type="module">
        import 'https://unpkg.com/@unocss/runtime?module';
    </script>

    <!-- JavaScript for Interactivity -->
    <script>
        // Initialize Flatpickr for date inputs
        flatpickr("#fromDate", {
            dateFormat: "Y-m-d",
            maxDate: "today",
            allowInput: true
        });

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

        // 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 custom modal
        function confirmDelete(orderId) {
            const deleteModal = document.getElementById('deleteModal');
            const deleteOrderId = document.getElementById('delete_order_id');

            // Set the order ID in the modal
            deleteOrderId.value = orderId;

            // Show the modal
            deleteModal.classList.remove('hidden');
        }

        // Function to close delete modal
        function closeDeleteModal() {
            const deleteModal = document.getElementById('deleteModal');
            deleteModal.classList.add('hidden');
        }

        // Function to open status change modal
        function openStatusModal(orderId, currentStatus) {
            const statusModal = document.getElementById('statusModal');
            const modalOrderId = document.getElementById('modal_order_id');
            const newStatusSelect = document.getElementById('newStatus');

            // Set the order ID in the modal
            modalOrderId.value = orderId;

            // Set the current status as the default selected option
            newStatusSelect.value = currentStatus;

            // Show the modal
            statusModal.classList.remove('hidden');
        }

        // Function to close status change modal
        function closeStatusModal() {
            const statusModal = document.getElementById('statusModal');
            statusModal.classList.add('hidden');
        }

        // Function to mark an order as paid
        function markPaid(orderId) {
            if (confirm("Are you sure you want to mark this order as paid?")) {
                // Create a form to submit the mark_paid action via POST
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = 'view_orders.php';

                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'mark_paid';
                form.appendChild(actionInput);

                const orderIdInput = document.createElement('input');
                orderIdInput.type = 'hidden';
                orderIdInput.name = 'order_id';
                orderIdInput.value = orderId;
                form.appendChild(orderIdInput);

                document.body.appendChild(form);
                form.submit();
            }
        }

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

        // Function to apply filters (on status change, priority change)
        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 modals when clicking outside of the modal content
        window.onclick = function(event) {
            const deleteModal = document.getElementById('deleteModal');
            const statusModal = document.getElementById('statusModal');
            if (event.target == deleteModal) {
                deleteModal.classList.add('hidden');
            }
            if (event.target == statusModal) {
                statusModal.classList.add('hidden');
            }
        }
    </script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>) it shows this (Address:
Deprecated: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in /home/u406552082/domains/longevacare.com/public_html/kaakalia/public/orders/view_orders.php on line 800
) and if there no address,,, don't add address, and if there addresss add addressa and type full codes