based on this old codes edit orders (<?php
// public/orders/edit_order.php

// Enable comprehensive error reporting for debugging purposes
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'; // Ensure sanitize_input() is defined

// Verify that sanitize_input() exists
if (!function_exists('sanitize_input')) {
    die("Error: sanitize_input() function is not defined.");
}

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

// 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?error=Invalid%20Order%20ID");
    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);
if (!$order_stmt) {
    die("An unexpected error occurred. Please try again later.");
}
$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?error=Order%20Not%20Found");
    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);
if (!$order_items_stmt) {
    die("An unexpected error occurred. Please try again later.");
}
$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();

// Define an array of countries with their dialing codes
$countries = [
    "Afghanistan" => "+93",
    "Albania" => "+355",
    "Algeria" => "+213",
    "Andorra" => "+376",
    "Angola" => "+244",
    "Antigua and Barbuda" => "+1-268",
    "Argentina" => "+54",
    "Armenia" => "+374",
    "Australia" => "+61",
    "Austria" => "+43",
    "Azerbaijan" => "+994",
    "Bahamas" => "+1-242",
    "Bahrain" => "+973",
    "Bangladesh" => "+880",
    "Barbados" => "+1-246",
    "Belarus" => "+375",
    "Belgium" => "+32",
    "Belize" => "+501",
    "Benin" => "+229",
    "Bhutan" => "+975",
    "Bolivia" => "+591",
    "Bosnia and Herzegovina" => "+387",
    "Botswana" => "+267",
    "Brazil" => "+55",
    "Brunei" => "+673",
    "Bulgaria" => "+359",
    "Burkina Faso" => "+226",
    "Burundi" => "+257",
    "Kuwait" => "+965",
    // Add more countries as needed
];

// Function to extract country code from contact number
function extract_country_code($contact, $countries) {
    foreach ($countries as $country => $code) {
        if (strpos($contact, $code) === 0) {
            return [$country, $code];
        }
    }
    // Default to Kuwait if no match found
    return ["Kuwait", "+965"];
}

// Extract country and contact number
list($current_country, $current_country_code) = extract_country_code($order['customer_contact'] ?? '', $countries);
$contact_number = substr($order['customer_contact'], strlen($current_country_code));

// Fetch products for selection
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);
if (!$products_result) {
    die("Error fetching products: " . $conn->error);
}
$products = $products_result->fetch_all(MYSQLI_ASSOC);

// Initialize form variables
$customer_name = $order['customer_name'];
$selected_country = $current_country_code;
$delivery_address = $order['delivery_address'];
$status = $order['status'];
$priority = $order['priority'];
$free_shipping = $order['free_shipping'];
$is_paid = $order['is_paid'];
$pickup = $order['pickup'];
$delivery_datetime = $order['delivery_datetime'];

// Handle form submission for updating the order
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve and sanitize form inputs
    $customer_name = sanitize_input($_POST['customer_name'] ?? '');
    $contact_input = sanitize_input($_POST['contact'] ?? '');
    $selected_country = sanitize_input($_POST['country'] ?? '+965');
    $delivery_address = sanitize_input($_POST['delivery_address'] ?? '');
    $status = sanitize_input($_POST['status'] ?? '');
    $priority = sanitize_input($_POST['priority'] ?? '');
    $free_shipping = isset($_POST['free_shipping']) ? 1 : 0;
    $is_paid = isset($_POST['is_paid']) ? 1 : 0;
    $pickup = isset($_POST['pickup']) ? 1 : 0;

    // Handle delivery_datetime conversion from 'Y-m-d\TH:i' to 'Y-m-d H:i:s'
    $delivery_datetime_input = $_POST['delivery_datetime'] ?? '';
    if (!empty($delivery_datetime_input)) {
        $parsed_datetime = strtotime($delivery_datetime_input);
        if ($parsed_datetime !== false) {
            $delivery_datetime = date('Y-m-d H:i:s', $parsed_datetime);
        } else {
            $delivery_datetime = null;
        }
    } else {
        $delivery_datetime = null;
    }

    // Determine delivery_fee based on free_shipping and pickup
    if (!$free_shipping && !$pickup) {
        $delivery_fee = isset($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00;
    } else {
        $delivery_fee = 0.00;
    }

    // Handle existing order items
    $existing_item_ids = $_POST['existing_item_id'] ?? [];
    $existing_product_ids = $_POST['existing_product_id'] ?? [];
    $existing_quantities = $_POST['existing_quantity'] ?? [];
    $existing_packaging_preferences = $_POST['existing_packaging_preferences'] ?? [];
    $existing_apply_discount = $_POST['existing_apply_discount'] ?? [];
    $existing_discount_percentages = $_POST['existing_discount_percentage'] ?? [];
    $existing_discount_reasons = $_POST['existing_discount_reason'] ?? [];

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

    // Handle deleted existing order items
    $deleted_existing_item_ids = $_POST['deleted_existing_item_ids'] ?? [];
    $active_existing_item_ids = array_diff($existing_item_ids, $deleted_existing_item_ids);

    // Initialize Error Array
    $errors = [];

    // Validate essential fields
    if (empty($customer_name)) {
        $errors[] = "Customer name is required.";
    }
    if (empty($contact_input)) {
        $errors[] = "Contact number is required.";
    }
    if (empty($status)) {
        $errors[] = "Order status is required.";
    }
    if (empty($priority)) {
        $errors[] = "Order priority is required.";
    }
    if (empty($active_existing_item_ids) && empty($new_product_ids)) {
        $errors[] = "At least one product must be selected.";
    }

    // Validate contact number
    $contact_digits = preg_replace('/\D/', '', $contact_input);
    if (empty($contact_digits)) {
        $errors[] = "A valid contact number is required.";
    } else {
        // Full contact number with country code
        $full_contact = $selected_country . $contact_digits;
    }

    // Validate delivery fee only if not free_shipping or pickup
    if (!$free_shipping && !$pickup && ($delivery_fee < 0)) {
        $errors[] = "Delivery fee cannot be negative.";
    }

    // Validate existing order items
    foreach ($active_existing_item_ids as $index => $item_id) {
        $item_index = array_search($item_id, $existing_item_ids);
        $product_id = intval($existing_product_ids[$item_index] ?? 0);
        $quantity = intval($existing_quantities[$item_index] ?? 0);

        if ($product_id <= 0) {
            $errors[] = "Product selection is required for all existing items.";
            break;
        }
        if ($quantity <= 0) {
            $errors[] = "Quantity must be at least 1 for all existing items.";
            break;
        }

        // Handle discounts for existing items
        if (isset($existing_apply_discount[$item_index])) {
            $discount_percentage = floatval(trim($existing_discount_percentages[$item_index] ?? 0));
            $discount_reason = sanitize_input($existing_discount_reasons[$item_index] ?? '');

            if (($discount_percentage === 0 && empty($discount_reason))) {
                $errors[] = "All discount fields must be filled if discount is applied for existing items.";
                break;
            }
            if ($discount_percentage < 0 || $discount_percentage > 100) {
                $errors[] = "Invalid discount percentage for existing items. It should be between 0 and 100.";
                break;
            }
        }
    }

    // Validate new order items
    foreach ($new_product_ids as $index => $product_id) {
        $product_id = intval($product_id);
        $quantity = intval($new_quantities[$index] ?? 0);

        if ($product_id <= 0) {
            $errors[] = "Product selection is required for all new items.";
            break;
        }
        if ($quantity <= 0) {
            $errors[] = "Quantity must be at least 1 for all new items.";
            break;
        }

        // Handle discounts for new items
        if (isset($new_apply_discount[$index])) {
            $discount_percentage = floatval(trim($new_discount_percentages[$index]));
            $discount_reason = sanitize_input($new_discount_reasons[$index] ?? '');

            if (($discount_percentage === 0 && empty($discount_reason))) {
                $errors[] = "All discount fields must be filled if discount is applied for new items.";
                break;
            }
            if ($discount_percentage < 0 || $discount_percentage > 100) {
                $errors[] = "Invalid discount percentage for new items. It should be between 0 and 100.";
                break;
            }
        }
    }

    // If no errors, proceed to update the order
    if (empty($errors)) {
        // Start Transaction
        $conn->begin_transaction();

        try {
            // Step 1: 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, $full_contact, $delivery_address, $order['customer_id']);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $stmt->close();

            // Step 2: Update Order Table
            $stmt = $conn->prepare("UPDATE orders SET status = ?, priority = ?, delivery_fee = ?, free_shipping = ?, is_paid = ?, pickup = ?, delivery_datetime = ? WHERE id = ?");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }

            if ($delivery_datetime !== null) {
                $stmt->bind_param("ssdiiiis", $status, $priority, $delivery_fee, $free_shipping, $is_paid, $pickup, $delivery_datetime, $order_id);
            } else {
                // Bind NULL for delivery_datetime
                $stmt->bind_param("ssdiiiis", $status, $priority, $delivery_fee, $free_shipping, $is_paid, $pickup, $delivery_datetime, $order_id);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $stmt->close();

            // Step 3: Remove Deleted Existing Order Items
            if (!empty($deleted_existing_item_ids)) {
                // Prepare placeholders
                $placeholders = implode(',', array_fill(0, count($deleted_existing_item_ids), '?'));
                $types = str_repeat('i', count($deleted_existing_item_ids));
                $stmt = $conn->prepare("DELETE FROM order_items WHERE id IN ($placeholders)");
                if (!$stmt) {
                    throw new Exception("Prepare statement failed: " . $conn->error);
                }

                // Bind parameters dynamically
                $stmt->bind_param($types, ...array_map('intval', $deleted_existing_item_ids));

                if (!$stmt->execute()) {
                    throw new Exception("Execute failed: " . $stmt->error);
                }
                $stmt->close();
            }

            // Step 4: Update Existing Order Items
            foreach ($active_existing_item_ids as $index => $item_id) {
                $item_index = array_search($item_id, $existing_item_ids);
                $product_id = intval($existing_product_ids[$item_index]);
                $quantity = intval($existing_quantities[$item_index]);
                $packaging_preferences = sanitize_input($existing_packaging_preferences[$item_index] ?? '');

                // Handle discounts
                $discount_percentage = 0.00;
                $discount_reason = '';
                if (isset($existing_apply_discount[$item_index])) {
                    $discount_percentage = floatval(trim($existing_discount_percentages[$item_index]));
                    $discount_reason = sanitize_input($existing_discount_reasons[$item_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", $product_id, $quantity, $packaging_preferences, $discount_percentage, $discount_reason, $item_id);
                if (!$stmt->execute()) {
                    throw new Exception("Execute failed: " . $stmt->error);
                }
                $stmt->close();
            }

            // Step 5: Add New Order Items
            foreach ($new_product_ids as $index => $product_id) {
                $product_id = intval($product_id);
                $quantity = intval($new_quantities[$index]);
                $packaging_preferences = sanitize_input($new_packaging_preferences[$index] ?? '');

                // Handle discounts
                $discount_percentage = 0.00;
                $discount_reason = '';
                if (isset($new_apply_discount[$index])) {
                    $discount_percentage = floatval(trim($new_discount_percentages[$index]));
                    $discount_reason = sanitize_input($new_discount_reasons[$index]);
                }

                $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);
                }
                $stmt->bind_param("iiidsi", $order_id, $product_id, $quantity, $packaging_preferences, $discount_percentage, $discount_reason);
                if (!$stmt->execute()) {
                    throw new Exception("Execute failed: " . $stmt->error);
                }
                $stmt->close();
            }

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

            // Redirect to view_orders.php with success message
            header("Location: view_orders.php?success=Order+updated+successfully");
            exit();
        } catch (Exception $e) {
            // Rollback Transaction
            $conn->rollback();
            $error = "Error updating order: " . sanitize_input($e->getMessage());
        }
    } else {
        // Collect all errors
        $error = implode('<br>', $errors);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Order #<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?> - Kaak Alia Management System</title>
    
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Flatpickr CSS for Date Picker -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <!-- Custom Styles -->
    <style>
        /* Custom scrollbar for better UX */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f5f9; /* Tailwind's gray-100 */
        }

        ::-webkit-scrollbar-thumb {
            background: #20B2AA; /* Teal-500 */
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #0d9488; /* Teal-600 */
        }

        /* Responsive Table */
        @media (max-width: 768px) {
            table {
                min-width: 600px;
            }
        }

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

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 250px;
            background-color: #6B7280; /* Tailwind's gray-500 */
            color: #fff;
            text-align: left;
            border-radius: 4px;
            padding: 8px;
            position: absolute;
            z-index: 10;
            bottom: 125%; /* Position above the icon */
            left: 50%;
            margin-left: -125px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
    </style>

    <!-- Additional JavaScript for dynamic product addition, discount handling, delivery fee toggle, and pickup handling -->
    <script>
        let productCount = <?= count($order_items) > 0 ? count($order_items) : 1; ?>;

        function addProductRow() {
            const productContainer = document.getElementById('new-products-container');

            const productRow = document.createElement('div');
            productRow.className = 'product-row bg-gray-50 p-4 rounded-lg shadow-md mb-4';
            productRow.innerHTML = `
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="new_product_id_${productCount}">
                            Product <span class="text-red-500">*</span>
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Select the product from the dropdown menu. This list includes available items that can be added to the customer's order.
                                </span>
                            </span>
                        </label>
                        <select name="new_product_id[]" id="new_product_id_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                            <option value="">Select Product</option>
                            <?php foreach($products as $product_option): ?>
                                <option value="<?= htmlspecialchars($product_option['id'], ENT_QUOTES, 'UTF-8') ?>">
                                    <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)", ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="new_quantity_${productCount}">
                            Quantity <span class="text-red-500">*</span>
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Enter the number of units required for each selected product. Quantities must be in whole numbers and are defaulted to one (1) if not specified.
                                </span>
                            </span>
                        </label>
                        <input type="number" name="new_quantity[]" id="new_quantity_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="1" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="new_packaging_preferences_${productCount}">
                            Packaging Preferences
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Specify any particular packaging requests, such as 'Gift Wrap' or 'Fragile - Handle with Care,' to ensure customer satisfaction and safe delivery.
                                </span>
                            </span>
                        </label>
                        <input type="text" name="new_packaging_preferences[]" id="new_packaging_preferences_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="new_discount_${productCount}">
                            Apply Discount
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Check this box if the customer is eligible for a discount. Discounts will be applied to the total product cost at checkout.
                                </span>
                            </span>
                        </label>
                        <div class="flex items-center mt-1">
                            <input type="checkbox" name="new_apply_discount[]" id="new_discount_checkbox_${productCount}" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleNewDiscountFields(this, ${productCount})">
                            <label for="new_discount_checkbox_${productCount}" class="ml-2 block text-sm text-gray-700">
                                Yes
                            </label>
                        </div>
                        <div id="new_discount_fields_${productCount}" class="discount-fields mt-2" style="display: none;">
                            <label class="block text-sm font-medium text-gray-700" for="new_discount_percentage_${productCount}">
                                Discount Percentage (%) <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Enter the discount percentage to be applied to this product. It should be between 0 and 100.
                                    </span>
                                </span>
                            </label>
                            <input type="number" name="new_discount_percentage[]" id="new_discount_percentage_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage" required>
                            
                            <label class="block text-sm font-medium text-gray-700 mt-2" for="new_discount_reason_${productCount}">
                                Discount Reason <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Provide a reason for the discount applied to this product.
                                    </span>
                                </span>
                            </label>
                            <input type="text" name="new_discount_reason[]" id="new_discount_reason_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" required>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end mt-2">
                    <button type="button" class="remove-product-button bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition duration-300 flex items-center gap-2" onclick="removeProductRow(this)">
                        <i class="bi bi-trash-fill"></i> Remove Product
                    </button>
                </div>
            `;
            productContainer.appendChild(productRow);

            productCount++;
        }

        function removeProductRow(button) {
            const productRow = button.closest('.product-row');
            productRow.remove();
        }

        // Toggle discount fields based on checkbox for existing items
        function toggleDiscountFields(checkbox, count) {
            const discountFields = document.getElementById(`discount_fields_${count}`);
            if (checkbox.checked) {
                discountFields.style.display = 'block';
            } else {
                discountFields.style.display = 'none';
                // Clear discount inputs
                discountFields.querySelectorAll('input').forEach(input => input.value = '');
            }
        }

        // Toggle discount fields based on checkbox for new items
        function toggleNewDiscountFields(checkbox, count) {
            const discountFields = document.getElementById(`new_discount_fields_${count}`);
            if (checkbox.checked) {
                discountFields.style.display = 'block';
            } else {
                discountFields.style.display = 'none';
                // Clear discount inputs
                discountFields.querySelectorAll('input').forEach(input => input.value = '');
            }
        }

        // Toggle delivery fee field based on free shipping and pickup checkboxes
        function toggleDeliveryFee() {
            const freeShippingCheckbox = document.getElementById('free_shipping');
            const pickupCheckbox = document.getElementById('pickup');
            const deliveryFeeField = document.getElementById('delivery_fee_field');
            const deliveryFeeInput = document.getElementById('delivery_fee');

            if (freeShippingCheckbox.checked || pickupCheckbox.checked) {
                deliveryFeeField.style.display = 'none';
                deliveryFeeInput.value = '0.00';
                deliveryFeeInput.disabled = true;
            } else {
                deliveryFeeField.style.display = 'block';
                deliveryFeeInput.disabled = false;
            }
        }

        // Toggle specific delivery details based on pickup checkbox
        function togglePickup() {
            const pickupCheckbox = document.getElementById('pickup');
            const freeShippingCheckbox = document.getElementById('free_shipping');
            const deliveryFeeInput = document.getElementById('delivery_fee');
            const deliveryFeeField = document.getElementById('delivery_fee_field');
            const deliveryAddressField = document.getElementById('delivery_address_field');

            if (pickupCheckbox.checked) {
                // Hide Delivery Address
                deliveryAddressField.style.display = 'none';

                // Uncheck and hide Free Shipping if it's checked
                if (freeShippingCheckbox.checked) {
                    freeShippingCheckbox.checked = false;
                    toggleDeliveryFee();
                }

                // Hide Delivery Fee
                deliveryFeeField.style.display = 'none';
                deliveryFeeInput.value = '0.00';
                deliveryFeeInput.disabled = true;
            } else {
                // Show Delivery Address
                deliveryAddressField.style.display = 'block';

                // Show Delivery Fee based on Free Shipping status
                toggleDeliveryFee();
            }
        }

        // Auto-generate Customer Name based on Contact Number
        function autoGenerateCustomerName() {
            const contactInput = document.getElementById('contact');
            const customerNameInput = document.getElementById('customer_name');
            
            // Extract digits from contact number
            const digits = contactInput.value.replace(/\D/g, '');
            if (digits.length > 0) {
                customerNameInput.value = 'Order_' + digits;
            } else {
                customerNameInput.value = '';
            }
        }

        // Initialize on DOM content loaded
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize delivery fee toggle
            toggleDeliveryFee();
            const freeShippingEl = document.getElementById('free_shipping');
            if (freeShippingEl) {
                freeShippingEl.addEventListener('change', toggleDeliveryFee);
            }

            // Initialize pickup toggle
            togglePickup();
            const pickupEl = document.getElementById('pickup');
            if (pickupEl) {
                pickupEl.addEventListener('change', togglePickup);
            }

            // Initialize Customer Name auto-generation
            const contactEl = document.getElementById('contact');
            if (contactEl) {
                contactEl.addEventListener('input', autoGenerateCustomerName);
            }

            // Initialize tooltip functionality
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('.tooltip'))
            tooltipTriggerList.forEach(function (tooltipTriggerEl) {
                var tooltipText = tooltipTriggerEl.querySelector('.tooltiptext');
                tooltipTriggerEl.addEventListener('mouseenter', function() {
                    tooltipText.style.visibility = 'visible';
                    tooltipText.style.opacity = '1';
                });
                tooltipTriggerEl.addEventListener('mouseleave', function() {
                    tooltipText.style.visibility = 'hidden';
                    tooltipText.style.opacity = '0';
                });
            });
        });
    </script>
</head>
<body class="font-inter bg-gray-100">

    <!-- Include header.php inside the body -->
    <?php require_once '../../includes/header.php'; ?>

    <!-- Main Container -->
    <main class="container mx-auto p-6">
        <!-- Page Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-blue-600 flex items-center">
                <i class="bi bi-pencil-square mr-2"></i> Edit Order #<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?>
            </h1>
        </div>

        <!-- Welcome Section -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <p class="text-gray-700">Update the details of the order below. Ensure all changes are accurate before submission.</p>
        </div>

        <!-- Form Container -->
        <div class="bg-white rounded-lg shadow-lg p-6">
            <?php if (!empty($error)): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 flex items-center">
                    <i class="bi bi-exclamation-triangle-fill mr-2"></i>
                    <span><?= $error ?></span>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="edit_order.php?id=<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?>">
                <!-- Customer Details -->
                <div class="mb-6">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">Customer Details</h2>
                    
                    <div class="flex flex-col md:flex-row md:space-x-6">
                        <div class="flex-1 mb-4 md:mb-0">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="customer_name">
                                Customer Name <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Automatically generated based on contact number. If unavailable, enter the customer's full name for record purposes.
                                    </span>
                                </span>
                            </label>
                            <input type="text" id="customer_name" name="customer_name" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                                   value="<?= htmlspecialchars($customer_name ?? $order['customer_name'], ENT_QUOTES, 'UTF-8') ?>" 
                                   placeholder="Enter customer name" required>
                        </div>
                        <div class="flex-1 mb-4 md:mb-0">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="country">
                                Country <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Select the customer’s country to ensure accurate address formatting and delivery options. Default is set based on existing contact.
                                    </span>
                                </span>
                            </label>
                            <select name="country" id="country" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                                <?php foreach($countries as $country => $code): ?>
                                    <option value="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>" <?= ($selected_country === $code) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($country . " (" . $code . ")", ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="flex flex-col md:flex-row md:space-x-6 mt-4">
                        <div class="flex-1 mb-4 md:mb-0" id="contact_field">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="contact">
                                Contact Number <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Enter a valid contact number without the country code. The country code is auto-prepended based on selected country.
                                    </span>
                                </span>
                            </label>
                            <input type="text" id="contact" name="contact" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                                   value="<?= htmlspecialchars($contact_number, ENT_QUOTES, 'UTF-8') ?>" 
                                   required placeholder="Enter contact number without country code">
                        </div>
                        <div class="flex-1" id="delivery_address_field">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_address">
                                Delivery Address
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Provide the full delivery address, including building name, street, area, and any special instructions to facilitate easy and efficient delivery.
                                    </span>
                                </span>
                            </label>
                            <textarea id="delivery_address" name="delivery_address" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" rows="3" placeholder="Enter delivery address"><?= htmlspecialchars($delivery_address ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
                        </div>
                    </div>
                </div>
                <hr class="my-6">

                <!-- Order Details -->
                <div class="mb-6">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Details</h2>
                    
                    <!-- Priority Selection -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Order Priority
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Choose a priority level for this order based on urgency: Normal for standard processing, Important for prioritized handling, and Quick for immediate attention.
                                </span>
                            </span>
                        </label>
                        <div class="flex space-x-4">
                            <?php
                                $priorities = ['Normal', 'Important', 'Quick'];
                                foreach ($priorities as $priority_option):
                                    $checked = ($priority === $priority_option) ? 'checked' : '';
                            ?>
                                <label class="inline-flex items-center">
                                    <input type="radio" name="priority" value="<?= htmlspecialchars($priority_option, ENT_QUOTES, 'UTF-8') ?>" class="form-radio text-teal-600" <?= $checked ?> required>
                                    <span class="ml-2"><?= htmlspecialchars($priority_option, ENT_QUOTES, 'UTF-8') ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Status Selection -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Order Status
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Update the current status of the order: Pending, In Progress, Completed, or Delivered.
                                </span>
                            </span>
                        </label>
                        <select name="status" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                            <option value="Pending" <?= ($status == 'Pending') ? 'selected' : '' ?>>Pending</option>
                            <option value="In Progress" <?= ($status == 'In Progress') ? 'selected' : '' ?>>In Progress</option>
                            <option value="Completed" <?= ($status == 'Completed') ? 'selected' : '' ?>>Completed</option>
                            <option value="Delivered" <?= ($status == 'Delivered') ? 'selected' : '' ?>>Delivered</option>
                        </select>
                    </div>

                    <!-- Delivery Fee and Free Shipping -->
                    <div class="mb-4" id="delivery_fee_field">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Delivery Fee (KWD)
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Enter any applicable delivery fee in Kuwaiti Dinar (KWD). This field will automatically set to 0 if ‘Free Shipping’ is selected or if pickup is chosen.
                                </span>
                            </span>
                        </label>
                        <input type="number" step="0.01" min="0" name="delivery_fee" id="delivery_fee" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                               value="<?= htmlspecialchars($delivery_fee, ENT_QUOTES, 'UTF-8') ?>" 
                               <?= ($free_shipping || $pickup) ? 'disabled' : '' ?> required>
                    </div>
                    <div class="flex items-center mb-4">
                        <input type="checkbox" id="free_shipping" name="free_shipping" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= $free_shipping ? 'checked' : '' ?> onchange="toggleDeliveryFee()">
                        <label for="free_shipping" class="ml-2 block text-sm text-gray-700">
                            Free Shipping
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Select this option if the customer qualifies for free shipping based on promotional offers or order amount. Delivery fees will automatically update.
                                </span>
                            </span>
                        </label>
                    </div>

                    <!-- Pickup Checkbox -->
                    <div class="flex items-center mb-4">
                        <input type="checkbox" id="pickup" name="pickup" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= $pickup ? 'checked' : '' ?> onchange="togglePickup()">
                        <label for="pickup" class="ml-2 block text-sm text-gray-700">
                            Customer Pickup
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Select this option if the customer will pick up the order directly from our kitchen, eliminating the need for delivery.
                                </span>
                            </span>
                        </label>
                    </div>

                    <!-- Delivery Date and Time -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_datetime">
                            Delivery Date and Time
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Choose a specific date and time for the order delivery or pickup. Ensure the date aligns with the customer’s availability and our schedule to avoid delays.
                                </span>
                            </span>
                        </label>
                        <input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                               value="<?= htmlspecialchars($delivery_datetime ? date('Y-m-d\TH:i', strtotime($delivery_datetime)) : '', ENT_QUOTES, 'UTF-8') ?>" required>
                    </div>
                </div>
                <hr class="my-6">

                <!-- Order Items -->
                <div class="mb-6">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Items</h2>
                    
                    <!-- Existing Order Items -->
                    <div class="mb-4">
                        <h3 class="text-lg font-semibold mb-2">Existing Items</h3>
                        <?php if (empty($order_items)): ?>
                            <p>No existing items for this order.</p>
                        <?php else: ?>
                            <?php foreach ($order_items as $index => $item): ?>
                                <div class="border border-gray-300 rounded-lg p-4 mb-4">
                                    <input type="hidden" name="existing_item_id[]" value="<?= htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') ?>">
                                    <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="existing_product_id_<?= $index ?>">
                                                Product <span class="text-red-500">*</span>
                                            </label>
                                            <select name="existing_product_id[]" id="existing_product_id_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                                                <option value="">Select Product</option>
                                                <?php foreach($products as $product_option): ?>
                                                    <option value="<?= htmlspecialchars($product_option['id'], ENT_QUOTES, 'UTF-8') ?>" <?= ($product_option['id'] == $item['product_id']) ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)", ENT_QUOTES, 'UTF-8') ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="existing_quantity_<?= $index ?>">
                                                Quantity <span class="text-red-500">*</span>
                                            </label>
                                            <input type="number" name="existing_quantity[]" id="existing_quantity_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="<?= htmlspecialchars($item['quantity'], ENT_QUOTES, 'UTF-8') ?>" required>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="existing_packaging_preferences_<?= $index ?>">
                                                Packaging Preferences
                                            </label>
                                            <input type="text" name="existing_packaging_preferences[]" id="existing_packaging_preferences_<?= $index ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($item['packaging_preferences'], ENT_QUOTES, 'UTF-8') ?>">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="existing_discount_<?= $index ?>">
                                                Apply Discount
                                            </label>
                                            <div class="flex items-center mt-1">
                                                <input type="checkbox" name="existing_apply_discount[]" id="existing_discount_checkbox_<?= $index ?>" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, <?= $index ?>)" <?= ($item['discount_percentage'] > 0) ? 'checked' : '' ?>>
                                                <label for="existing_discount_checkbox_<?= $index ?>" class="ml-2 block text-sm text-gray-700">
                                                    Yes
                                                </label>
                                            </div>
                                            <div id="discount_fields_<?= $index ?>" class="discount-fields mt-2" style="display: <?= ($item['discount_percentage'] > 0) ? 'block' : 'none' ?>;">
                                                <label class="block text-sm font-medium text-gray-700" for="existing_discount_percentage_<?= $index ?>">
                                                    Discount Percentage (%) <span class="text-red-500">*</span>
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Enter the discount percentage to be applied to this product. It should be between 0 and 100.
                                                        </span>
                                                    </span>
                                                </label>
                                                <input type="number" name="existing_discount_percentage[]" id="existing_discount_percentage_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" value="<?= htmlspecialchars($item['discount_percentage'], ENT_QUOTES, 'UTF-8') ?>" required>
                                                
                                                <label class="block text-sm font-medium text-gray-700 mt-2" for="existing_discount_reason_<?= $index ?>">
                                                    Discount Reason <span class="text-red-500">*</span>
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Provide a reason for the discount applied to this product.
                                                        </span>
                                                    </span>
                                                </label>
                                                <input type="text" name="existing_discount_reason[]" id="existing_discount_reason_<?= $index ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" value="<?= htmlspecialchars($item['discount_reason'], ENT_QUOTES, 'UTF-8') ?>" required>
                                            </div>
                                        </div>
                                        <div class="flex items-center">
                                            <label class="flex items-center">
                                                <input type="checkbox" name="deleted_existing_item_ids[]" value="<?= htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') ?>" class="h-4 w-4 text-red-600 border-gray-300 rounded">
                                                <span class="ml-2 text-sm text-gray-700">Delete</span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>

                    <!-- New Order Items -->
                    <div class="mb-4">
                        <h3 class="text-lg font-semibold mb-2">Add New Items</h3>
                        <div id="new-products-container">
                            <!-- New Product Rows will be added here -->
                        </div>
                        <button type="button" class="bg-teal-500 text-white px-4 py-2 rounded-lg hover:bg-teal-600 transition duration-300 flex items-center gap-2 mt-4" onclick="addProductRow()">
                            <i class="bi bi-plus-circle-fill"></i> Add Another Product
                        </button>
                    </div>
                </div>
                <hr class="my-6">

                <!-- Submit Button -->
                <div class="mb-6">
                    <button type="submit" class="w-full bg-green-500 text-white px-4 py-3 rounded-lg hover:bg-green-600 transition duration-300 flex justify-center items-center gap-2">
                        <i class="bi bi-save"></i> Update Order
                    </button>
                </div>
            </form>
        </div>

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

    <!-- Bootstrap JS Bundle (optional if using Bootstrap components) -->
    <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Flatpickr JS for Date Picker -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <!-- Flatpickr Initialization -->
    <script>
        flatpickr("#delivery_datetime", {
            enableTime: true,
            dateFormat: "Y-m-d\\TH:i",
            minDate: "today"
        });
    </script>

</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>) fix this orders please (<?php
// public/orders/edit_order.php

// Enable comprehensive error reporting for debugging purposes
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'; // Ensure sanitize_input() is defined

// Verify that sanitize_input() exists
if (!function_exists('sanitize_input')) {
    die("Error: sanitize_input() function is not defined.");
}

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

// 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?error=Invalid%20Order%20ID");
    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);
if (!$order_stmt) {
    die("An unexpected error occurred. Please try again later.");
}
$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?error=Order%20Not%20Found");
    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);
if (!$order_items_stmt) {
    die("An unexpected error occurred. Please try again later.");
}
$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();

// Define an array of countries with their dialing codes
$countries = [
    "Afghanistan" => "+93",
    "Albania" => "+355",
    "Algeria" => "+213",
    "Andorra" => "+376",
    "Angola" => "+244",
    "Antigua and Barbuda" => "+1-268",
    "Argentina" => "+54",
    "Armenia" => "+374",
    "Australia" => "+61",
    "Austria" => "+43",
    "Azerbaijan" => "+994",
    "Bahamas" => "+1-242",
    "Bahrain" => "+973",
    "Bangladesh" => "+880",
    "Barbados" => "+1-246",
    "Belarus" => "+375",
    "Belgium" => "+32",
    "Belize" => "+501",
    "Benin" => "+229",
    "Bhutan" => "+975",
    "Bolivia" => "+591",
    "Bosnia and Herzegovina" => "+387",
    "Botswana" => "+267",
    "Brazil" => "+55",
    "Brunei" => "+673",
    "Bulgaria" => "+359",
    "Burkina Faso" => "+226",
    "Burundi" => "+257",
    "Kuwait" => "+965",
    // Add more countries as needed
];

// Function to extract country code from contact number
function extract_country_code($contact, $countries) {
    foreach ($countries as $country => $code) {
        if (strpos($contact, $code) === 0) {
            return [$country, $code];
        }
    }
    // Default to Kuwait if no match found
    return ["Kuwait", "+965"];
}

// Extract country and contact number
list($current_country, $current_country_code) = extract_country_code($order['customer_contact'] ?? '', $countries);
$contact_number = substr($order['customer_contact'], strlen($current_country_code));

// Fetch products for selection
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);
if (!$products_result) {
    die("Error fetching products: " . $conn->error);
}
$products = $products_result->fetch_all(MYSQLI_ASSOC);

// Initialize form variables
$customer_name = $order['customer_name'];
$selected_country = $current_country_code;
$delivery_address = $order['delivery_address'];
$status = $order['status'];
$priority = $order['priority'];
$free_shipping = $order['free_shipping'];
$is_paid = $order['is_paid'];
$pickup = $order['pickup'];
$delivery_datetime = $order['delivery_datetime'];

// Handle form submission for updating the order
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve and sanitize form inputs
    $customer_name = sanitize_input($_POST['customer_name'] ?? '');
    $contact_input = sanitize_input($_POST['contact'] ?? '');
    $selected_country = sanitize_input($_POST['country'] ?? '+965');
    $delivery_address = sanitize_input($_POST['delivery_address'] ?? '');
    $status = sanitize_input($_POST['status'] ?? '');
    $priority = sanitize_input($_POST['priority'] ?? '');
    $free_shipping = isset($_POST['free_shipping']) ? 1 : 0;
    $is_paid = isset($_POST['is_paid']) ? 1 : 0;
    $pickup = isset($_POST['pickup']) ? 1 : 0;

    // Handle delivery_datetime conversion from 'Y-m-d\TH:i' to 'Y-m-d H:i:s'
    $delivery_datetime_input = $_POST['delivery_datetime'] ?? '';
    if (!empty($delivery_datetime_input)) {
        $parsed_datetime = strtotime($delivery_datetime_input);
        if ($parsed_datetime !== false) {
            $delivery_datetime = date('Y-m-d H:i:s', $parsed_datetime);
        } else {
            $delivery_datetime = null;
        }
    } else {
        $delivery_datetime = null;
    }

    // Determine delivery_fee based on free_shipping and pickup
    if (!$free_shipping && !$pickup) {
        $delivery_fee = isset($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00;
    } else {
        $delivery_fee = 0.00;
    }

    // Handle existing order items
    $existing_item_ids = $_POST['existing_item_id'] ?? [];
    $existing_product_ids = $_POST['existing_product_id'] ?? [];
    $existing_quantities = $_POST['existing_quantity'] ?? [];
    $existing_packaging_preferences = $_POST['existing_packaging_preferences'] ?? [];
    $existing_apply_discount = $_POST['existing_apply_discount'] ?? [];
    $existing_discount_percentages = $_POST['existing_discount_percentage'] ?? [];
    $existing_discount_reasons = $_POST['existing_discount_reason'] ?? [];

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

    // Handle deleted existing order items
    $deleted_existing_item_ids = $_POST['deleted_existing_item_ids'] ?? [];
    $active_existing_item_ids = array_diff($existing_item_ids, $deleted_existing_item_ids);

    // Initialize Error Array
    $errors = [];

    // Validate essential fields
    if (empty($customer_name)) {
        $errors[] = "Customer name is required.";
    }
    if (empty($contact_input)) {
        $errors[] = "Contact number is required.";
    }
    if (empty($status)) {
        $errors[] = "Order status is required.";
    }
    if (empty($priority)) {
        $errors[] = "Order priority is required.";
    }
    if (empty($active_existing_item_ids) && empty($new_product_ids)) {
        $errors[] = "At least one product must be selected.";
    }

    // Validate contact number
    $contact_digits = preg_replace('/\D/', '', $contact_input);
    if (empty($contact_digits)) {
        $errors[] = "A valid contact number is required.";
    } else {
        // Full contact number with country code
        $full_contact = $selected_country . $contact_digits;
    }

    // Validate delivery fee only if not free_shipping or pickup
    if (!$free_shipping && !$pickup && ($delivery_fee < 0)) {
        $errors[] = "Delivery fee cannot be negative.";
    }

    // Validate existing order items
    foreach ($active_existing_item_ids as $index => $item_id) {
        $item_index = array_search($item_id, $existing_item_ids);
        $product_id = intval($existing_product_ids[$item_index] ?? 0);
        $quantity = intval($existing_quantities[$item_index] ?? 0);

        if ($product_id <= 0) {
            $errors[] = "Product selection is required for all existing items.";
            break;
        }
        if ($quantity <= 0) {
            $errors[] = "Quantity must be at least 1 for all existing items.";
            break;
        }

        // Handle discounts for existing items
        if (isset($existing_apply_discount[$item_index])) {
            $discount_percentage = floatval(trim($existing_discount_percentages[$item_index] ?? 0));
            $discount_reason = sanitize_input($existing_discount_reasons[$item_index] ?? '');

            if (($discount_percentage <= 0 && !empty($existing_discount_percentages[$item_index]))) {
                $errors[] = "Discount percentage must be greater than 0 if discount is applied for existing items.";
                break;
            }
            if ($discount_percentage < 0 || $discount_percentage > 100) {
                $errors[] = "Invalid discount percentage for existing items. It should be between 0 and 100.";
                break;
            }
            if (empty($discount_reason) && $discount_percentage > 0) {
                $errors[] = "Discount reason is required if discount is applied for existing items.";
                break;
            }
        }
    }

    // Validate new order items
    foreach ($new_product_ids as $index => $product_id) {
        $product_id = intval($product_id);
        $quantity = intval($new_quantities[$index] ?? 0);

        if ($product_id <= 0) {
            $errors[] = "Product selection is required for all new items.";
            break;
        }
        if ($quantity <= 0) {
            $errors[] = "Quantity must be at least 1 for all new items.";
            break;
        }

        // Handle discounts for new items
        if (isset($new_apply_discount[$index])) {
            $discount_percentage = floatval(trim($new_discount_percentages[$index]));
            $discount_reason = sanitize_input($new_discount_reasons[$index] ?? '');

            if (($discount_percentage <= 0 && !empty($new_discount_percentages[$index]))) {
                $errors[] = "Discount percentage must be greater than 0 if discount is applied for new items.";
                break;
            }
            if ($discount_percentage < 0 || $discount_percentage > 100) {
                $errors[] = "Invalid discount percentage for new items. It should be between 0 and 100.";
                break;
            }
            if (empty($discount_reason) && $discount_percentage > 0) {
                $errors[] = "Discount reason is required if discount is applied for new items.";
                break;
            }
        }
    }

    // If no errors, proceed to update the order
    if (empty($errors)) {
        // Start Transaction
        $conn->begin_transaction();

        try {
            // Step 1: Update Customer Details
            // If pickup is selected, clear the delivery_address
            if ($pickup) {
                $delivery_address = '';
            }

            $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, $full_contact, $delivery_address, $order['customer_id']);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $stmt->close();

            // Step 2: Update Order Table
            $stmt = $conn->prepare("UPDATE orders SET status = ?, priority = ?, delivery_fee = ?, free_shipping = ?, is_paid = ?, pickup = ?, delivery_datetime = ? WHERE id = ?");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }

            if ($delivery_datetime !== null) {
                $stmt->bind_param("ssdiiiis", $status, $priority, $delivery_fee, $free_shipping, $is_paid, $pickup, $delivery_datetime, $order_id);
            } else {
                $stmt->bind_param("ssdiiiis", $status, $priority, $delivery_fee, $free_shipping, $is_paid, $pickup, $delivery_datetime, $order_id);
            }

            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $stmt->close();

            // Step 3: Remove Deleted Existing Order Items
            if (!empty($deleted_existing_item_ids)) {
                // Prepare placeholders
                $placeholders = implode(',', array_fill(0, count($deleted_existing_item_ids), '?'));
                $types = str_repeat('i', count($deleted_existing_item_ids));
                $stmt = $conn->prepare("DELETE FROM order_items WHERE id IN ($placeholders)");
                if (!$stmt) {
                    throw new Exception("Prepare statement failed: " . $conn->error);
                }

                // Bind parameters dynamically
                $stmt->bind_param($types, ...array_map('intval', $deleted_existing_item_ids));

                if (!$stmt->execute()) {
                    throw new Exception("Execute failed: " . $stmt->error);
                }
                $stmt->close();
            }

            // Step 4: Update Existing Order Items
            foreach ($active_existing_item_ids as $index => $item_id) {
                $item_index = array_search($item_id, $existing_item_ids);
                $product_id = intval($existing_product_ids[$item_index]);
                $quantity = intval($existing_quantities[$item_index]);
                $packaging_preferences = sanitize_input($existing_packaging_preferences[$item_index] ?? '');

                // Handle discounts
                $discount_percentage = 0.00;
                $discount_reason = '';
                if (isset($existing_apply_discount[$item_index])) {
                    $discount_percentage = floatval(trim($existing_discount_percentages[$item_index]));
                    $discount_reason = sanitize_input($existing_discount_reasons[$item_index]);

                    // If discount_percentage is 0, set discount_reason to empty
                    if ($discount_percentage <= 0) {
                        $discount_reason = '';
                    }
                }

                $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("iidssi", $product_id, $quantity, $packaging_preferences, $discount_percentage, $discount_reason, $item_id);
                if (!$stmt->execute()) {
                    throw new Exception("Execute failed: " . $stmt->error);
                }
                $stmt->close();
            }

            // Step 5: Add New Order Items
            foreach ($new_product_ids as $index => $product_id) {
                $product_id = intval($product_id);
                $quantity = intval($new_quantities[$index]);
                $packaging_preferences = sanitize_input($new_packaging_preferences[$index] ?? '');

                // Handle discounts
                $discount_percentage = 0.00;
                $discount_reason = '';
                if (isset($new_apply_discount[$index])) {
                    $discount_percentage = floatval(trim($new_discount_percentages[$index]));
                    $discount_reason = sanitize_input($new_discount_reasons[$index]);

                    // If discount_percentage is 0, set discount_reason to empty
                    if ($discount_percentage <= 0) {
                        $discount_reason = '';
                    }
                }

                $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);
                }
                $stmt->bind_param("iiidsi", $order_id, $product_id, $quantity, $packaging_preferences, $discount_percentage, $discount_reason);
                if (!$stmt->execute()) {
                    throw new Exception("Execute failed: " . $stmt->error);
                }
                $stmt->close();
            }

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

            // Redirect to view_orders.php with success message
            header("Location: view_orders.php?success=Order+updated+successfully");
            exit();
        } catch (Exception $e) {
            // Rollback Transaction
            $conn->rollback();
            $error = "Error updating order: " . sanitize_input($e->getMessage());
        }
    } else {
        // Collect all errors
        $error = implode('<br>', $errors);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Order #<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?> - Kaak Alia Management System</title>
    
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Flatpickr CSS for Date Picker -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <!-- Custom Styles -->
    <style>
        /* Custom scrollbar for better UX */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f5f9; /* Tailwind's gray-100 */
        }

        ::-webkit-scrollbar-thumb {
            background: #20B2AA; /* Teal-500 */
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #0d9488; /* Teal-600 */
        }

        /* Responsive Table */
        @media (max-width: 768px) {
            table {
                min-width: 600px;
            }
        }

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

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 250px;
            background-color: #6B7280; /* Tailwind's gray-500 */
            color: #fff;
            text-align: left;
            border-radius: 4px;
            padding: 8px;
            position: absolute;
            z-index: 10;
            bottom: 125%; /* Position above the icon */
            left: 50%;
            margin-left: -125px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
    </style>

    <!-- Additional JavaScript for dynamic product addition, discount handling, delivery fee toggle, and pickup handling -->
    <script>
        let productCount = <?= count($order_items) > 0 ? count($order_items) : 1; ?>;

        function addProductRow() {
            const productContainer = document.getElementById('new-products-container');

            const productRow = document.createElement('div');
            productRow.className = 'product-row bg-gray-50 p-4 rounded-lg shadow-md mb-4';
            productRow.innerHTML = `
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="new_product_id_${productCount}">
                            Product <span class="text-red-500">*</span>
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Select the product from the dropdown menu. This list includes available items that can be added to the customer's order.
                                </span>
                            </span>
                        </label>
                        <select name="new_product_id[]" id="new_product_id_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                            <option value="">Select Product</option>
                            <?php foreach($products as $product_option): ?>
                                <option value="<?= htmlspecialchars($product_option['id'], ENT_QUOTES, 'UTF-8') ?>">
                                    <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)", ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="new_quantity_${productCount}">
                            Quantity <span class="text-red-500">*</span>
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Enter the number of units required for each selected product. Quantities must be in whole numbers and are defaulted to one (1) if not specified.
                                </span>
                            </span>
                        </label>
                        <input type="number" name="new_quantity[]" id="new_quantity_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="1" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="new_packaging_preferences_${productCount}">
                            Packaging Preferences
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Specify any particular packaging requests, such as 'Gift Wrap' or 'Fragile - Handle with Care,' to ensure customer satisfaction and safe delivery.
                                </span>
                            </span>
                        </label>
                        <input type="text" name="new_packaging_preferences[]" id="new_packaging_preferences_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700" for="new_discount_${productCount}">
                            Apply Discount
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Check this box if the customer is eligible for a discount. Discounts will be applied to the total product cost at checkout.
                                </span>
                            </span>
                        </label>
                        <div class="flex items-center mt-1">
                            <input type="checkbox" name="new_apply_discount[]" id="new_discount_checkbox_${productCount}" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleNewDiscountFields(this, ${productCount})">
                            <label for="new_discount_checkbox_${productCount}" class="ml-2 block text-sm text-gray-700">
                                Yes
                            </label>
                        </div>
                        <div id="new_discount_fields_${productCount}" class="discount-fields mt-2" style="display: none;">
                            <label class="block text-sm font-medium text-gray-700" for="new_discount_percentage_${productCount}">
                                Discount Percentage (%) <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Enter the discount percentage to be applied to this product. It should be between 0 and 100.
                                    </span>
                                </span>
                            </label>
                            <input type="number" name="new_discount_percentage[]" id="new_discount_percentage_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage" required>
                            
                            <label class="block text-sm font-medium text-gray-700 mt-2" for="new_discount_reason_${productCount}">
                                Discount Reason <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Provide a reason for the discount applied to this product.
                                    </span>
                                </span>
                            </label>
                            <input type="text" name="new_discount_reason[]" id="new_discount_reason_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" required>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end mt-2">
                    <button type="button" class="remove-product-button bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition duration-300 flex items-center gap-2" onclick="removeProductRow(this)">
                        <i class="bi bi-trash-fill"></i> Remove Product
                    </button>
                </div>
            `;
            productContainer.appendChild(productRow);

            productCount++;
        }

        function removeProductRow(button) {
            const productRow = button.closest('.product-row');
            productRow.remove();
        }

        // Toggle discount fields based on checkbox for existing items
        function toggleDiscountFields(checkbox, count) {
            const discountFields = document.getElementById(`discount_fields_${count}`);
            if (checkbox.checked) {
                discountFields.style.display = 'block';
            } else {
                discountFields.style.display = 'none';
                // Clear discount inputs
                discountFields.querySelectorAll('input').forEach(input => input.value = '');
            }
        }

        // Toggle discount fields based on checkbox for new items
        function toggleNewDiscountFields(checkbox, count) {
            const discountFields = document.getElementById(`new_discount_fields_${count}`);
            if (checkbox.checked) {
                discountFields.style.display = 'block';
            } else {
                discountFields.style.display = 'none';
                // Clear discount inputs
                discountFields.querySelectorAll('input').forEach(input => input.value = '');
            }
        }

        // Toggle delivery fee field based on free shipping and pickup checkboxes
        function toggleDeliveryFee() {
            const freeShippingCheckbox = document.getElementById('free_shipping');
            const pickupCheckbox = document.getElementById('pickup');
            const deliveryFeeField = document.getElementById('delivery_fee_field');
            const deliveryFeeInput = document.getElementById('delivery_fee');

            if (freeShippingCheckbox.checked || pickupCheckbox.checked) {
                deliveryFeeField.style.display = 'none';
                deliveryFeeInput.value = '0.00';
                deliveryFeeInput.disabled = true;
            } else {
                deliveryFeeField.style.display = 'block';
                deliveryFeeInput.disabled = false;
            }
        }

        // Toggle specific delivery details based on pickup checkbox
        function togglePickup() {
            const pickupCheckbox = document.getElementById('pickup');
            const freeShippingCheckbox = document.getElementById('free_shipping');
            const deliveryFeeInput = document.getElementById('delivery_fee');
            const deliveryFeeField = document.getElementById('delivery_fee_field');
            const deliveryAddressField = document.getElementById('delivery_address_field');

            if (pickupCheckbox.checked) {
                // Hide Delivery Address
                deliveryAddressField.style.display = 'none';

                // Uncheck and hide Free Shipping if it's checked
                if (freeShippingCheckbox.checked) {
                    freeShippingCheckbox.checked = false;
                    toggleDeliveryFee();
                }

                // Hide Delivery Fee
                deliveryFeeField.style.display = 'none';
                deliveryFeeInput.value = '0.00';
                deliveryFeeInput.disabled = true;
            } else {
                // Show Delivery Address
                deliveryAddressField.style.display = 'block';

                // Show Delivery Fee based on Free Shipping status
                toggleDeliveryFee();
            }
        }

        // Auto-generate Customer Name based on Contact Number
        function autoGenerateCustomerName() {
            const contactInput = document.getElementById('contact');
            const customerNameInput = document.getElementById('customer_name');
            
            // Extract digits from contact number
            const digits = contactInput.value.replace(/\D/g, '');
            if (digits.length > 0) {
                customerNameInput.value = 'Order_' + digits;
            } else {
                customerNameInput.value = '';
            }
        }

        // Initialize on DOM content loaded
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize delivery fee toggle
            toggleDeliveryFee();
            const freeShippingEl = document.getElementById('free_shipping');
            if (freeShippingEl) {
                freeShippingEl.addEventListener('change', toggleDeliveryFee);
            }

            // Initialize pickup toggle
            togglePickup();
            const pickupEl = document.getElementById('pickup');
            if (pickupEl) {
                pickupEl.addEventListener('change', togglePickup);
            }

            // Initialize Customer Name auto-generation
            const contactEl = document.getElementById('contact');
            if (contactEl) {
                contactEl.addEventListener('input', autoGenerateCustomerName);
            }

            // Initialize tooltip functionality
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('.tooltip'))
            tooltipTriggerList.forEach(function (tooltipTriggerEl) {
                var tooltipText = tooltipTriggerEl.querySelector('.tooltiptext');
                tooltipTriggerEl.addEventListener('mouseenter', function() {
                    tooltipText.style.visibility = 'visible';
                    tooltipText.style.opacity = '1';
                });
                tooltipTriggerEl.addEventListener('mouseleave', function() {
                    tooltipText.style.visibility = 'hidden';
                    tooltipText.style.opacity = '0';
                });
            });
        });
    </script>

</head>
<body class="font-inter bg-gray-100">

    <!-- Include header.php inside the body -->
    <?php require_once '../../includes/header.php'; ?>

    <!-- Main Container -->
    <main class="container mx-auto p-6">
        <!-- Page Header -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-blue-600 flex items-center">
                <i class="bi bi-pencil-square mr-2"></i> Edit Order #<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?>
            </h1>
        </div>

        <!-- Welcome Section -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <p class="text-gray-700">Update the details of the order below. Ensure all changes are accurate before submission.</p>
        </div>

        <!-- Form Container -->
        <div class="bg-white rounded-lg shadow-lg p-6">
            <?php if (!empty($error)): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 flex items-center">
                    <i class="bi bi-exclamation-triangle-fill mr-2"></i>
                    <span><?= $error ?></span>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="edit_order.php?id=<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?>">
                <!-- Customer Details -->
                <div class="mb-6">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">Customer Details</h2>
                    
                    <div class="flex flex-col md:flex-row md:space-x-6">
                        <div class="flex-1 mb-4 md:mb-0">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="customer_name">
                                Customer Name <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Automatically generated based on contact number. If unavailable, enter the customer's full name for record purposes.
                                    </span>
                                </span>
                            </label>
                            <input type="text" id="customer_name" name="customer_name" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                                   value="<?= htmlspecialchars($customer_name ?? $order['customer_name'], ENT_QUOTES, 'UTF-8') ?>" 
                                   placeholder="Enter customer name" required>
                        </div>
                        <div class="flex-1 mb-4 md:mb-0">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="country">
                                Country <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Select the customer’s country to ensure accurate address formatting and delivery options. Default is set based on existing contact.
                                    </span>
                                </span>
                            </label>
                            <select name="country" id="country" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                                <?php foreach($countries as $country => $code): ?>
                                    <option value="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>" <?= ($selected_country === $code) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($country . " (" . $code . ")", ENT_QUOTES, 'UTF-8') ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="flex flex-col md:flex-row md:space-x-6 mt-4">
                        <div class="flex-1 mb-4 md:mb-0" id="contact_field">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="contact">
                                Contact Number <span class="text-red-500">*</span>
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Enter a valid contact number without the country code. The country code is auto-prepended based on selected country.
                                    </span>
                                </span>
                            </label>
                            <input type="text" id="contact" name="contact" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                                   value="<?= htmlspecialchars($contact_number, ENT_QUOTES, 'UTF-8') ?>" 
                                   required placeholder="Enter contact number without country code">
                        </div>
                        <div class="flex-1" id="delivery_address_field">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_address">
                                Delivery Address
                                <span class="tooltip">
                                    <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                    <span class="tooltiptext">
                                        Provide the full delivery address, including building name, street, area, and any special instructions to facilitate easy and efficient delivery.
                                    </span>
                                </span>
                            </label>
                            <textarea id="delivery_address" name="delivery_address" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" rows="3" placeholder="Enter delivery address"><?= htmlspecialchars($delivery_address ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
                        </div>
                    </div>
                </div>
                <hr class="my-6">

                <!-- Order Details -->
                <div class="mb-6">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Details</h2>
                    
                    <!-- Priority Selection -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Order Priority
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Choose a priority level for this order based on urgency: Normal for standard processing, Important for prioritized handling, and Quick for immediate attention.
                                </span>
                            </span>
                        </label>
                        <div class="flex space-x-4">
                            <?php
                                $priorities = ['Normal', 'Important', 'Quick'];
                                foreach ($priorities as $priority_option):
                                    $checked = ($priority === $priority_option) ? 'checked' : '';
                            ?>
                                <label class="inline-flex items-center">
                                    <input type="radio" name="priority" value="<?= htmlspecialchars($priority_option, ENT_QUOTES, 'UTF-8') ?>" class="form-radio text-teal-600" <?= $checked ?> required>
                                    <span class="ml-2"><?= htmlspecialchars($priority_option, ENT_QUOTES, 'UTF-8') ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Status Selection -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Order Status
                            <span class="text-red-500">*</span>
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Update the current status of the order: Pending, In Progress, Completed, or Delivered.
                                </span>
                            </span>
                        </label>
                        <select name="status" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                            <option value="Pending" <?= ($status == 'Pending') ? 'selected' : '' ?>>Pending</option>
                            <option value="In Progress" <?= ($status == 'In Progress') ? 'selected' : '' ?>>In Progress</option>
                            <option value="Completed" <?= ($status == 'Completed') ? 'selected' : '' ?>>Completed</option>
                            <option value="Delivered" <?= ($status == 'Delivered') ? 'selected' : '' ?>>Delivered</option>
                        </select>
                    </div>

                    <!-- Delivery Fee and Free Shipping -->
                    <div class="mb-4" id="delivery_fee_field">
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Delivery Fee (KWD)
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Enter any applicable delivery fee in Kuwaiti Dinar (KWD). This field will automatically set to 0 if ‘Free Shipping’ is selected or if pickup is chosen.
                                </span>
                            </span>
                        </label>
                        <input type="number" step="0.01" min="0" name="delivery_fee" id="delivery_fee" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                               value="<?= htmlspecialchars($delivery_fee, ENT_QUOTES, 'UTF-8') ?>" 
                               <?= ($free_shipping || $pickup) ? 'disabled' : '' ?> required>
                    </div>
                    <div class="flex items-center mb-4">
                        <input type="checkbox" id="free_shipping" name="free_shipping" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= $free_shipping ? 'checked' : '' ?> onchange="toggleDeliveryFee()">
                        <label for="free_shipping" class="ml-2 block text-sm text-gray-700">
                            Free Shipping
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Select this option if the customer qualifies for free shipping based on promotional offers or order amount. Delivery fees will automatically update.
                                </span>
                            </span>
                        </label>
                    </div>

                    <!-- Pickup Checkbox -->
                    <div class="flex items-center mb-4">
                        <input type="checkbox" id="pickup" name="pickup" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= $pickup ? 'checked' : '' ?> onchange="togglePickup()">
                        <label for="pickup" class="ml-2 block text-sm text-gray-700">
                            Customer Pickup
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Select this option if the customer will pick up the order directly from our kitchen, eliminating the need for delivery.
                                </span>
                            </span>
                        </label>
                    </div>

                    <!-- Delivery Date and Time -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_datetime">
                            Delivery Date and Time
                            <span class="tooltip">
                                <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                <span class="tooltiptext">
                                    Choose a specific date and time for the order delivery or pickup. Ensure the date aligns with the customer’s availability and our schedule to avoid delays.
                                </span>
                            </span>
                        </label>
                        <input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 
                               value="<?= htmlspecialchars($delivery_datetime ? date('Y-m-d\TH:i', strtotime($delivery_datetime)) : '', ENT_QUOTES, 'UTF-8') ?>" 
                               required>
                    </div>
                </div>
                <hr class="my-6">

                <!-- Order Items -->
                <div class="mb-6">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Items</h2>
                    
                    <!-- Existing Order Items -->
                    <div class="mb-4">
                        <h3 class="text-lg font-semibold mb-2">Existing Items</h3>
                        <?php if (empty($order_items)): ?>
                            <p>No existing items for this order.</p>
                        <?php else: ?>
                            <?php foreach ($order_items as $index => $item): ?>
                                <div class="border border-gray-300 rounded-lg p-4 mb-4">
                                    <input type="hidden" name="existing_item_id[]" value="<?= htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') ?>">
                                    <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="existing_product_id_<?= $index ?>">
                                                Product <span class="text-red-500">*</span>
                                            </label>
                                            <select name="existing_product_id[]" id="existing_product_id_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
                                                <option value="">Select Product</option>
                                                <?php foreach($products as $product_option): ?>
                                                    <option value="<?= htmlspecialchars($product_option['id'], ENT_QUOTES, 'UTF-8') ?>" <?= ($product_option['id'] == $item['product_id']) ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)", ENT_QUOTES, 'UTF-8') ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="existing_quantity_<?= $index ?>">
                                                Quantity <span class="text-red-500">*</span>
                                            </label>
                                            <input type="number" name="existing_quantity[]" id="existing_quantity_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="<?= htmlspecialchars($item['quantity'], ENT_QUOTES, 'UTF-8') ?>" required>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="existing_packaging_preferences_<?= $index ?>">
                                                Packaging Preferences
                                            </label>
                                            <input type="text" name="existing_packaging_preferences[]" id="existing_packaging_preferences_<?= $index ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($item['packaging_preferences'], ENT_QUOTES, 'UTF-8') ?>">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700" for="existing_discount_<?= $index ?>">
                                                Apply Discount
                                            </label>
                                            <div class="flex items-center mt-1">
                                                <input type="checkbox" name="existing_apply_discount[]" id="existing_discount_checkbox_<?= $index ?>" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, <?= $index ?>)" <?= ($item['discount_percentage'] > 0) ? 'checked' : '' ?>>
                                                <label for="existing_discount_checkbox_<?= $index ?>" class="ml-2 block text-sm text-gray-700">
                                                    Yes
                                                </label>
                                            </div>
                                            <div id="discount_fields_<?= $index ?>" class="discount-fields mt-2" style="display: <?= ($item['discount_percentage'] > 0) ? 'block' : 'none' ?>;">
                                                <label class="block text-sm font-medium text-gray-700" for="existing_discount_percentage_<?= $index ?>">
                                                    Discount Percentage (%) <span class="text-red-500">*</span>
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Enter the discount percentage to be applied to this product. It should be between 0 and 100.
                                                        </span>
                                                    </span>
                                                </label>
                                                <input type="number" name="existing_discount_percentage[]" id="existing_discount_percentage_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" value="<?= htmlspecialchars($item['discount_percentage'], ENT_QUOTES, 'UTF-8') ?>" required>
                                                
                                                <label class="block text-sm font-medium text-gray-700 mt-2" for="existing_discount_reason_<?= $index ?>">
                                                    Discount Reason <span class="text-red-500">*</span>
                                                    <span class="tooltip">
                                                        <i class="bi bi-question-circle text-gray-400 text-sm"></i>
                                                        <span class="tooltiptext">
                                                            Provide a reason for the discount applied to this product.
                                                        </span>
                                                    </span>
                                                </label>
                                                <input type="text" name="existing_discount_reason[]" id="existing_discount_reason_<?= $index ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" value="<?= htmlspecialchars($item['discount_reason'], ENT_QUOTES, 'UTF-8') ?>" required>
                                            </div>
                                        </div>
                                        <div class="flex items-center">
                                            <label class="flex items-center">
                                                <input type="checkbox" name="deleted_existing_item_ids[]" value="<?= htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') ?>" class="h-4 w-4 text-red-600 border-gray-300 rounded">
                                                <span class="ml-2 text-sm text-gray-700">Delete</span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>

                    <!-- New Order Items -->
                    <div class="mb-4">
                        <h3 class="text-lg font-semibold mb-2">Add New Items</h3>
                        <div id="new-products-container">
                            <!-- New Product Rows will be added here -->
                        </div>
                        <button type="button" class="bg-teal-500 text-white px-4 py-2 rounded-lg hover:bg-teal-600 transition duration-300 flex items-center gap-2 mt-4" onclick="addProductRow()">
                            <i class="bi bi-plus-circle-fill"></i> Add Another Product
                        </button>
                    </div>
                </div>
                <hr class="my-6">

                <!-- Submit Button -->
                <div class="mb-6">
                    <button type="submit" class="w-full bg-green-500 text-white px-4 py-3 rounded-lg hover:bg-green-600 transition duration-300 flex justify-center items-center gap-2">
                        <i class="bi bi-save"></i> Update Order
                    </button>
                </div>
            </form>
        </div>

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

    <!-- Bootstrap JS Bundle (optional if using Bootstrap components) -->
    <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Flatpickr JS for Date Picker -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <!-- Flatpickr Initialization -->
    <script>
        flatpickr("#delivery_datetime", {
            enableTime: true,
            dateFormat: "Y-m-d\\TH:i",
            minDate: "today"
        });
    </script>

</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>) type full codes