in thsi codes (<?php
// public/orders/add_order.php

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

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

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

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

// 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",
    // ... (Add all other countries as needed)
    "Kuwait" => "+965",
    // Continue adding countries up to the desired list
];

// 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);
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate input
    $selected_country = sanitize_input($_POST['country'] ?? '+965');
    $contact_input = sanitize_input($_POST['contact'] ?? '');
    $delivery_address = sanitize_input($_POST['delivery_address'] ?? '');

    // Ensure contact number contains only digits
    $contact_digits = preg_replace('/\D/', '', $contact_input);
    if (empty($contact_digits)) {
        $error = "A valid contact number is required.";
    } else {
        // Full contact number with country code
        $full_contact = $selected_country . $contact_digits;

        // Generate customer name
        $customer_name = 'Order_' . $contact_digits;
    }

    $priority = sanitize_input($_POST['priority'] ?? 'Normal');
    $free_shipping = isset($_POST['free_shipping']) ? 1 : 0;
    $delivery_fee = $free_shipping ? 0.00 : (isset($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00);

    // Validate priority
    $valid_priorities = ['Normal', 'Important', 'Quick'];
    if (!in_array($priority, $valid_priorities)) {
        $priority = 'Normal';
    }

    // Handle multiple products
    $product_ids = $_POST['product_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $packaging_preferences = $_POST['packaging_preferences'] ?? [];
    $apply_discount = $_POST['apply_discount'] ?? [];
    $discount_percentages = $_POST['discount_percentage'] ?? [];
    $discount_reasons = $_POST['discount_reason'] ?? [];

    // Basic validation
    if (empty($customer_name)) {
        $error = "Customer name generation failed.";
    } elseif (empty($contact_input)) {
        $error = "Contact number is required.";
    } elseif (empty($product_ids) || !is_array($product_ids) || count($product_ids) == 0) {
        $error = "At least one product must be selected.";
    } else {
        // Validate each product entry
        foreach ($product_ids as $index => $pid) {
            if (empty($pid)) {
                $error = "Product selection is required for all items.";
                break;
            }
            if (!isset($quantities[$index]) || intval($quantities[$index]) <= 0) {
                $error = "Quantity must be at least 1 for all items.";
                break;
            }
            // If discount is applied, validate discount fields
            if (isset($apply_discount[$index])) {
                $discount = trim($discount_percentages[$index]);
                $reason = trim($discount_reasons[$index]);
                if ($discount === '') {
                    $error = "Discount percentage is required if discount is applied.";
                    break;
                }
                if (!is_numeric($discount) || floatval($discount) < 0 || floatval($discount) > 100) {
                    $error = "Invalid discount percentage for product. It should be between 0 and 100.";
                    break;
                }
                if (empty($reason)) {
                    $error = "Discount reason is required if discount is applied.";
                    break;
                }
            }
        }

        // Validate delivery_datetime
        $delivery_datetime_input = $_POST['delivery_datetime'] ?? '';
        if (!empty($delivery_datetime_input)) {
            // Convert from 'Y-m-d\TH:i' to 'Y-m-d H:i:s'
            $delivery_datetime = sanitize_input(str_replace('T', ' ', $delivery_datetime_input) . ':00');
            if (!preg_match("/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/", $delivery_datetime)) {
                $error = "Invalid delivery date and time format.";
            } elseif (strtotime($delivery_datetime) < strtotime(date('Y-m-d H:i:s'))) {
                $error = "Delivery date and time cannot be in the past.";
            }
        } else {
            $delivery_datetime = null;
        }

        // Validate delivery_fee if not free shipping
        if (!$free_shipping) {
            if (!isset($_POST['delivery_fee']) || !is_numeric($_POST['delivery_fee']) || floatval($_POST['delivery_fee']) < 0) {
                $error = "Valid delivery fee is required.";
            }
        }
    }

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

        try {
            // Insert into customers table using prepared statement
            $stmt = $conn->prepare("INSERT INTO customers (name, contact, delivery_address) VALUES (?, ?, ?)");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }
            $stmt->bind_param("sss", $customer_name, $full_contact, $delivery_address);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $customer_id = $stmt->insert_id;
            $stmt->close();

            // Insert into orders table using prepared statement
            $status = 'Pending'; // Default status
            $stmt = $conn->prepare("INSERT INTO orders (customer_id, status, priority, delivery_datetime, delivery_fee, free_shipping) VALUES (?, ?, ?, ?, ?, ?)");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }
            $stmt->bind_param("isssdi", $customer_id, $status, $priority, $delivery_datetime, $delivery_fee, $free_shipping);
            if (!$stmt->execute()) {
                throw new Exception("Execute failed: " . $stmt->error);
            }
            $order_id = $stmt->insert_id;
            $stmt->close();

            // Insert products into order_items table
            $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);
            }

            // Loop through each product
            foreach ($product_ids as $index => $pid) {
                $pid = intval($pid);
                $qty = intval($quantities[$index]);
                $pack_pref = sanitize_input($packaging_preferences[$index] ?? '');

                // Handle discount
                $discount_percent = 0.00;
                $discount_rs = null;
                if (isset($apply_discount[$index])) {
                    $discount_percent = floatval(trim($discount_percentages[$index]));
                    $discount_rs = sanitize_input($discount_reasons[$index]);
                }

                $stmt->bind_param("iiisds", $order_id, $pid, $qty, $pack_pref, $discount_percent, $discount_rs);
                if (!$stmt->execute()) {
                    throw new Exception("Execute failed: " . $stmt->error);
                }
            }

            $stmt->close();

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

            // Redirect to view_orders.php after successful addition
            header("Location: view_orders.php?success=1");
            exit();
        } catch (Exception $e) {
            // Rollback transaction
            $conn->rollback();
            $error = "Error adding order: " . $e->getMessage();
        }
    }
}

// Now include the header AFTER form handling
require_once '../../includes/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add New Order - Kaak Alia Management System</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="/kaak_alia_management_system/assets/bootstrap/css/bootstrap.min.css">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Flatpickr CSS for Date Picker -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <!-- Custom Styles -->
    <style>
        /* ---------------------------------------------------
           1. CSS Variables for Consistent Design
        ---------------------------------------------------- */
        :root {
            /* Primary Colors */
            --background-color: #FFFFFF; /* Crisp White */
            --light-grey: #F5F5F5;
            --medium-grey: #E0E0E0;
            --dark-grey: #333333;
            --charcoal: #4A4A4A;

            /* Accent Colors */
            --accent-purple: #8A65FF;
            --accent-yellow: #FFD166;
            --accent-blue: #4A90E2;
            --accent-green: #50C878;
            --accent-red: #FF6B6B;

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

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

            /* Button Colors */
            --button-primary: var(--accent-purple);
            --button-secondary: var(--accent-blue);
            --button-danger: var(--accent-red);

            /* Status Badge Colors */
            --badge-pending: #FFD166; /* Yellow */
            --badge-in-progress: #8A65FF; /* Purple */
            --badge-completed: #50C878; /* Green */
            --badge-delivered: #4A90E2; /* Blue */
        }

        /* Custom scrollbar for better UX */
        ::-webkit-scrollbar {
            width: 8px;
        }

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

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

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

        /* ---------------------------------------------------
           2. Global Styles
        ---------------------------------------------------- */
        body {
            font-family: 'Roboto', sans-serif;
            background-color: var(--light-grey);
            margin: 0;
            padding: 0;
            color: var(--primary-text);
        }

        .container-body {
            max-width: 1200px;
            margin: 40px auto;
            padding: 40px 20px;
            box-sizing: border-box;
            background-color: var(--background-color);
            box-shadow: var(--box-shadow);
            border-radius: var(--box-border-radius);
            font-family: 'Roboto', sans-serif;
            transition: all 0.3s ease;
        }

        /* ---------------------------------------------------
           3. Header Styles
        ---------------------------------------------------- */
        .header {
            padding: 20px 30px;
            background-color: var(--background-color);
            display: flex;
            align-items: center;
            justify-content: center; /* Center the content */
            margin-bottom: 30px;
            border-bottom: 1px solid var(--light-grey);
        }

        .header h1 {
            color: var(--charcoal);
            font-size: 32px;
            font-weight: 700;
            font-family: 'Poppins', sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .header h1 i {
            margin-right: 10px;
            font-size: 28px;
            color: var(--accent-purple);
        }

        /* ---------------------------------------------------
           4. Welcome Section
        ---------------------------------------------------- */
        .welcome-section {
            background-color: var(--background-color);
            box-shadow: var(--box-shadow);
            border-radius: var(--box-border-radius);
            padding: 30px;
            text-align: center;
            margin-bottom: 30px;
            font-family: 'Poppins', sans-serif;
        }

        .welcome-section h3 {
            font-size: 28px;
            color: var(--primary-text);
            margin-bottom: 10px;
            font-weight: 700;
            display: none; /* Removed "Add New Order" from welcome section */
        }

        .welcome-section p {
            font-size: 16px;
            color: var(--secondary-text);
            margin: 0;
        }

        /* Decorative Line Under Welcome Section */
        .welcome-section::after {
            content: "";
            display: block;
            width: 80px;
            height: 4px;
            background: linear-gradient(90deg, var(--accent-blue), var(--accent-purple));
            margin: 15px auto 0;
            border-radius: 2px;
        }

        /* ---------------------------------------------------
           5. Form Container Styles
        ---------------------------------------------------- */
        .form-container {
            background-color: var(--background-color);
            box-shadow: var(--box-shadow);
            border-radius: var(--box-border-radius);
            padding: 30px;
            max-width: 900px;
            margin: auto;
            font-family: 'Roboto', sans-serif;
        }

        .form-container h3 {
            text-align: center;
            margin-bottom: 30px;
            color: var(--accent-blue);
            font-family: 'Poppins', sans-serif;
            font-size: 28px;
            font-weight: 700;
        }

        /* ---------------------------------------------------
           6. Form Styles
        ---------------------------------------------------- */
        .form-control {
            border-radius: var(--box-border-radius);
            border: 1px solid var(--input-border);
            background-color: #ffffff;
            padding: 12px;
            box-shadow: var(--box-shadow);
            transition: border-color 0.3s, box-shadow 0.3s;
            width: 100%;
            margin-bottom: 20px;
            font-family: 'Roboto', sans-serif;
            color: var(--primary-text);
            font-size: 16px;
        }

        .form-control::placeholder {
            color: #AAAAAA;
            font-style: italic;
        }

        .form-control:focus {
            border-color: var(--accent-blue);
            box-shadow: 0 0 5px var(--accent-blue);
            outline: none;
        }

        .form-label {
            margin-bottom: 5px;
            font-size: 14px;
            text-align: left;
            font-family: 'Poppins', sans-serif;
            font-weight: 600;
            color: var(--secondary-text);
        }

        /* ---------------------------------------------------
           7. Order Priority Styles
        ---------------------------------------------------- */
        .order-priority {
            display: flex;
            gap: 25px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }

        .order-priority label {
            cursor: pointer;
            position: relative;
            padding-left: 35px;
            user-select: none;
            font-weight: 600;
            transition: color 0.3s;
            font-family: 'Poppins', sans-serif;
            color: var(--secondary-text);
        }

        .order-priority input[type="radio"] {
            position: absolute;
            opacity: 0;
            cursor: pointer;
        }

        .order-priority .custom-radio {
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            height: 20px;
            width: 20px;
            background-color: #fff;
            border: 2px solid var(--input-border);
            border-radius: 50%;
            transition: background-color 0.3s, border-color 0.3s;
        }

        .order-priority label:hover input ~ .custom-radio {
            border-color: var(--accent-blue);
        }

        .order-priority input:checked ~ .custom-radio {
            background-color: var(--accent-blue);
            border-color: var(--accent-blue);
        }

        .order-priority .custom-radio::after {
            content: "";
            position: absolute;
            display: none;
        }

        .order-priority input:checked ~ .custom-radio::after {
            display: block;
        }

        .order-priority .custom-radio::after {
            top: 6px;
            left: 6px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: white;
        }

        /* ---------------------------------------------------
           8. Buttons Section
        ---------------------------------------------------- */
        .add-product-button,
        .remove-product-button,
        .submit-button {
            border: none;
            border-radius: 50px; /* Pill-shaped */
            padding: 10px 20px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s, transform 0.3s, box-shadow 0.3s;
            font-family: 'Poppins', sans-serif;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .add-product-button {
            background-color: var(--accent-purple);
            color: #ffffff;
            margin-top: 10px;
        }

        .add-product-button:hover {
            background-color: #7e5aff;
            transform: scale(1.05);
            box-shadow: 0 4px 12px var(--hover-shadow);
        }

        .remove-product-button {
            background-color: var(--button-danger);
            color: #ffffff;
        }

        .remove-product-button:hover {
            background-color: #e63946;
            transform: scale(1.05);
            box-shadow: 0 4px 12px var(--hover-shadow);
        }

        .submit-button {
            width: 100%;
            height: 50px;
            font-weight: bold;
            background-color: var(--accent-blue);
            color: #ffffff;
            justify-content: center;
            font-family: 'Poppins', sans-serif;
            box-shadow: var(--box-shadow);
            gap: 10px;
        }

        .submit-button:hover {
            background-color: #357ABD;
            transform: scale(1.02);
            box-shadow: 0 4px 12px var(--hover-shadow);
        }

        /* ---------------------------------------------------
           9. Alert Styles
        ---------------------------------------------------- */
        .alert-success,
        .alert-danger {
            border-radius: var(--box-border-radius);
            padding: 15px 20px;
            margin-bottom: 20px;
            text-align: center;
            width: 100%;
            margin: 20px auto;
            font-family: 'Poppins', sans-serif;
            font-size: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .alert-success {
            background-color: var(--badge-completed);
            color: #ffffff;
        }

        .alert-danger {
            background-color: var(--badge-delivered);
            color: #ffffff;
        }

        /* ---------------------------------------------------
           10. Footer Styles
        ---------------------------------------------------- */
        .footer {
            background-color: var(--background-color);
            color: var(--secondary-text);
            padding: 20px;
            text-align: center;
            border-radius: var(--box-border-radius);
            font-size: 14px;
            line-height: 22px;
            margin-top: 40px;
            font-family: 'Roboto', sans-serif;
            box-shadow: var(--box-shadow);
        }

        /* ---------------------------------------------------
           11. Responsive Design Enhancements
        ---------------------------------------------------- */
        @media (max-width: 768px) {
            .header h1 {
                font-size: 24px;
            }

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

            .form-container h3 {
                font-size: 24px;
            }

            .action-button {
                flex: 1 1 100%;
                height: 50px;
                font-size: 14px;
            }

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

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

            .submit-button {
                height: 50px;
                font-size: 16px;
            }
        }

        @media (max-width: 480px) {
            .container-body {
                padding: 20px 10px;
            }

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

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

            .form-container h3 {
                font-size: 20px;
            }

            .form-control {
                font-size: 13px;
            }

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

            .submit-button {
                height: 45px;
                font-size: 14px;
            }

            .order-priority {
                flex-direction: column;
            }
        }

        /* ---------------------------------------------------
           12. Additional Styles for Enhanced UI
        ---------------------------------------------------- */
        /* Card Styles for Product Rows */
        .product-row {
            background-color: var(--light-grey);
            border: 1px solid var(--input-border);
            border-radius: var(--box-border-radius);
            padding: 20px;
            position: relative;
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .product-row:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 16px var(--hover-shadow);
        }

        /* Icon Styles */
        .icon-primary {
            color: var(--accent-purple);
            font-size: 20px;
        }

        /* Transition for discount fields */
        .discount-fields {
            transition: all 0.3s ease-in-out;
        }

        /* Country Selector Styles */
        .country-selector {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .country-selector select {
            width: 150px;
        }
    </style>    
    
    <!-- Additional JavaScript for dynamic product addition, discount handling, and delivery fee toggle -->
    <script>
        let productCount = <?= isset($product_ids) ? count($product_ids) : 1; ?>;

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

            const productRow = document.createElement('div');
            productRow.className = 'product-row mb-3';
            productRow.innerHTML = `
                <div class="row">
                    <div class="col-md-4">
                        <label class="form-label" for="product_id_${productCount}">Product <span class="text-danger">*</span></label>
                        <select name="product_id[]" id="product_id_${productCount}" class="form-control" required>
                            <option value="">Select Product</option>
                            <?php
                            // Reset the products_result pointer
                            $products_result->data_seek(0);
                            while($product = $products_result->fetch_assoc()): ?>
                                <option value="<?= htmlspecialchars($product['id']) ?>">
                                    <?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label" for="quantity_${productCount}">Quantity <span class="text-danger">*</span></label>
                        <input type="number" name="quantity[]" id="quantity_${productCount}" class="form-control" min="1" value="1" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label" for="packaging_preferences_${productCount}">Packaging Preferences</label>
                        <input type="text" name="packaging_preferences[]" id="packaging_preferences_${productCount}" class="form-control" placeholder="e.g., Gift Wrap">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label" for="discount_${productCount}">Apply Discount</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_${productCount}" name="apply_discount[]">
                            <label class="form-check-label" for="discount_checkbox_${productCount}">
                                Yes
                            </label>
                        </div>
                        <div id="discount_fields_${productCount}" class="discount-fields" style="display: none; margin-top: 10px;">
                            <label class="form-label" for="discount_percentage_${productCount}">Discount Percentage (%) <span class="text-danger">*</span></label>
                            <input type="number" name="discount_percentage[]" id="discount_percentage_${productCount}" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
                            
                            <label class="form-label mt-2" for="discount_reason_${productCount}">Discount Reason <span class="text-danger">*</span></label>
                            <input type="text" name="discount_reason[]" id="discount_reason_${productCount}" class="form-control" placeholder="Enter reason for discount">
                        </div>
                    </div>
                    <div class="col-md-12 d-flex justify-content-end mt-3">
                        <button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
                    </div>
                </div>
            `;
            productContainer.appendChild(productRow);

            // Initialize discount toggle for the new row
            const newCheckbox = productRow.querySelector(`input[name="apply_discount[]"]`);
            newCheckbox.addEventListener('change', function() {
                toggleDiscountFields(this, productCount);
            });

            productCount++;
        }

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

        // Toggle discount fields based on checkbox
        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 delivery fee field based on free shipping checkbox
        function toggleDeliveryFee() {
            const freeShippingCheckbox = document.getElementById('free_shipping');
            const deliveryFeeField = document.getElementById('delivery_fee_field');
            const deliveryFeeInput = document.getElementById('delivery_fee');
            if (freeShippingCheckbox.checked) {
                deliveryFeeField.style.display = 'none';
                deliveryFeeInput.value = '0.00';
                deliveryFeeInput.disabled = true;
            } else {
                deliveryFeeField.style.display = 'block';
                deliveryFeeInput.disabled = false;
            }
        }

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

        // Add event listeners to existing discount checkboxes on page load
        function initializeDiscountToggle() {
            const discountCheckboxes = document.querySelectorAll('input[name="apply_discount[]"]');
            discountCheckboxes.forEach((checkbox, index) => {
                checkbox.addEventListener('change', function() {
                    toggleDiscountFields(this, index);
                });
            });
        }

        // Initialize on DOM content loaded
        document.addEventListener('DOMContentLoaded', function() {
            // Add initial product row if none exist
            if (document.getElementById('products-container').children.length === 0) {
                addProductRow();
            }

            // Initialize discount toggles
            initializeDiscountToggle();

            // Initialize delivery fee toggle
            toggleDeliveryFee();

            document.getElementById('free_shipping').addEventListener('change', toggleDeliveryFee);

            // Initialize Customer Name auto-generation
            document.getElementById('contact').addEventListener('input', autoGenerateCustomerName);
        });
    </script>

</head>
<body>

    <main class='container-body'>
        <!-- Header -->
        <div class="header">
            <h1><i class="bi bi-cart-plus"></i>Add New Order</h1>
            <!-- You can add navigation or user info here -->
        </div>

        <!-- Welcome Section -->
        <div class="welcome-section">
            <p>Fill out the form below to add a new customer order.</p>
        </div>

        <!-- Form Container -->
        <div class="form-container">
            <?php if (!empty($error)): ?>
                <div class="alert-danger d-flex align-items-center">
                    <i class="bi bi-exclamation-triangle-fill"></i> <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($success)): ?>
                <div class="alert-success d-flex align-items-center">
                    <i class="bi bi-check-circle-fill"></i> <?= htmlspecialchars($success) ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="add_order.php">
                <!-- Customer Details -->
                <div class="form-section">
                    <h5 class="mb-3">Customer Details</h5>
                    

                    <label class="form-label" for="customer_name">Customer Name <span class="text-danger">*</span></label>
                    <input type="text" id="customer_name" name="customer_name" class="form-control" 
                           value="<?= htmlspecialchars($_POST['customer_name'] ?? '') ?>" 
                           required placeholder="Auto-generated based on contact number">
                    <!-- Country Selector -->
                    <div class="country-selector">
                        <label class="form-label" for="country">Country <span class="text-danger">*</span></label>
                        <select name="country" id="country" class="form-control" required>
                            <?php foreach($countries as $country => $code): ?>
                                <option value="<?= htmlspecialchars($code) ?>" <?= (($_POST['country'] ?? '+965') === $code) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($country . " (" . $code . ")") ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <label class="form-label" for="contact">Contact <span class="text-danger">*</span></label>
                    <input type="text" id="contact" name="contact" class="form-control" 
                           value="<?= htmlspecialchars($_POST['contact'] ?? '') ?>" 
                           required placeholder="Enter contact number without country code">
                    
                    <label class="form-label" for="delivery_address">Delivery Address</label>
                    <textarea id="delivery_address" name="delivery_address" class="form-control" rows="3"><?= htmlspecialchars($_POST['delivery_address'] ?? '') ?></textarea>
                </div>
                <hr>
                <!-- Order Details -->
                <div class="form-section">
                    <h5 class="mb-3">Order Details</h5>
                    <!-- Priority Selection -->
                    <label class="form-label">Order Priority</label>
                    <div class="order-priority">
                        <label>
                            <input type="radio" name="priority" value="Normal" <?= (($_POST['priority'] ?? 'Normal') === 'Normal') ? 'checked' : '' ?>>
                            <span class="custom-radio"></span>
                            Normal (Default)
                        </label>
                        <label>
                            <input type="radio" name="priority" value="Important" <?= (($_POST['priority'] ?? '') === 'Important') ? 'checked' : '' ?>>
                            <span class="custom-radio"></span>
                            Important
                        </label>
                        <label>
                            <input type="radio" name="priority" value="Quick" <?= (($_POST['priority'] ?? '') === 'Quick') ? 'checked' : '' ?>>
                            <span class="custom-radio"></span>
                            Quick
                        </label>
                    </div>
                    <!-- Products Selection -->
                    <div id="products-container">
                        <!-- Product Rows will be added here -->
                        <?php
                        // If form was submitted with errors, repopulate the product rows
                        if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($error) && !empty($product_ids) && is_array($product_ids)) {
                            foreach ($product_ids as $i => $pid) {
                                ?>
                                <div class="product-row mb-3">
                                    <div class="row">
                                        <div class="col-md-4">
                                            <label class="form-label" for="product_id_<?= $i ?>">Product <span class="text-danger">*</span></label>
                                            <select name="product_id[]" id="product_id_<?= $i ?>" class="form-control" required>
                                                <option value="">Select Product</option>
                                                <?php
                                                $products_result->data_seek(0);
                                                while($product = $products_result->fetch_assoc()):
                                                    $selected = ($product['id'] == $pid) ? 'selected' : '';
                                                ?>
                                                    <option value="<?= htmlspecialchars($product['id']) ?>" <?= $selected ?>>
                                                        <?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label" for="quantity_<?= $i ?>">Quantity <span class="text-danger">*</span></label>
                                            <input type="number" name="quantity[]" id="quantity_<?= $i ?>" class="form-control" min="1" value="<?= isset($quantities[$i]) ? intval($quantities[$i]) : '1' ?>" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label" for="packaging_preferences_<?= $i ?>">Packaging Preferences</label>
                                            <input type="text" name="packaging_preferences[]" id="packaging_preferences_<?= $i ?>" class="form-control" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($packaging_preferences[$i] ?? '') ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label" for="discount_<?= $i ?>">Apply Discount</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_<?= $i ?>" name="apply_discount[]" <?= isset($apply_discount[$i]) ? 'checked' : '' ?>>
                                                <label class="form-check-label" for="discount_checkbox_<?= $i ?>">
                                                    Yes
                                                </label>
                                            </div>
                                            <div id="discount_fields_<?= $i ?>" class="discount-fields" style="display: <?= isset($apply_discount[$i]) ? 'block' : 'none' ?>; margin-top: 10px;">
                                                <label class="form-label" for="discount_percentage_<?= $i ?>">Discount Percentage (%) <span class="text-danger">*</span></label>
                                                <input type="number" name="discount_percentage[]" id="discount_percentage_<?php echo $i; ?>" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage" value="<?= htmlspecialchars($discount_percentages[$i] ?? '') ?>">
                                                
                                                <label class="form-label mt-2" for="discount_reason_<?= $i ?>">Discount Reason <span class="text-danger">*</span></label>
                                                <input type="text" name="discount_reason[]" id="discount_reason_<?php echo $i; ?>" class="form-control" placeholder="Enter reason for discount" value="<?= htmlspecialchars($discount_reasons[$i] ?? '') ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-12 d-flex justify-content-end mt-3">
                                            <button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
                                        </div>
                                    </div>
                                </div>
                                <?php
                            }
                        } else {
                            // Add one default product row
                            ?>
                            <div class="product-row mb-3">
                                <div class="row">
                                    <div class="col-md-4">
                                        <label class="form-label" for="product_id_0">Product <span class="text-danger">*</span></label>
                                        <select name="product_id[]" id="product_id_0" class="form-control" required>
                                            <option value="">Select Product</option>
                                            <?php
                                            $products_result->data_seek(0);
                                            while($product = $products_result->fetch_assoc()): ?>
                                                <option value="<?= htmlspecialchars($product['id']) ?>">
                                                    <?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label" for="quantity_0">Quantity <span class="text-danger">*</span></label>
                                        <input type="number" name="quantity[]" id="quantity_0" class="form-control" min="1" value="1" required>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label" for="packaging_preferences_0">Packaging Preferences</label>
                                        <input type="text" name="packaging_preferences[]" id="packaging_preferences_0" class="form-control" placeholder="e.g., Gift Wrap">
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label" for="discount_0">Apply Discount</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_0" name="apply_discount[]">
                                            <label class="form-check-label" for="discount_checkbox_0">
                                                Yes
                                            </label>
                                        </div>
                                        <div id="discount_fields_0" class="discount-fields" style="display: none; margin-top: 10px;">
                                            <label class="form-label" for="discount_percentage_0">Discount Percentage (%) <span class="text-danger">*</span></label>
                                            <input type="number" name="discount_percentage[]" id="discount_percentage_0" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
                                            
                                            <label class="form-label mt-2" for="discount_reason_0">Discount Reason <span class="text-danger">*</span></label>
                                            <input type="text" name="discount_reason[]" id="discount_reason_0" class="form-control" placeholder="Enter reason for discount">
                                        </div>
                                    </div>
                                    <div class="col-md-12 d-flex justify-content-end mt-3">
                                        <button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
                                    </div>
                                </div>
                            </div>
                            <?php
                        }
                        ?>
                    </div>
                    <button type="button" class="add-product-button btn btn-secondary" onclick="addProductRow()"><i class="bi bi-plus-circle-fill"></i> Add Another Product</button>
                    
                    <!-- Delivery Details -->
                    <hr>
                    <div class="form-section delivery-section">
                        <h5 class="mb-3">Delivery Details</h5>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" value="1" id="free_shipping" name="free_shipping" <?= isset($_POST['free_shipping']) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="free_shipping">
                                Free Shipping
                            </label>
                        </div>
                        <div id="delivery_fee_field" class="delivery-fee-field">
                            <label class="form-label" for="delivery_fee">Delivery Fee (KD)</label>
                            <input type="number" step="0.01" min="0" name="delivery_fee" id="delivery_fee" class="form-control" 
                                   value="<?= isset($_POST['delivery_fee']) ? htmlspecialchars($_POST['delivery_fee']) : '0.00' ?>" 
                                   <?= isset($_POST['free_shipping']) ? 'disabled' : '' ?>>
                        </div>
                        <label class="form-label" for="delivery_datetime">Delivery Date and Time</label>
                        <input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="form-control" 
                               value="<?= htmlspecialchars($_POST['delivery_datetime'] ?? '') ?>">
                    </div>
                </div>
                <!-- Submit Button -->
                <button type="submit" class="submit-button btn btn-primary"><i class="bi bi-plus-lg"></i> Add Order</button>
            </form>
        </div>

        <!-- Footer -->
        <div class="footer">
            &copy; 2024 Kaak Alia Bakery. All rights reserved.
        </div>
    </main>
    <!-- Bootstrap JS Bundle -->
    <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <!-- 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>

    <!-- Bootstrap Tooltip Initialization -->
    <script>
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
        })
    </script>

</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>)  make hte contact readable easy when enter and add more codes to make it better