i want to change edit order codes design to new desgin (<?php
// public/orders/edit_order.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';

// Initialize success and error variables
$success = '';
$error = '';

// Retrieve and sanitize the order ID from GET parameters
$order_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Redirect if no valid order ID is provided
if ($order_id <= 0) {
    header("Location: view_orders.php");
    exit();
}

// Fetch order details along with customer information
$order_sql = "SELECT o.*, c.name AS customer_name, c.contact AS customer_contact, c.delivery_address 
              FROM orders o 
              JOIN customers c ON o.customer_id = c.id 
              WHERE o.id = ? LIMIT 1";
$order_stmt = $conn->prepare($order_sql);
$order_stmt->bind_param("i", $order_id);
$order_stmt->execute();
$order_result = $order_stmt->get_result();

if ($order_result->num_rows != 1) {
    header("Location: view_orders.php");
    exit();
}

$order = $order_result->fetch_assoc();
$order_stmt->close();

// Fetch existing order items
$order_items_sql = "SELECT oi.*, p.name AS product_name, p.size, p.price 
                   FROM order_items oi 
                   JOIN products p ON oi.product_id = p.id 
                   WHERE oi.order_id = ?";
$order_items_stmt = $conn->prepare($order_items_sql);
$order_items_stmt->bind_param("i", $order_id);
$order_items_stmt->execute();
$order_items_result = $order_items_stmt->get_result();
$order_items = [];
while ($item = $order_items_result->fetch_assoc()) {
    $order_items[] = $item;
}
$order_items_stmt->close();

// Fetch products for selection
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);

// Handle form submission for updating the order
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Retrieve and sanitize form inputs
    $customer_name = trim($_POST['customer_name']);
    $contact = trim($_POST['contact']);
    $delivery_address = trim($_POST['delivery_address']);
    $status = isset($_POST['status']) ? trim($_POST['status']) : 'Pending';
    $priority = isset($_POST['priority']) ? trim($_POST['priority']) : 'Normal';
    $delivery_datetime = isset($_POST['delivery_datetime']) && !empty($_POST['delivery_datetime']) ? trim($_POST['delivery_datetime']) : null;
    $delivery_date = isset($_POST['delivery_date']) && !empty($_POST['delivery_date']) ? trim($_POST['delivery_date']) : null;

    // Handle existing order items
    $existing_item_ids = isset($_POST['existing_item_id']) ? $_POST['existing_item_id'] : [];
    $product_ids = isset($_POST['product_id']) ? $_POST['product_id'] : [];
    $quantities = isset($_POST['quantity']) ? $_POST['quantity'] : [];
    $packaging_preferences = isset($_POST['packaging_preferences']) ? $_POST['packaging_preferences'] : [];
    $discount_percentages = isset($_POST['discount_percentage']) ? $_POST['discount_percentage'] : [];
    $discount_reasons = isset($_POST['discount_reason']) ? $_POST['discount_reason'] : [];

    // Handle new order items
    $new_product_ids = isset($_POST['new_product_id']) ? $_POST['new_product_id'] : [];
    $new_quantities = isset($_POST['new_quantity']) ? $_POST['new_quantity'] : [];
    $new_packaging_preferences = isset($_POST['new_packaging_preferences']) ? $_POST['new_packaging_preferences'] : [];
    $new_discount_percentages = isset($_POST['new_discount_percentage']) ? $_POST['new_discount_percentage'] : [];
    $new_discount_reasons = isset($_POST['new_discount_reason']) ? $_POST['new_discount_reason'] : [];

    // Basic validation
    if (empty($customer_name)) {
        $error = "Customer name is required.";
    } elseif (empty($status)) {
        $error = "Order status is required.";
    } elseif (empty($priority)) {
        $error = "Order priority is required.";
    } elseif (($existing_item_ids && (empty($product_ids) || empty($quantities))) && (empty($new_product_ids))) {
        $error = "At least one product must be selected.";
    } else {
        // Validate each existing product entry
        foreach ($product_ids as $index => $pid) {
            if (empty($pid)) {
                $error = "Product selection is required for all existing items.";
                break;
            }
            if (intval($quantities[$index]) <= 0) {
                $error = "Quantity must be at least 1 for all existing items.";
                break;
            }
            if ($discount_percentages[$index] !== '' && (floatval($discount_percentages[$index]) < 0 || floatval($discount_percentages[$index]) > 100)) {
                $error = "Discount percentage must be between 0 and 100.";
                break;
            }
        }

        // Validate new product entries
        foreach ($new_product_ids as $index => $pid) {
            if (!empty($pid)) {
                if (intval($new_quantities[$index]) <= 0) {
                    $error = "Quantity must be at least 1 for all new items.";
                    break;
                }
                if ($new_discount_percentages[$index] !== '' && (floatval($new_discount_percentages[$index]) < 0 || floatval($new_discount_percentages[$index]) > 100)) {
                    $error = "Discount percentage must be between 0 and 100 for all new items.";
                    break;
                }
            }
        }

        if ($delivery_datetime && !preg_match("/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/", $delivery_datetime)) {
            $error = "Invalid delivery date and time format.";
        } elseif ($delivery_datetime && strtotime(str_replace('T', ' ', $delivery_datetime)) < strtotime(date('Y-m-d H:i'))) {
            $error = "Delivery date and time cannot be in the past.";
        }

        if ($delivery_date && !preg_match("/^\d{4}-\d{2}-\d{2}$/", $delivery_date)) {
            $error = "Invalid delivery date format.";
        }
    }

    if (empty($error)) {
        // Start transaction
        $conn->begin_transaction();

        try {
            // Update customer details
            $stmt = $conn->prepare("UPDATE customers SET name = ?, contact = ?, delivery_address = ? WHERE id = ?");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }
            $stmt->bind_param("sssi", $customer_name, $contact, $delivery_address, $order['customer_id']);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $stmt->close();

            // Update orders table
            $stmt = $conn->prepare("UPDATE orders SET status = ?, priority = ?, delivery_datetime = ?, delivery_date = ? WHERE id = ?");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }
            $stmt->bind_param("ssssi", $status, $priority, $delivery_datetime, $delivery_date, $order_id);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $stmt->close();

            // Update existing order items
            foreach ($existing_item_ids as $index => $item_id) {
                $item_id = intval($item_id);
                $pid = intval($product_ids[$index]);
                $qty = intval($quantities[$index]);
                $pack_pref = trim($packaging_preferences[$index]);
                $discount_pct = $discount_percentages[$index] !== '' ? floatval($discount_percentages[$index]) : 0.00;
                $discount_rsn = trim($discount_reasons[$index]);

                $stmt = $conn->prepare("UPDATE order_items SET product_id = ?, quantity = ?, packaging_preferences = ?, discount_percentage = ?, discount_reason = ? WHERE id = ?");
                if (!$stmt) {
                    throw new Exception("Prepare statement failed: " . $conn->error);
                }
                $stmt->bind_param("iisdsi", $pid, $qty, $pack_pref, $discount_pct, $discount_rsn, $item_id);
                if (!$stmt->execute()) {
                    throw new Exception("Execute failed: " . $stmt->error);
                }
                $stmt->close();
            }

            // Insert new order items
            $stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, packaging_preferences, discount_percentage, discount_reason) VALUES (?, ?, ?, ?, ?, ?)");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }

            for ($i = 0; $i < count($new_product_ids); $i++) {
                $new_pid = intval($new_product_ids[$i]);
                $new_qty = intval($new_quantities[$i]);
                $new_pack_pref = trim($new_packaging_preferences[$i]);
                $new_discount_pct = $new_discount_percentages[$i] !== '' ? floatval($new_discount_percentages[$i]) : 0.00;
                $new_discount_rsn = trim($new_discount_reasons[$i]);

                if (!empty($new_pid)) {
                    $stmt->bind_param("iiisds", $order_id, $new_pid, $new_qty, $new_pack_pref, $new_discount_pct, $new_discount_rsn);
                    if (!$stmt->execute()) {
                        throw new Exception("Execute failed: " . $stmt->error);
                    }
                }
            }
            $stmt->close();

            // Commit transaction
            $conn->commit();

            $success = "Order updated successfully!";

            // Refresh order data
            // Fetch updated order items
            $order_items_sql = "SELECT oi.*, p.name AS product_name, p.size, p.price 
                               FROM order_items oi 
                               JOIN products p ON oi.product_id = p.id 
                               WHERE oi.order_id = ?";
            $order_items_stmt = $conn->prepare($order_items_sql);
            $order_items_stmt->bind_param("i", $order_id);
            $order_items_stmt->execute();
            $order_items_result = $order_items_stmt->get_result();
            $order_items = [];
            while ($item = $order_items_result->fetch_assoc()) {
                $order_items[] = $item;
            }
            $order_items_stmt->close();
        } catch (Exception $e) {
            // Rollback transaction
            $conn->rollback();
            $error = "Error updating order: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Order #<?= htmlspecialchars($order_id) ?> - 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="../../public/bootstrap/css/bootstrap.min.css">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Embedded Custom Styles -->
    <style>
        /* ---------------------------------------------------
           1. CSS Variables for Consistent Design
        ---------------------------------------------------- */
        :root {
            --dark-gray: #333333; /* Header and Footer Background */
            --primary-color: #b78d67; /* Buttons and Highlights */
            --secondary-color: #515151; /* Text and Icons */
            --success-color: #06D6A0; /* Success Messages */
            --error-color: #EF476F; /* Error Messages */
            --white: #FFFFFF;
            --background-gradient: linear-gradient(to bottom, #f5f7fa, #c3cfe2);
            --divider-color: #FFD166;
            --input-background: #f9f9f9;
            --border-color: #ccc;
            --hover-shadow: rgba(0, 0, 0, 0.1);
            --transition-speed: 0.3s;
        }

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

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

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

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

        /* ---------------------------------------------------
           4. Container Styles
        ---------------------------------------------------- */
        .container-custom {
            max-width: 1000px;
            margin: auto;
            background-color: var(--white);
            padding: 30px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            box-shadow: 0 4px 6px var(--hover-shadow);
        }

        /* ---------------------------------------------------
           5. Success and Error Alerts
        ---------------------------------------------------- */
        .alert-custom {
            border-radius: 8px;
            padding: 15px 20px;
            margin-bottom: 20px;
            text-align: center;
        }

        .alert-success-custom {
            background-color: var(--success-color);
            color: var(--white);
        }

        .alert-danger-custom {
            background-color: var(--error-color);
            color: var(--white);
        }

        /* ---------------------------------------------------
           6. Form Styles
        ---------------------------------------------------- */
        .form-label {
            font-weight: 600;
            color: var(--secondary-color);
        }

        .form-control {
            background-color: var(--input-background);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            padding: 10px 15px;
            transition: border-color var(--transition-speed), box-shadow var(--transition-speed);
        }

        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 5px rgba(182, 141, 103, 0.5);
            background-color: var(--white);
        }

        .btn-primary-custom {
            background-color: var(--primary-color);
            border: none;
            transition: background-color var(--transition-speed), transform var(--transition-speed);
        }

        .btn-primary-custom:hover {
            background-color: #a77c55;
            transform: scale(1.05);
        }

        .btn-secondary-custom {
            background-color: #6c757d;
            border: none;
            transition: background-color var(--transition-speed), transform var(--transition-speed);
        }

        .btn-secondary-custom:hover {
            background-color: #5a6268;
            transform: scale(1.05);
        }

        .remove-product-button {
            background-color: var(--error-color);
            color: var(--white);
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            cursor: pointer;
            transition: background-color var(--transition-speed), transform var(--transition-speed);
        }

        .remove-product-button:hover {
            background-color: #d43f50;
            transform: scale(1.1);
        }

        /* ---------------------------------------------------
           7. 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;
        }

        /* ---------------------------------------------------
           8. Responsive Design Enhancements
        ---------------------------------------------------- */
        @media (max-width: 768px) {
            .container-custom {
                padding: 20px;
            }

            .btn {
                width: 100%;
                margin-bottom: 10px;
            }
        }

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

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

            .form-label {
                font-size: 14px;
            }

            .form-control {
                padding: 8px 12px;
            }

            .btn {
                font-size: 14px;
                padding: 10px 0;
            }

            .footer {
                font-size: 12px;
            }
        }
    </style>

    <!-- Additional JavaScript for dynamic product addition -->
    <script>
        function addOrderItemRow() {
            const orderItemsContainer = document.getElementById('order-items-container');
            const itemCount = orderItemsContainer.children.length;

            const orderItemRow = document.createElement('div');
            orderItemRow.className = 'order-item-row border p-3 mb-3';
            orderItemRow.innerHTML = `
                <div class="row">
                    <div class="col-md-4">
                        <label class="form-label" for="new_product_id_${itemCount}">Product <span class="text-danger">*</span></label>
                        <select name="new_product_id[]" id="new_product_id_${itemCount}" class="form-control" required>
                            <option value="">Select Product</option>
                            <?php
                            // Reset the products_result pointer
                            $products_result->data_seek(0);
                            while($product = $products_result->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($product['id']) ?>">
                                    <?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label" for="new_quantity_${itemCount}">Quantity <span class="text-danger">*</span></label>
                        <input type="number" name="new_quantity[]" id="new_quantity_${itemCount}" class="form-control" min="1" value="1" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label" for="new_packaging_preferences_${itemCount}">Packaging Preferences</label>
                        <input type="text" name="new_packaging_preferences[]" id="new_packaging_preferences_${itemCount}" class="form-control" placeholder="e.g., Gift Wrap">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label" for="new_discount_percentage_${itemCount}">Discount (%)</label>
                        <input type="number" name="new_discount_percentage[]" id="new_discount_percentage_${itemCount}" class="form-control" min="0" max="100" step="0.01" value="0.00">
                    </div>
                    <div class="col-md-1 d-flex align-items-end">
                        <button type="button" class="remove-product-button" onclick="removeOrderItemRow(this)" title="Remove Product">X</button>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-12">
                        <label class="form-label" for="new_discount_reason_${itemCount}">Discount Reason</label>
                        <input type="text" name="new_discount_reason[]" id="new_discount_reason_${itemCount}" class="form-control" placeholder="e.g., Seasonal Sale">
                    </div>
                </div>
            `;
            orderItemsContainer.appendChild(orderItemRow);
        }

        function removeOrderItemRow(button) {
            const orderItemRow = button.closest('.order-item-row');
            orderItemRow.remove();
        }

        function removeExistingOrderItemRow(button) {
            const orderItemRow = button.closest('.order-item-row');
            // Optionally, you can mark the item for deletion or remove it directly
            // For simplicity, we'll remove it directly
            orderItemRow.remove();
            // To handle deletion in backend, you'd need to track removed IDs and delete them from database
            // This requires additional implementation
        }

        // Add initial new order item row on page load
        document.addEventListener('DOMContentLoaded', function() {
            // Uncomment the line below if you want to have an initial new product row
            // addOrderItemRow();
        });
    </script>
</head>
<body>

    <!-- Header -->
    <div class="header">
        <h1>Kaak Alia Management System</h1>
    </div>

    <!-- Container -->
    <div class="container-custom">
        <h3 class="mb-4">Edit Order #<?= htmlspecialchars($order_id) ?></h3>
        
        <!-- Display Success or Error Messages -->
        <?php if (!empty($success)): ?>
            <div class="alert alert-custom alert-success-custom"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <div class="alert alert-custom alert-danger-custom"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <!-- Edit Order Form -->
        <form method="POST" action="">
            <!-- Customer Details -->
            <div class="mb-4">
                <h5>Customer Details</h5>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="customer_name">Customer Name <span class="text-danger">*</span></label>
                        <input type="text" id="customer_name" name="customer_name" class="form-control" 
                               value="<?= htmlspecialchars(isset($_POST['customer_name']) ? $_POST['customer_name'] : $order['customer_name']) ?>" 
                               required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label" for="contact">Contact</label>
                        <input type="text" id="contact" name="contact" class="form-control" 
                               value="<?= htmlspecialchars(isset($_POST['contact']) ? $_POST['contact'] : $order['customer_contact']) ?>">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label" for="delivery_address">Delivery Address</label>
                    <textarea id="delivery_address" name="delivery_address" class="form-control" rows="3"><?= htmlspecialchars(isset($_POST['delivery_address']) ? $_POST['delivery_address'] : $order['delivery_address']) ?></textarea>
                </div>
            </div>
            <hr>
            <!-- Order Details -->
            <div class="mb-4">
                <h5>Order Details</h5>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label" for="status">Status <span class="text-danger">*</span></label>
                        <select name="status" id="status" class="form-control" required>
                            <option value="">Select Status</option>
                            <option value="Pending" <?= (isset($_POST['status']) ? $_POST['status'] : $order['status']) == 'Pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="In Progress" <?= (isset($_POST['status']) ? $_POST['status'] : $order['status']) == 'In Progress' ? 'selected' : '' ?>>In Progress</option>
                            <option value="Completed" <?= (isset($_POST['status']) ? $_POST['status'] : $order['status']) == 'Completed' ? 'selected' : '' ?>>Completed</option>
                            <option value="Delivered" <?= (isset($_POST['status']) ? $_POST['status'] : $order['status']) == 'Delivered' ? 'selected' : '' ?>>Delivered</option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label" for="priority">Priority <span class="text-danger">*</span></label>
                        <select name="priority" id="priority" class="form-control" required>
                            <option value="">Select Priority</option>
                            <option value="Normal" <?= (isset($_POST['priority']) ? $_POST['priority'] : $order['priority']) == 'Normal' ? 'selected' : '' ?>>Normal</option>
                            <option value="Important" <?= (isset($_POST['priority']) ? $_POST['priority'] : $order['priority']) == 'Important' ? 'selected' : '' ?>>Important</option>
                            <option value="Quick" <?= (isset($_POST['priority']) ? $_POST['priority'] : $order['priority']) == 'Quick' ? 'selected' : '' ?>>Quick</option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label" for="delivery_datetime">Delivery Date and Time</label>
                        <input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="form-control" 
                               value="<?= isset($_POST['delivery_datetime']) ? htmlspecialchars($_POST['delivery_datetime']) : ($order['delivery_datetime'] ? date('Y-m-d\TH:i', strtotime($order['delivery_datetime'])) : '') ?>">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label" for="delivery_date">Delivery Date</label>
                        <input type="date" id="delivery_date" name="delivery_date" class="form-control" 
                               value="<?= isset($_POST['delivery_date']) ? htmlspecialchars($_POST['delivery_date']) : ($order['delivery_date'] ? date('Y-m-d', strtotime($order['delivery_date'])) : '') ?>">
                    </div>
                </div>
            </div>
            <hr>
            <!-- Existing Order Items -->
            <div class="mb-4">
                <h5>Existing Order Items</h5>
                <div id="existing-order-items-container">
                    <?php foreach ($order_items as $item): ?>
                        <div class="order-item-row border p-3 mb-3">
                            <input type="hidden" name="existing_item_id[]" value="<?= htmlspecialchars($item['id']) ?>">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label" for="product_id_<?= htmlspecialchars($item['id']) ?>">Product <span class="text-danger">*</span></label>
                                    <select name="product_id[]" id="product_id_<?= htmlspecialchars($item['id']) ?>" class="form-control" required>
                                        <option value="">Select Product</option>
                                        <?php
                                        // Reset the products_result pointer
                                        $products_result->data_seek(0);
                                        while($product = $products_result->fetch_assoc()): ?>
                                            <option value="<?= htmlspecialchars($product['id']) ?>" <?= ($product['id'] == $item['product_id']) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label class="form-label" for="quantity_<?= htmlspecialchars($item['id']) ?>">Quantity <span class="text-danger">*</span></label>
                                    <input type="number" name="quantity[]" id="quantity_<?= htmlspecialchars($item['id']) ?>" class="form-control" min="1" value="<?= htmlspecialchars($item['quantity']) ?>" required>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label" for="packaging_preferences_<?= htmlspecialchars($item['id']) ?>">Packaging Preferences</label>
                                    <input type="text" name="packaging_preferences[]" id="packaging_preferences_<?= htmlspecialchars($item['id']) ?>" class="form-control" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($item['packaging_preferences']) ?>">
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label class="form-label" for="discount_percentage_<?= htmlspecialchars($item['id']) ?>">Discount (%)</label>
                                    <input type="number" name="discount_percentage[]" id="discount_percentage_<?= htmlspecialchars($item['id']) ?>" class="form-control" min="0" max="100" step="0.01" value="<?= htmlspecialchars($item['discount_percentage']) ?>">
                                </div>
                                <div class="col-md-1 d-flex align-items-end">
                                    <button type="button" class="remove-product-button" onclick="removeExistingOrderItemRow(this)" title="Remove Product">X</button>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <label class="form-label" for="discount_reason_<?= htmlspecialchars($item['id']) ?>">Discount Reason</label>
                                    <input type="text" name="discount_reason[]" id="discount_reason_<?= htmlspecialchars($item['id']) ?>" class="form-control" placeholder="e.g., Seasonal Sale" value="<?= htmlspecialchars($item['discount_reason']) ?>">
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <hr>
            <!-- Add New Order Items -->
            <div class="mb-4">
                <h5>Add New Order Items</h5>
                <div id="order-items-container">
                    <!-- New Order Item Rows will be added here -->
                </div>
                <button type="button" class="btn btn-secondary mt-2" onclick="addOrderItemRow()">Add Another Product</button>
            </div>
            <!-- Submit Buttons -->
            <div class="d-flex justify-content-between mt-4">
                <button type="submit" class="btn btn-primary-custom">Update Order</button>
                <a href="view_orders.php" class="btn btn-secondary-custom">Cancel</a>
            </div>
        </form>
    </div>

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

    <!-- Bootstrap JS Bundle -->
    <script src="../../public/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>) and this (refine the design to make it modern, clean, and professional while maintaining a subtle, sophisticated hint of the bakery theme. This approach will result in an interface that feels both contemporary and warm, ideal for an upscale online bakery platform.

1. Background and Layout
Background Color: Use a crisp white background for the entire interface. This creates a professional, high-end look and allows the products to be the main focus.
Card and Table Shadows: Implement minimal shadows on product cards and tables for a sleek "floating" effect. This adds depth without overcrowding the design, keeping it light and professional.
Padding and Spacing: Increase spacing around elements to create an airy layout, making the interface feel open and reducing visual clutter.
2. Filters Section
Filter Buttons: Use pill-shaped filter buttons in a neutral palette, like cool greys or soft charcoal, with a gradient accent. This keeps the design sleek and modern while adding a subtle highlight.
Date Pickers and Dropdowns: Use outlined fields with a thin grey border. When clicked, the border color changes to a soft accent color (e.g., light grey or teal) to enhance interactivity.
3. Search Bar
Search Field Styling: Incorporate a modern search bar with a grey border and a magnifying glass icon inside the field for usability. On focus, the border color should change to a darker grey, creating a professional highlight effect.
Search Button: Use a rounded, solid button in a soft grey or cool-toned accent color. Adding a slight shadow or a darkened border on hover makes it feel interactive while remaining understated.
4. Product Display and Table
Column Headers: Use a sans-serif font like "Inter" or "Roboto" in a slightly larger size and bold weight for headers. Style headers with a very light grey background and a single underline to separate them from the content rows, giving a minimalist appearance.
Row Backgrounds: Use alternating light grey and white backgrounds for rows to improve readability without adding visual noise.
Product Details: Arrange product details in a clean, vertical layout within each cell. This could include the product name, price, and description, each on a new line in a smaller, lighter font.
Status Badges: Design status labels with modern colors and rounded edges. For example:
Available: A muted green label with white text.
Out of Stock: Light grey with dark text to indicate unavailability in a subtle way.
New Arrival: Soft blue with white text to add a touch of vibrancy without overpowering the layout.
5. Action Buttons
Button Colors and Layout: Use clean, solid-colored buttons with slight gradients for emphasis, keeping the colors muted to match the professional tone:
Add to Cart: Soft grey-blue or charcoal to fit the modern look.
View Details: Neutral grey with a slight hover effect, like darkening the button or adding a shadow.
Remove: Soft, muted red for "Remove" to indicate caution without looking aggressive.
Button Shape and Iconography: Use rounded buttons with slight shadowing to give them a subtle, floating effect. Small icons next to the text (e.g., shopping cart icon for "Add to Cart") can add clarity to the buttons without adding too much visual weight.
6. Typography
Font Choice: Choose a modern sans-serif font like "Inter," "Roboto," or "Open Sans" to keep the text clean and professional. Use different weights to establish hierarchy, such as bold for product names and regular or light for details.
Hierarchy and Emphasis: Increase font sizes for key information like product names and headers. Keep secondary details in a smaller, lighter font for contrast and readability.
7. Color Palette
Primary Colors: White and light grey for a clean, modern background. Dark grey or charcoal can be used for text to maintain high contrast.
Accent Colors: Muted blues, greens, and a touch of soft red for status indicators or subtle highlights on buttons.
Text Colors: Dark grey or black for primary text for readability, with lighter shades of grey for secondary information.
8. Image and Visuals
Product Images: Use high-resolution images with a subtle shadow around each to give them a polished look. Keeping the images well-lit and professionally styled adds to the upscale aesthetic.
Minimal Decorative Elements: For a more modern and professional look, limit decorative elements. Instead, rely on clean lines, soft shadows, and whitespace for visual structure.
9. Interactive Elements and Transitions
Hover and Focus Effects: Add subtle transitions when hovering over interactive elements like buttons and filter options. For instance, slightly darken the color or add a shadow to indicate interactivity.
Load Animations: When loading new products or applying filters, consider adding a minimalist fade-in effect to maintain a smooth, modern user experience.
10. Product Highlights and Labels
Featured Products or Discounts: Use a sleek "badge" design in a soft accent color like muted teal or grey-blue for featured products, bestsellers, or discounts. Keep the text small and centered for a refined look.
This design approach will create a clean, modern UI that feels both professional and sophisticated, with a hint of bakery warmth through subtle accent colors. By using minimalistic layouts, rounded buttons, and a balanced color palette, the interface will look polished and user-friendly, ideal for an online bakery platform focused on a professional shopping experience.) and use this style (        :root {
            /* Primary Colors */
            --background-color: #FFFFFF; /* Crisp White */
            --light-grey: #F5F5F5;
            --medium-grey: #CCCCCC;
            --dark-grey: #333333;
            --charcoal: #374151; /* Updated to requested color */

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

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

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

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

            /* Status Badge Colors */
            --badge-pending: #FFD166;
            --badge-in-progress: #6A4C93;
            --badge-completed: #4CAF50;
            --badge-delivered: #20B2AA;
        }
) and type full codes and change this codes too (<?php
// public/orders/view_order_customer.php

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

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

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

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

// Initialize variables for messages
$success_message = '';
$error_message = '';

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

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

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

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

// Handle Status Update Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    // Sanitize and validate inputs
    $new_status = isset($_POST['status']) ? sanitize_input($_POST['status']) : '';
    $allowed_statuses = ['Pending', 'Completed', 'Delivered']; // Removed 'In Progress'
    
    if (in_array($new_status, $allowed_statuses)) {
        // Prepare SQL to update status
        $update_sql = "UPDATE orders SET status = ? WHERE id = ?";
        $update_stmt = $conn->prepare($update_sql);
        if ($update_stmt) {
            $update_stmt->bind_param("si", $new_status, $order_id);
            if ($update_stmt->execute()) {
                $success_message = "Order status updated successfully to '" . htmlspecialchars($new_status) . "'.";
                $order['status'] = $new_status; // Update the local variable to reflect change
            } else {
                $error_message = "Failed to update order status. Please try again.";
            }
            $update_stmt->close();
        } else {
            $error_message = "Database error: " . htmlspecialchars($conn->error);
        }
    } else {
        $error_message = "Invalid status selected.";
    }
}

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

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

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

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

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

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

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

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

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

        .container-body {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

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

        /* ---------------------------------------------------
           3. Welcome Section
        ---------------------------------------------------- */
        .welcome-section {
            background-color: var(--white);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            padding: 40px;
            text-align: center;
            margin-bottom: 40px;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .welcome-section h3 {
            font-size: 36px;
            color: var(--main-text);
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .welcome-section h3 .bi {
            margin-right: 10px;
            color: #FF6347; /* Tomato color */
            font-size: 40px;
        }

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

        /* ---------------------------------------------------
           4. Enhanced Order Information Section
        ---------------------------------------------------- */
        .order-info-section {
            background-color: var(--white);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            padding: 30px;
            margin-bottom: 40px;
            display: flex;
            flex-direction: column;
        }

        .order-info-header {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
        }

        .order-info-header .bi {
            font-size: 36px;
            color: #ff4d4d;
            margin-right: 15px;
        }

        .order-info-header h4 {
            font-size: 32px;
            color: var(--main-text);
            font-weight: bold;
        }

        .order-info-content {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }

        .order-info-item {
            width: 50%;
            display: flex;
            align-items: center;
        }

        .order-info-item .bi {
            font-size: 28px;
            color: #0d6efd; /* Changed to a distinct color */
            margin-right: 12px;
        }

        .order-info-item .info-text {
            font-size: 22px;
            color: var(--main-text);
            font-weight: 600;
        }

        /* ---------------------------------------------------
           5. Product Summary Section
        ---------------------------------------------------- */
        .product-summary-section {
            background-color: #ffe6e6; /* Light red background */
            border-left: 6px solid #ff4d4d; /* Red border */
            border-radius: 8px;
            padding: 25px;
            margin-bottom: 40px;
            box-shadow: 0 4px 12px rgba(255, 77, 77, 0.15);
        }

        .product-summary-section h4 {
            font-size: 28px;
            color: #cc0000; /* Darker red */
            margin-bottom: 25px;
            display: flex;
            align-items: center;
        }

        .product-summary-section h4 .bi {
            margin-right: 10px;
            color: #ff4d4d;
            font-size: 32px;
        }

        .product-summary-list {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }

        .product-item {
            background-color: #fff;
            border: 1px solid #ffcccc;
            border-radius: 6px;
            padding: 20px;
            width: calc(33.333% - 13.333px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .product-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
        }

        .product-item .bi {
            font-size: 28px;
            color: #ff4d4d;
            margin-right: 15px;
        }

        .product-details {
            flex-grow: 1;
        }

        .product-details p {
            font-size: 20px;
            margin-bottom: 8px;
            color: var(--main-text);
        }

        .product-details p strong {
            color: #cc0000;
        }

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

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

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

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

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

        .recent-orders-section th {
            background-color: #e0e0e0; /* Light grey instead of blue */
            color: var(--main-text);
            font-weight: bold;
            position: sticky;
            top: 0;
            z-index: 1;
        }

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

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

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

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

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

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

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

        .total-section p strong {
            font-size: 24px;
            color: #0d6efd;
        }

        /* ---------------------------------------------------
           8. Action Buttons
        ---------------------------------------------------- */
        .action-buttons {
            display: flex;
            gap: 20px;
            justify-content: flex-end;
            margin-bottom: 50px;
            flex-wrap: wrap;
        }

        .action-button {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 15px 25px;
            font-size: 20px;
            font-weight: bold;
            color: var(--white);
            border: none;
            border-radius: 10px;
            cursor: pointer;
            transition: transform 0.3s, box-shadow 0.3s;
            text-decoration: none;
            min-width: 220px;
            text-align: center;
        }

        .action-button.print-order { background-color: var(--button-view-orders); }
        .action-button.edit-order { background-color: var(--button-add-order); }
        .action-button.copy-order { background-color: #FF6347; /* Tomato color */ }

        .action-button:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 16px var(--hover-shadow);
        }

        .action-button .bi {
            margin-right: 10px;
            font-size: 24px;
        }

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

        /* ---------------------------------------------------
           10. Responsive Design Enhancements
        ---------------------------------------------------- */
        @media (max-width: 992px) {
            .product-item {
                width: calc(50% - 10px);
            }

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

            .order-info-header h4 {
                font-size: 28px;
            }

            .order-info-item .bi {
                font-size: 24px;
            }

            .order-info-item .info-text {
                font-size: 20px;
            }

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

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

            .action-button {
                font-size: 18px;
                padding: 12px 20px;
                min-width: 200px;
            }

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

            /* Adjust Product Summary Items */
            .product-item {
                width: 100%;
            }
        }

        @media (max-width: 576px) {
            .welcome-section h3 {
                font-size: 28px;
            }

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

            .order-info-header h4 {
                font-size: 26px;
            }

            .order-info-item .bi {
                font-size: 22px;
            }

            .order-info-item .info-text {
                font-size: 18px;
            }

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

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

            .action-button {
                font-size: 16px;
                padding: 10px 15px;
                min-width: 180px;
            }

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

            /* Adjust Product Summary Items */
            .product-item {
                width: 100%;
            }
        }
    </style>

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

        function copyOrderDetails() {
            // Gather the required information
            const deliveryDateTime = document.querySelector('.delivery-date-time').innerText.replace('Delivery Date & Time: ', '');
            const deliveryAddress = document.querySelector('.delivery-address').innerText.replace('Delivery Address: ', '');
            const contact = document.querySelector('.contact-info').innerText.replace('Contact: ', '');

            let productSummary = '';
            document.querySelectorAll('.product-summary-item').forEach(function(item) {
                const productName = item.querySelector('.product-name').innerText;
                const productSize = item.querySelector('.product-size').innerText.replace('Size: ', '');
                const productQuantityText = item.querySelector('.product-quantity').innerText.replace('Quantity: ', '');
                const productQuantity = parseInt(productQuantityText);

                if (!isNaN(productQuantity) && productQuantity > 1) {
                    productSummary += `* Item: ${productQuantity} Boxes, Size: ${productSize} - ${productName}\n`;
                } else if (!isNaN(productQuantity) && productQuantity === 1) {
                    productSummary += `* Item: ${productQuantity} Box, Size: ${productSize} - ${productName}\n`;
                }
            });

            // Construct the formatted text
            const formattedText = `🔴 Order Details 🔴
🔸 Delivery Date & Time: ${deliveryDateTime}
${productSummary}🔸 Delivery Address: ${deliveryAddress}
🔸 Contact Number: ${contact}`;

            // Copy to clipboard using Clipboard API
            navigator.clipboard.writeText(formattedText).then(() => {
                alert('Order details copied to clipboard!');
            }).catch(err => {
                alert('Failed to copy: ' + err);
            });
        }
    </script>
</head>
<body>
    <!-- Header Already Included via header.php -->

    <main class='container-body'>
        <!-- Welcome Section -->
        <div class="welcome-section">
            <h3><i class="bi bi-box-seam-fill"></i> Order #<?= htmlspecialchars($order['order_id']) ?></h3>
            <hr>
            <!-- Copy Info Block Above HR -->
            <button class="btn btn-sm btn-outline-secondary mt-3" onclick="copyOrderDetails()">
                <i class="bi bi-clipboard-fill"></i> Copy Order Info
            </button>
        </div>

        <!-- Display Success or Error Messages -->
        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?= htmlspecialchars($success_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?= htmlspecialchars($error_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Product Summary Section -->
        <div class="product-summary-section">
            <h4><i class="bi bi-bag-fill"></i> Product Summary</h4>
            <div class="product-summary-list">
                <?php foreach ($order_items as $item): ?>
                    <?php if (strtolower($item['packaging_preferences']) !== 'n/a'): // Only display if Packaging Preferences is not 'N/A' ?>
                        <div class="product-item d-flex align-items-center product-summary-item">
                            <i class="bi bi-box-seam-fill"></i>
                            <div class="product-details">
                                <p class="product-name"><strong><?= htmlspecialchars($item['product_name']) ?></strong></p>
                                <p class="product-size"><i class="bi bi-arrows-angle-contract"></i> Size: <?= htmlspecialchars($item['product_size']) ?></p>
                                <p class="product-quantity"><i class="bi bi-people-fill"></i> Quantity: <?= htmlspecialchars($item['quantity']) ?></p>
                                <p class="packaging-preferences"><i class="bi bi-box-seam-fill"></i> Packaging: <?= htmlspecialchars($item['packaging_preferences']) ?></p>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="product-item d-flex align-items-center product-summary-item">
                            <i class="bi bi-box-seam-fill"></i>
                            <div class="product-details">
                                <p class="product-name"><strong><?= htmlspecialchars($item['product_name']) ?></strong></p>
                                <p class="product-size"><i class="bi bi-arrows-angle-contract"></i> Size: <?= htmlspecialchars($item['product_size']) ?></p>
                                <p class="product-quantity"><i class="bi bi-people-fill"></i> Quantity: <?= htmlspecialchars($item['quantity']) ?></p>
                                <!-- Packaging Preferences not displayed if 'N/A' -->
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Order Information Section -->
        <div class="order-info-section">
            <div class="order-info-header">
                <i class="bi bi-info-circle-fill"></i>
                <h4>Order Information</h4>
            </div>
            <div class="order-info-content">
                <!-- Status -->
                <div class="order-info-item">
                    <i class="bi bi-tag-fill"></i>
                    <div class="info-text">
                        <form method="POST" action="" class="d-flex align-items-center">
                            <strong>Status:</strong>&nbsp;
                            <select name="status" class="form-select form-select-lg ms-2 me-2 px-3 py-2 status-dropdown" style="width: auto;" aria-label="Order Status">
                                <?php
                                    $statuses = ['Pending', 'Completed', 'Delivered']; // Removed 'In Progress'
                                    foreach ($statuses as $status) {
                                        $selected = ($order['status'] === $status) ? 'selected' : '';
                                        echo "<option value=\"{$status}\" {$selected}>{$status}</option>";
                                    }
                                ?>
                            </select>
                            <button type="submit" name="update_status" class="btn btn-primary btn-lg px-4">
                                <i class="bi bi-arrow-repeat"></i> Update
                            </button>
                        </form>
                    </div>
                </div>
                <!-- Priority -->
                <div class="order-info-item">
                    <i class="bi bi-exclamation-triangle-fill"></i>
                    <div class="info-text"><strong>Priority:</strong> <?= htmlspecialchars($order['priority']) ?></div>
                </div>
                <!-- Order Date -->
                <div class="order-info-item">
                    <i class="bi bi-calendar-event-fill"></i>
                    <div class="info-text"><strong>Order Date:</strong> <?= date("d M Y, h:i A", strtotime($order['order_date'])) ?></div>
                </div>
                <!-- Delivery Date & Time -->
                <div class="order-info-item">
                    <i class="bi bi-clock-fill"></i>
                    <div class="info-text delivery-date-time"><strong>Delivery Date & Time:</strong> <?= $order['delivery_datetime'] ? date("d M Y, h:i A", strtotime($order['delivery_datetime'])) : 'N/A' ?></div>
                </div>
                <!-- Customer Name -->
                <div class="order-info-item">
                    <i class="bi bi-person-fill"></i>
                    <div class="info-text"><strong>Customer Name:</strong> <?= htmlspecialchars($order['customer_name']) ?></div>
                </div>
                <!-- Contact -->
                <div class="order-info-item">
                    <i class="bi bi-whatsapp"></i>
                    <div class="info-text contact-info"><strong>Contact:</strong> 
                        <a href="<?= generate_whatsapp_link($order['contact']) ?>" target="_blank" class="d-inline-flex align-items-center text-decoration-none">
                            <i class="bi bi-whatsapp text-success"></i>
                            <span class="ms-2"><?= htmlspecialchars($order['contact']) ?></span>
                        </a>
                    </div>
                </div>
                <!-- Delivery Address -->
                <div class="order-info-item">
                    <i class="bi bi-geo-alt-fill"></i>
                    <div class="info-text delivery-address">
                        <strong>Delivery Address:</strong> <?= nl2br(htmlspecialchars($order['delivery_address'])) ?>
                        <button class="btn btn-sm btn-outline-secondary ms-3" onclick="copyOrderDetails()">
                            <i class="bi bi-clipboard-fill"></i> Copy Info
                        </button>
                    </div>
                </div>
            </div>
        </div>

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

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

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

        <!-- Footer -->
        <div class="footer">
            &copy; <?= date("Y") ?> Kaak Alia Bakery. All rights reserved.
        </div>
    </main>

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