based on this info database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 09, 2024 at 01:37 PM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `u406552082_kaakalia`
--

-- --------------------------------------------------------

--
-- Table structure for table `customers`
--

CREATE TABLE `customers` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `contact` varchar(50) DEFAULT NULL,
  `delivery_address` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `orders`
--

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `customer_id` int(11) NOT NULL,
  `status` enum('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
  `priority` enum('Normal','Important','Quick') DEFAULT 'Normal',
  `order_date` datetime DEFAULT current_timestamp(),
  `delivery_datetime` datetime DEFAULT NULL,
  `delivery_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `order_items`
--

CREATE TABLE `order_items` (
  `id` int(11) NOT NULL,
  `order_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL DEFAULT 1,
  `packaging_preferences` varchar(255) DEFAULT NULL,
  `discount_percentage` decimal(5,2) DEFAULT 0.00,
  `discount_reason` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `products`
--

CREATE TABLE `products` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `size` varchar(50) DEFAULT NULL,
  `price` decimal(10,2) NOT NULL,
  `category` varchar(50) DEFAULT NULL,
  `thumbnail` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `role` enum('admin','staff') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
  ADD PRIMARY KEY (`id`),
  ADD KEY `customer_id` (`customer_id`),
  ADD KEY `idx_orders_customer_id` (`customer_id`);

--
-- Indexes for table `order_items`
--
ALTER TABLE `order_items`
  ADD PRIMARY KEY (`id`),
  ADD KEY `order_id` (`order_id`),
  ADD KEY `product_id` (`product_id`),
  ADD KEY `idx_order_items_order_id` (`order_id`),
  ADD KEY `idx_order_items_product_id` (`product_id`);

--
-- Indexes for table `products`
--
ALTER TABLE `products`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `username` (`username`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `order_items`
--
ALTER TABLE `order_items`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
  ADD CONSTRAINT `fk_orders_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `order_items`
--
ALTER TABLE `order_items`
  ADD CONSTRAINT `fk_order_items_order_id` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_order_items_product_id` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `order_items_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;) and fix and update this codes (<?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
$order_sql = "SELECT * FROM orders WHERE 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 * FROM order_items WHERE 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']);
    $delivery_datetime = isset($_POST['delivery_datetime']) && !empty($_POST['delivery_datetime']) ? trim($_POST['delivery_datetime']) : null;
    $status = isset($_POST['status']) ? trim($_POST['status']) : 'Pending';

    // Handle multiple products
    $product_ids = isset($_POST['product_id']) ? $_POST['product_id'] : [];
    $quantities = isset($_POST['quantity']) ? $_POST['quantity'] : [];
    $packaging_preferences = isset($_POST['packaging_preferences']) ? $_POST['packaging_preferences'] : [];
    $existing_item_ids = isset($_POST['existing_item_id']) ? $_POST['existing_item_id'] : [];

    // Handle additional new products
    $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'] : [];

    // Basic validation
    if (empty($customer_name)) {
        $error = "Customer name is required.";
    } elseif ((empty($product_ids) && 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;
            }
        }

        // Validate new product entries
        foreach ($new_product_ids as $index => $pid) {
            if (!empty($pid) && intval($new_quantities[$index]) <= 0) {
                $error = "Quantity must be at least 1 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 (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's primary product
            $primary_product_id = intval($_POST['primary_product_id']);
            $primary_quantity = intval($_POST['primary_quantity']);
            $primary_packaging_preferences = trim($_POST['primary_packaging_preferences']);

            $stmt = $conn->prepare("UPDATE orders SET product_id = ?, quantity = ?, packaging_preferences = ?, status = ?, delivery_datetime = ? WHERE id = ?");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }
            $stmt->bind_param("iisssi", $primary_product_id, $primary_quantity, $primary_packaging_preferences, $status, $delivery_datetime, $order_id);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $stmt->close();

            // Update existing order items
            foreach ($product_ids as $index => $pid) {
                $item_id = intval($existing_item_ids[$index]);
                $pid = intval($pid);
                $qty = intval($quantities[$index]);
                $pack_pref = trim($packaging_preferences[$index]);

                $stmt = $conn->prepare("UPDATE order_items SET product_id = ?, quantity = ?, packaging_preferences = ? WHERE id = ?");
                if (!$stmt) {
                    throw new Exception("Prepare statement failed: " . $conn->error);
                }
                $stmt->bind_param("iisi", $pid, $qty, $pack_pref, $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) 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]);

                if (!empty($new_pid)) {
                    $stmt->bind_param("iiis", $order_id, $new_pid, $new_qty, $new_pack_pref);
                    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 * FROM order_items WHERE 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);
            width: 48%;
        }

        .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);
            width: 48%;
        }

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

        /* ---------------------------------------------------
           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 = `
                <input type="hidden" name="existing_item_id[]" value="">
                <div class="row">
                    <div class="col-md-5">
                        <label class="form-label" for="new_product_id_${itemCount}">Product</label>
                        <select name="new_product_id[]" id="new_product_id_${itemCount}" class="form-control">
                            <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-3">
                        <label class="form-label" for="new_quantity_${itemCount}">Quantity</label>
                        <input type="number" name="new_quantity[]" id="new_quantity_${itemCount}" class="form-control" min="1" value="1">
                    </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-1 d-flex align-items-end">
                        <button type="button" class="remove-product-button" onclick="removeOrderItemRow(this)">X</button>
                    </div>
                </div>
            `;
            orderItemsContainer.appendChild(orderItemRow);
        }

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

        // 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-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'] : $conn->query("SELECT name FROM customers WHERE id = {$order['customer_id']}")->fetch_assoc()['name']) ?>" 
                       required>
            </div>
            <div class="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'] : $conn->query("SELECT contact FROM customers WHERE id = {$order['customer_id']}")->fetch_assoc()['contact']) ?>">
            </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"><?= htmlspecialchars(isset($_POST['delivery_address']) ? $_POST['delivery_address'] : $conn->query("SELECT delivery_address FROM customers WHERE id = {$order['customer_id']}")->fetch_assoc()['delivery_address']) ?></textarea>
            </div>
            <hr>
            <!-- Order Status and Delivery DateTime -->
            <div class="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="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>
            <hr>
            <!-- Primary Product Details -->
            <div class="mb-3">
                <h5>Primary Product</h5>
                <div class="row">
                    <div class="col-md-5">
                        <label class="form-label" for="primary_product_id">Product <span class="text-danger">*</span></label>
                        <select name="primary_product_id" id="primary_product_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'] == $order['product_id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label" for="primary_quantity">Quantity <span class="text-danger">*</span></label>
                        <input type="number" name="primary_quantity" id="primary_quantity" class="form-control" min="1" value="<?= htmlspecialchars(isset($_POST['primary_quantity']) ? $_POST['primary_quantity'] : $order['quantity']) ?>" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label" for="primary_packaging_preferences">Packaging Preferences</label>
                        <input type="text" name="primary_packaging_preferences" id="primary_packaging_preferences" class="form-control" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars(isset($_POST['primary_packaging_preferences']) ? $_POST['primary_packaging_preferences'] : $order['packaging_preferences']) ?>">
                    </div>
                    <div class="col-md-1 d-flex align-items-end">
                        <!-- Empty for alignment -->
                    </div>
                </div>
            </div>
            <hr>
            <!-- Existing Order Items -->
            <div class="mb-3">
                <h5>Existing Additional Products</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-5">
                                    <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-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">
                                    <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-1 d-flex align-items-end">
                                    <button type="button" class="remove-product-button" onclick="removeExistingOrderItemRow(this)">X</button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <hr>
            <!-- Add New Order Items -->
            <div class="mb-3">
                <h5>Add New Additional Products</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">
                <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 make it cool design and do'nt change the stylse colors