fix this codes (<?php
// public/orders/add_order.php

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

// Start output buffering to prevent header issues
ob_start();

// Include authentication/database/functions -- adjust paths as needed
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php';

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

// Initialize variables
$error = '';
$customer_name = '';
$full_contact = '';
$priority = 'Normal';            // Default priority
$payment_method = 'Payment Link';// Default payment method (important to set early)
$selected_country = '+965';      // Default country code

// An array of countries with their dialing codes
$countries = [
    "Kuwait" => "+965",
];
$kuwaitCities = [ "Al Asimah (Capital)", "Hawalli", "Farwaniya", "Mubarak Al-Kabeer", "Ahmadi", "Jahra" ];

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

// If form submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Gather data
    $contact_input = sanitize_input($_POST['contact'] ?? '');
    $city_selected = sanitize_input($_POST['city'] ?? '');
    $address_details = sanitize_input($_POST['address_details'] ?? '');
    $customer_name_input = sanitize_input($_POST['customer_name'] ?? '');
    $pickup = isset($_POST['pickup']) ? 1 : 0;
    $notes = sanitize_input($_POST['notes'] ?? ''); // We'll store in orders.notes

    // Payment items
    $payment_method_post = $_POST['payment_method'] ?? 'Payment Link'; // Get raw post value for debugging
    $payment_method = sanitize_input($payment_method_post);  // Get and sanitize payment method
    if (!in_array($payment_method, ['Cash','Payment Link','Free Order'])) {
        $payment_method = 'Payment Link'; // Default if something fishy happens
    }
    $free_order_reason = sanitize_input($_POST['free_order_reason'] ?? '');

    // Delivery & shipping
    $free_shipping = (!$pickup && isset($_POST['free_shipping'])) ? 1 : 0;
    $delivery_fee = $pickup ? 0.00 : floatval($_POST['delivery_fee'] ?? 0.00);

    // Priority
    $priority = sanitize_input($_POST['priority'] ?? 'Normal');
    if (!in_array($priority, ['Normal','Important','Quick'])) {
        $priority = 'Normal';
    }

    // Validate contact
    $contact_digits = preg_replace('/\D/', '', $contact_input);
    if (empty($contact_digits)) {
        $error = "A valid contact number is required.";
    } else {
        // If user selected a country code (or default +965)
        $selected_country = sanitize_input($_POST['country'] ?? '+965');
        $full_contact = $selected_country . $contact_digits;

        // Auto-generate customer name if not provided
        $customer_name = $customer_name_input ?: (
            $pickup ? 'pickup_' . $contact_digits : 'order_' . $contact_digits
        );
    }

    // Validate date/time
    $delivery_datetime = null;
    if (!empty($_POST['delivery_date']) && !empty($_POST['delivery_time'])) {
        $delivery_date_input = sanitize_input($_POST['delivery_date']);
        $delivery_time_input = sanitize_input($_POST['delivery_time']);
        $dt_string = $delivery_date_input . ' ' . $delivery_time_input . ':00';
        $delivery_parsed = DateTime::createFromFormat('Y-m-d H:i:s', $dt_string);
        if (!$delivery_parsed) {
            $error = "Invalid delivery date/time format.";
        } else {
            // Check if in the past
            $now = new DateTime('now');
            if ($delivery_parsed < $now) {
                $error = "Delivery date/time cannot be in the past.";
            } else {
                $delivery_datetime = $delivery_parsed->format('Y-m-d H:i:s');
            }
        }
    } else {
        $error = "Delivery date and time are required fields.";
    }

    // Validate city if not pickup
    if (!$pickup) {
        if (!in_array($city_selected, $kuwaitCities) || empty($city_selected)) {
            $error = "Please select a valid city in Kuwait.";
        }
    }

    // If free order, require reason
    if ($payment_method === 'Free Order' && empty($free_order_reason)) {
        $error = "Please provide a reason for the free order.";
    }

    // Check selected products
    $product_ids = $_POST['product_id'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    if (empty($product_ids)) {
        $error = "At least one product must be selected.";
    }

    // If no errors, insert
    if (empty($error)) {
        $conn->begin_transaction();
        try {
            // Insert or find existing customer
            $full_address = $pickup ? '' : ($city_selected . "\n" . $address_details);

            // Check if a customer with same contact exists
            $stmt = $conn->prepare("SELECT id FROM customers WHERE contact = ?");
            $stmt->bind_param("s", $full_contact);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $customer_id = $row['id'];
                // Possibly update name/address
                $updateStmt = $conn->prepare("UPDATE customers SET name = ?, delivery_address = ? WHERE id = ?");
                $updateStmt->bind_param("ssi", $customer_name, $full_address, $customer_id);
                $updateStmt->execute();
                $updateStmt->close();
            } else {
                // Insert new
                $stmt = $conn->prepare("INSERT INTO customers (name, contact, delivery_address) VALUES (?, ?, ?)");
                $stmt->bind_param("sss", $customer_name, $full_contact, $full_address);
                $stmt->execute();
                $customer_id = $stmt->insert_id;
                $stmt->close();
            }

            // --- DEBUGGING: Log payment method values RIGHT BEFORE INSERT ---
            error_log("DEBUG: Payment Method value before order insert: " . $payment_method);
            error_log("DEBUG: Payment Method raw POST value: " . $payment_method_post);
            error_log("DEBUG: Final payment_method value being inserted: " . $payment_method);
            // -------------------------------------------------------

            // Insert order
             // ADDED: default status is "Pending"
             $status = 'Pending';
             // Ensure the payment method is stored (important part)
            $sql_insert_order = "
                INSERT INTO orders
                    (customer_id, status, priority, order_date, delivery_datetime, delivery_fee, free_shipping, pickup, payment_method, free_order_reason, notes)
                VALUES
                    (?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?)
            ";
            $stmt = $conn->prepare($sql_insert_order);

             // --- DEBUGGING: Check for prepare statement error ---
            if (!$stmt) {
                $error_message = "Prepare statement failed: " . $conn->error;
                error_log("DEBUG ERROR: " . $error_message);
                throw new Exception($error_message);
            }
            // ----------------------------------------------------

            // --- DEBUGGING: Check the values being bound ---
            error_log("DEBUG: Binding parameters - customer_id: " . $customer_id . ", status: " . $status . ", priority: " . $priority . ", delivery_datetime: " . $delivery_datetime . ", delivery_fee: " . $delivery_fee . ", free_shipping: " . $free_shipping . ", pickup: " . $pickup . ", payment_method: " . $payment_method . ", free_order_reason: " . $free_order_reason . ", notes: " . $notes);
            // ----------------------------------------------------


            $stmt->bind_param(
                "isssdiiiss",
                $customer_id,
                $status,           // "Pending"
                $priority,
                $delivery_datetime,
                $delivery_fee,
                $free_shipping,
                $pickup,
                $payment_method,   // <<-- Payment method is here!
                $free_order_reason,
                $notes
            );

            if (!$stmt->execute()) {
                $error_message = "Execute statement failed: " . $stmt->error;
                error_log("DEBUG ERROR: " . $error_message); // Log to server logs
                throw new Exception($error_message); // Throw exception to rollback and show error
            }
            $order_id = $stmt->insert_id;
            $stmt->close();

            // Insert order items
            $stmt = $conn->prepare("
                INSERT INTO order_items
                    (order_id, product_id, quantity, packaging_preferences, discount_percentage, discount_reason)
                VALUES
                    (?, ?, ?, ?, ?, ?)
            ");

            foreach ($product_ids as $index => $pid) {
                $qty = intval($quantities[$index] ?? 1);
                $pack_pref = sanitize_input($_POST['packaging_preferences'][$index] ?? '');

                // Check discount
                $discount_checked = isset($_POST['apply_discount'][$index]);
                if ($discount_checked) {
                    $discount_percent = floatval($_POST['discount_percentage'][$index] ?? 0);
                    $discount_reason = sanitize_input($_POST['discount_reason'][$index] ?? '');
                } else {
                    $discount_percent = 0.0;
                    $discount_reason = '';
                }

                $stmt->bind_param(
                    "iiisds",
                    $order_id,
                    $pid,
                    $qty,
                    $pack_pref,
                    $discount_percent,
                    $discount_reason
                );
                $stmt->execute();
            }
            $stmt->close();

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

            // Redirect to view_orders.php with a success flag AND the new order ID
            header("Location: view_orders.php?success=1&order_id=" . $order_id);
            exit;

        } catch (Exception $e) {
            $conn->rollback();
            $error = "Error processing order: " . $e->getMessage();
            error_log("Full Error: " . $error); // Log full error for detailed debugging
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!-- Responsive Design -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Order - Kaak Alia Management System</title>

    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"
    >
    <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"
    >

    <style>
        /* Existing minimal styling - keep for general layout if needed, can be removed if fully replaced by Tailwind */
        .section-card {
            background-color: #fff;
            border-radius: 0.5rem;
            padding: 1.5rem;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        .form-label {
            @apply block text-sm font-medium text-gray-700;
        }
        .form-input {
            @apply w-full border border-gray-300 rounded-md p-2 mt-1;
        }
        .form-select {
            @apply w-full border border-gray-300 rounded-md p-2 mt-1;
        }
        .form-textarea {
            @apply w-full border border-gray-300 rounded-md p-2 mt-1;
        }
        .form-checkbox {
            @apply h-4 w-4 text-teal-600 border-gray-300 rounded;
        }
         .form-radio {
            @apply form-radio text-teal-600;
        }
        .btn-primary {
            @apply bg-teal-500 text-white px-4 py-2 rounded hover:bg-teal-600 transition flex items-center gap-2;
        }
        .btn-danger {
            @apply bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600 transition flex items-center gap-2;
        }
        .error-message {
           @apply bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4 flex items-center;
        }
        .product-row{
            @apply bg-gray-50 p-4 rounded-lg shadow-md mb-4;
        }

        /* Modal Styles - Now with more Tailwind classes */
        .modal-overlay {
            @apply fixed top-0 left-0 w-full h-full bg-gray-500 opacity-50 z-40;
        }

        .modal-container {
            @apply fixed top-0 left-0 w-full h-full flex items-center justify-center z-50;
        }

        .modal-content {
            @apply bg-white p-6 rounded-lg shadow-xl text-left max-w-xl mx-auto;
        }

        .modal-header {
            @apply mb-4 border-b pb-2;
        }

        .modal-body {
            @apply mb-6;
        }

        .modal-footer {
            @apply flex justify-end gap-4 border-t pt-4;
        }
    </style>

</head>
<body class="bg-gray-100">
<?php require_once '../../includes/header.php'; ?>

<main class="container mx-auto p-6">
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-teal-600 flex items-center">
            <i class="bi bi-cart-plus mr-2"></i> Add New Order
        </h1>
    </div>

    <div class="section-card">
        <?php if (!empty($error)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4 flex items-center">
                <i class="bi bi-exclamation-triangle-fill mr-2"></i>
                <span><?= htmlspecialchars($error) ?></span>
            </div>
        <?php endif; ?>

        <form id="addOrderForm" method="POST" action="add_order.php">
            <!-- Customer -->
            <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 mb-4">
                <!-- name -->
                <div class="flex-1">
                    <label class="form-label" for="customer_name">
                        Customer Name
                    </label>
                    <input
                        type="text"
                        id="customer_name"
                        name="customer_name"
                        class="form-input"
                        value="<?= htmlspecialchars($customer_name ?? '') ?>"
                        placeholder="e.g. Ahmed"
                    >
                </div>
                <!-- country -->
                <div class="flex-1">
                    <label class="form-label" for="country">
                        Country
                    </label>
                    <select
                        name="country"
                        id="country"
                        class="form-select"
                    >
                        <?php foreach($countries as $cName => $cCode): ?>
                            <option value="<?= htmlspecialchars($cCode) ?>"
                                <?= ($selected_country === $cCode) ? 'selected' : '' ?>
                            >
                                <?= htmlspecialchars($cName . " (" . $cCode . ")") ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <!-- contact -->
            <div class="mb-4">
                <label class="form-label" for="contact">
                    Contact Number
                </label>
                <input
                    type="text"
                    id="contact"
                    name="contact"
                    class="form-input"
                    value="<?= htmlspecialchars($_POST['contact'] ?? '') ?>"
                    placeholder="e.g., 66667777"
                    oninput="autoGenerateCustomerName()"
                >
            </div>
            <hr class="my-6">

            <!-- Priority / Products -->
            <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Details</h2>
            <!-- priority -->
            <div class="mb-4">
                <label class="form-label">Order Priority</label>
                <div class="flex space-x-4">
                    <?php foreach(['Normal','Important','Quick'] as $pOpt): ?>
                        <label class="inline-flex items-center">
                            <input
                                type="radio"
                                name="priority"
                                value="<?= htmlspecialchars($pOpt) ?>"
                                <?= ($priority === $pOpt) ? 'checked' : '' ?>
                                class="form-radio"
                            >
                            <span class="ml-2"><?= htmlspecialchars($pOpt) ?></span>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- products area -->
            <div class="mb-4">
                <div class="flex justify-between items-center mb-2">
                    <label class="form-label">
                        Products
                    </label>
                    <button
                        type="button"
                        class="btn-primary"
                        onclick="addProductRow()"
                    >
                        <i class="bi bi-plus-circle-fill"></i> Add Product
                    </button>
                </div>
                <div id="products-container">
                    <?php
                    // If there's old POST data, re-populate. Otherwise, show one default row.
                    $product_ids = $_POST['product_id'] ?? [];
                    $quantities = $_POST['quantity'] ?? [];
                    if (!empty($error) && !empty($product_ids) && is_array($product_ids)) {
                        foreach($product_ids as $idx => $pid) {
                            $qty = intval($quantities[$idx] ?? 1);
                            $pack_pref = $_POST['packaging_preferences'][$idx] ?? '';
                            $discount_checked = isset($_POST['apply_discount'][$idx]);
                            $discount_percent = $_POST['discount_percentage'][$idx] ?? '';
                            $discount_reason = $_POST['discount_reason'][$idx] ?? '';
                            ?>
                            <div class="product-row">
                                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                                    <div>
                                        <label class="form-label">Product</label>
                                        <select name="product_id[]" class="form-select">
                                            <option value="">Select Product</option>
                                            <?php foreach($products as $p): ?>
                                                <?php
                                                    $selected = ($p['id'] == $pid) ? 'selected' : '';
                                                    $pLabel = htmlspecialchars($p['name']." - ".$p['size']." (".number_format($p['price'],2)." KD)");
                                                ?>
                                                <option value="<?= $p['id'] ?>" <?= $selected ?>><?= $pLabel ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="form-label">Quantity</label>
                                        <input
                                            type="number"
                                            name="quantity[]"
                                            min="1"
                                            value="<?= htmlspecialchars($qty) ?>"
                                            class="form-input"
                                        >
                                    </div>
                                    <div>
                                        <label class="form-label">Packaging</label>
                                        <input
                                            type="text"
                                            name="packaging_preferences[]"
                                            value="<?= htmlspecialchars($pack_pref) ?>"
                                            class="form-input"
                                            placeholder="e.g., Gift Wrap"
                                        >
                                    </div>
                                    <div>
                                        <label class="form-label">Discount</label>
                                        <div class="flex items-center mt-1">
                                            <input
                                                type="checkbox"
                                                name="apply_discount[<?= $idx ?>]"
                                                class="form-checkbox"
                                                <?php if ($discount_checked) echo 'checked'; ?>
                                                onchange="toggleDiscountFields(this, <?= $idx ?>)"
                                            >
                                            <label class="ml-2">Apply</label>
                                        </div>
                                        <div id="discount_fields_<?= $idx ?>" class="mt-2" style="<?= $discount_checked ? '' : 'display:none;' ?>">
                                            <label class="form-label">Discount (%)</label>
                                            <input
                                                type="number"
                                                name="discount_percentage[<?= $idx ?>]"
                                                min="0"
                                                max="100"
                                                step="0.01"
                                                value="<?= htmlspecialchars($discount_percent) ?>"
                                                class="form-input"
                                                placeholder="e.g., 10"
                                            >
                                            <label class="form-label mt-2">Reason</label>
                                            <input
                                                type="text"
                                                name="discount_reason[<?= $idx ?>]"
                                                value="<?= htmlspecialchars($discount_reason) ?>"
                                                class="form-input"
                                                placeholder="e.g., Special promo"
                                            >
                                        </div>
                                    </div>
                                </div>
                                <div class="flex justify-end mt-2">
                                    <button
                                        type="button"
                                        class="btn-danger"
                                        onclick="removeProductRow(this)"
                                    >
                                        <i class="bi bi-trash-fill"></i> Remove
                                    </button>
                                </div>
                            </div>
                            <?php
                        }
                    } else {
                        // Show one default row if no error data
                        ?>
                        <div class="product-row">
                            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                                <div>
                                    <label class="form-label">Product</label>
                                    <select name="product_id[]" class="form-select" required>
                                        <option value="">Select Product</option>
                                        <?php foreach($products as $p): ?>
                                            <?php
                                                $pLabel = htmlspecialchars($p['name']." - ".$p['size']." (".number_format($p['price'],2)." KD)");
                                            ?>
                                            <option value="<?= $p['id'] ?>"><?= $pLabel ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label class="form-label">Quantity</label>
                                    <input
                                        type="number"
                                        name="quantity[]"
                                        min="1"
                                        value="1"
                                        class="form-input"
                                        required
                                    >
                                </div>
                                <div>
                                    <label class="form-label">Packaging Preferences</label>
                                    <input
                                        type="text"
                                        name="packaging_preferences[]"
                                        class="form-input"
                                        placeholder="e.g., Gift Wrap"
                                    >
                                </div>
                                <div>
                                    <label class="form-label">Discount</label>
                                    <div class="flex items-center mt-1">
                                        <input
                                            type="checkbox"
                                            name="apply_discount[0]"
                                            class="form-checkbox"
                                            onchange="toggleDiscountFields(this, 0)"
                                        >
                                        <label class="ml-2">Apply</label>
                                    </div>
                                    <div id="discount_fields_0" class="mt-2" style="display:none;">
                                        <label class="form-label">Discount (%)</label>
                                        <input
                                            type="number"
                                            name="discount_percentage[0]"
                                            min="0"
                                            max="100"
                                            step="0.01"
                                            class="form-input"
                                            placeholder="e.g., 10"
                                        >
                                        <label class="form-label mt-2">Reason</label>
                                        <input
                                            type="text"
                                            name="discount_reason[0]"
                                            class="form-input"
                                            placeholder="e.g., Special promo"
                                        >
                                    </div>
                                </div>
                            </div>
                            <div class="flex justify-end mt-2">
                                <button
                                    type="button"
                                    class="btn-danger"
                                    onclick="removeProductRow(this)"
                                >
                                    <i class="bi bi-trash-fill"></i> Remove
                                </button>
                                </div>
                            </div>
                        <?php
                    }
                    ?>
                </div>
                <button
                    type="button"
                    class="btn-primary mt-4"
                    onclick="addProductRow()"
                >
                    <i class="bi bi-plus-circle-fill"></i> Add Another Product
                </button>
            </div>

            <!-- Delivery Details -->
            <hr class="my-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">Delivery Details</h2>
            <div class="mb-4">
                <input
                    type="checkbox"
                    id="pickup"
                    name="pickup"
                    class="form-checkbox"
                    <?php if(isset($_POST['pickup'])) echo 'checked'; ?>
                    onchange="togglePickup()"
                >
                <label for="pickup" class="ml-2">Customer Pickup</label>
            </div>
            <div id="delivery_details">
                <div class="mb-4" id="city_container">
                    <label class="form-label" for="city">
                        City (Kuwait)
                    </label>
                    <select
                        name="city"
                        id="city"
                        class="form-select"
                    >
                        <option value="">Select City</option>
                        <?php foreach ($kuwaitCities as $city): ?>
                            <option
                                value="<?= htmlspecialchars($city) ?>"
                                <?php if(isset($_POST['city']) && $_POST['city'] === $city) echo 'selected'; ?>
                            >
                                <?= htmlspecialchars($city) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-4" id="address_details_container">
                    <label class="form-label">Address Details</label>
                    <textarea
                        name="address_details"
                        rows="3"
                        class="form-textarea"
                        placeholder="e.g., Block 2, Street 5, House 10"
                    ><?= htmlspecialchars($_POST['address_details'] ?? '') ?></textarea>
                </div>
                <div class="mb-4" id="free_shipping_field">
                    <input
                        type="checkbox"
                        id="free_shipping"
                        name="free_shipping"
                        class="form-checkbox"
                        <?php if(isset($_POST['free_shipping']) && !$pickup) echo 'checked'; ?>
                        onchange="toggleDeliveryFee()"
                    >
                    <label for="free_shipping" class="ml-2">Free Shipping</label>
                </div>
                <div class="mb-4" id="delivery_fee_field">
                    <label class="form-label" for="delivery_fee">
                        Delivery Fee (KWD)
                    </label>
                    <input
                        type="number"
                        step="0.01"
                        min="0"
                        name="delivery_fee"
                        id="delivery_fee"
                        class="form-input"
                        value="<?= htmlspecialchars($_POST['delivery_fee'] ?? '0.00') ?>"
                        placeholder="e.g., 1.00"
                    >
                </div>
            </div>
            <div class="flex flex-col md:flex-row md:space-x-6">
                <div class="flex-1 mb-4">
                    <label class="form-label" for="delivery_date">
                        Delivery Date
                    </label>
                    <input
                        type="date"
                        name="delivery_date"
                        id="delivery_date"
                        class="form-input"
                        value="<?= htmlspecialchars($_POST['delivery_date'] ?? '') ?>"
                    >
                </div>
                <div class="flex-1 mb-4">
                    <label class="form-label" for="delivery_time">
                        Delivery Time
                    </label>
                    <input
                        type="time"
                        name="delivery_time"
                        id="delivery_time"
                        class="form-input"
                        value="<?= htmlspecialchars($_POST['delivery_time'] ?? '') ?>"
                    >
                </div>
            </div>
            <!-- Other Instructions -->
            <hr class="my-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">Other Instructions</h2>
            <div class="mb-4">
                <!-- Notes -->
                <label class="form-label" for="notes">
                    Notes
                </label>
                <textarea
                    name="notes"
                    id="notes"
                    rows="3"
                    class="form-textarea"
                    placeholder="Any extra instructions or special requests"
                ><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>
            </div>

            <!-- Payment Method -->
            <div class="mb-4">
                <label class="form-label">Payment Method</label>
                <select
                    name="payment_method"
                    id="payment_method"
                    class="form-select"
                    onchange="toggleFreeOrderReason()"
                >
                    <option value="Cash" <?= ($payment_method === 'Cash') ? 'selected' : '' ?>>Cash</option>
                    <option value="Payment Link" <?= ($payment_method === 'Payment Link') ? 'selected' : '' ?>>Payment Link</option>
                    <option value="Free Order" <?= ($payment_method === 'Free Order') ? 'selected' : '' ?>>Free Order</option>
                </select>
            </div>
            <div class="mb-4" id="free_order_reason_field" style="display:none;">
                <label class="form-label" for="free_order_reason">
                    Reason for Free Order
                </label>
                <textarea
                    name="free_order_reason"
                    id="free_order_reason"
                    rows="2"
                    class="form-textarea"
                    placeholder="e.g., influencer collaboration"
                ><?= htmlspecialchars($free_order_reason) ?></textarea>
            </div>

            <!-- (EXTRA) Add a Status selection with 4 statuses + 'Canceled' -->
             <div class="mb-4">
                <label class="form-label">Order Status</label>
                <select class="form-select" disabled>
                   <!-- Not used in the DB insertion (since we default to Pending),
                         but you said you want these 5 statuses, so let's display them. -->
                    <option value="Pending" selected>Pending</option>
                    <option value="In Progress">In Progress</option>
                    <option value="Completed">Completed</option>
                    <option value="Delivered">Delivered</option>
                    <option value="Canceled">Canceled</option>
                </select>
                <p class="text-sm text-gray-500 mt-1">Note: Actual DB insertion defaults to "Pending"</p>
            </div>

             <!-- Hidden submit button to be triggered by JS -->
            <button type="submit" id="submitBtn" class="hidden">Submit Order</button>
        </form>

        <!-- Confirm Order Modal -->
        <div id="confirmationModal" class="modal-container hidden">
            <div class="modal-overlay" onclick="closeConfirmationModal()"></div>
            <div class="modal-content bg-white p-6 rounded-lg shadow-xl text-left max-w-xl mx-auto"> <!-- Tailwind classes here -->
                <div class="modal-header mb-4 border-b pb-2">
                    <h4 class="text-xl font-semibold">Confirm Order Details</h4>
                </div>
                <div class="modal-body mb-6">
                    <p class="mb-2"><span class="font-semibold">Customer Name:</span> <span id="confirm_customer_name"></span></p>
                    <p class="mb-2"><span class="font-semibold">Contact:</span> <span id="confirm_contact"></span></p>
                    <p class="mb-2"><span class="font-semibold">Priority:</span> <span id="confirm_priority"></span></p>
                    <p class="mb-2"><span class="font-semibold">Pickup:</span> <span id="confirm_pickup"></span></p>
                    <div id="confirm_delivery_details_section">
                        <p class="mb-2"><span class="font-semibold">City:</span> <span id="confirm_city"></span></p>
                        <p class="mb-2"><span class="font-semibold">Address:</span> <span id="confirm_address_details"></span></p>
                        <p class="mb-2"><span class="font-semibold">Delivery Fee:</span> <span id="confirm_delivery_fee"></span></p>
                        <p class="mb-2"><span class="font-semibold">Free Shipping:</span> <span id="confirm_free_shipping"></span></p>
                    </div>
                    <p class="mb-2"><span class="font-semibold">Delivery Date/Time:</span> <span id="confirm_delivery_datetime"></span></p>
                    <p class="mb-2"><span class="font-semibold">Payment Method:</span> <span id="confirm_payment_method"></span></p>
                    <div id="confirm_free_order_reason_section">
                        <p class="mb-2"><span class="font-semibold">Free Order Reason:</span> <span id="confirm_free_order_reason"></span></p>
                    </div>
                    <p class="mb-2"><span class="font-semibold">Notes:</span> <span id="confirm_notes"></span></p>
                    <h5 class="font-semibold mt-4">Products:</h5>
                    <ul id="confirm_products_list" class="list-disc list-inside">
                        <!-- Product list will be populated here -->
                    </ul>
                </div>
                <div class="modal-footer flex justify-end gap-4 border-t pt-4"> <!-- Tailwind classes here -->
                    <button type="button" class="btn-primary" onclick="submitForm()">Confirm Order</button>
                    <button type="button" class="btn-danger" onclick="closeConfirmationModal()">Cancel</button>
                </div>
            </div>
        </div>

            <!-- Submit Button (now triggers modal) -->
        <div class="mt-6">
            <button
                type="button"
                class="btn-primary w-full"
                onclick="showConfirmationModal()"
            >
                <i class="bi bi-plus-lg"></i> Add Order
            </button>
        </div>
    </div>
</main>

<script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<script>
    let productCount = <?= (isset($product_ids) && is_array($product_ids) && count($product_ids)>0) ? count($product_ids) : 1; ?>;

    function addProductRow() {
        const container = document.getElementById('products-container');
        const idx = productCount++;
        const row = document.createElement('div');
        row.className = 'product-row';
        row.innerHTML = `
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                    <label class="form-label">Product</label>
                    <select name="product_id[]" class="form-select" required>
                        <option value="">Select Product</option>
                        <?php foreach ($products as $p): ?>
                            <?php
                                $pLabel = htmlspecialchars($p['name']." - ".$p['size']." (".number_format($p['price'],2)." KD)");
                            ?>
                            <option value="<?= $p['id'] ?>"><?= $pLabel ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="form-label">Quantity</label>
                    <input type="number" name="quantity[]" min="1" value="1" class="form-input" required>
                </div>
                <div>
                    <label class="form-label">Packaging Preferences</label>
                    <input type="text" name="packaging_preferences[]" class="form-input" placeholder="e.g., Gift Wrap">
                </div>
                <div>
                    <label class="form-label">Discount</label>
                    <div class="flex items-center mt-1">
                        <input type="checkbox" name="apply_discount[${idx}]" class="form-checkbox" onchange="toggleDiscountFields(this, ${idx})">
                        <label class="ml-2">Apply</label>
                    </div>
                    <div id="discount_fields_${idx}" style="display:none;" class="mt-2">
                        <label class="form-label">Discount (%)</label>
                        <input type="number" name="discount_percentage[${idx}]" min="0" max="100" step="0.01" class="form-input" placeholder="e.g., 10">
                        <label class="form-label mt-2">Reason</label>
                        <input type="text" name="discount_reason[${idx}]" class="form-input" placeholder="e.g., Special promo">
                    </div>
                </div>
            </div>
            <div class="flex justify-end mt-2">
                <button type="button" class="btn-danger" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
            </div>
        `;
        container.appendChild(row);
    }

    function removeProductRow(btn) {
        btn.closest('.product-row').remove();
    }

    function toggleDiscountFields(checkbox, idx) {
        const discountDiv = document.getElementById(`discount_fields_${idx}`);
        discountDiv.style.display = checkbox.checked ? 'block' : 'none';
        if (!checkbox.checked) {
            discountDiv.querySelectorAll('input').forEach(input => input.value = '');
        }
    }
    function togglePickup() {
        const pickup = document.getElementById('pickup').checked;
        document.getElementById('city_container').style.display = pickup ? 'none' : 'block';
        document.getElementById('address_details_container').style.display = pickup ? 'none' : 'block';
        document.getElementById('free_shipping_field').style.display = pickup ? 'none' : 'block';
        const freeShippingCheckbox = document.getElementById('free_shipping');
        freeShippingCheckbox.checked = false;  //Always reset on pickup toggle
        document.getElementById('delivery_fee_field').style.display = pickup ? 'none' : 'block';
        document.getElementById('delivery_fee').value = '0.00';
        document.getElementById('delivery_fee').disabled = pickup; // Disable if pickup

        //Trigger free shipping check
        toggleDeliveryFee();


         // Autofill customer name, only if the current name is an autogenerated one
        autoGenerateCustomerName();
    }

    function toggleDeliveryFee() {
        const freeShipping = document.getElementById('free_shipping').checked;
        const deliveryFeeField = document.getElementById('delivery_fee_field');
        const deliveryFeeInput = document.getElementById('delivery_fee');

        if (freeShipping) {
            deliveryFeeField.style.display = 'none';
            deliveryFeeInput.value = '0.00';
            deliveryFeeInput.disabled = true;
        } else {
            deliveryFeeField.style.display = 'block';
             deliveryFeeInput.disabled = false; // Enable input
        }
    }

    function toggleFreeOrderReason() {
        const paymentMethod = document.getElementById('payment_method').value;
        const reasonField = document.getElementById('free_order_reason_field');
        reasonField.style.display = (paymentMethod === 'Free Order') ? 'block' : 'none';
        document.getElementById('free_order_reason').required = (paymentMethod === 'Free Order');
        if(paymentMethod !== 'Free Order') {
            document.getElementById('free_order_reason').value = '';
        }
    }

    function autoGenerateCustomerName() {
        const contactEl = document.getElementById('contact');
        const nameEl = document.getElementById('customer_name');
        const digits = contactEl.value.replace(/\D/g, '');
        if (digits.length > 0 && (nameEl.value === '' || nameEl.value.startsWith('order_') || nameEl.value.startsWith('pickup_'))) {
            const pickup = document.getElementById('pickup').checked;
            nameEl.value = (pickup ? 'pickup_' : 'order_') + digits;
        }
    }

    function showConfirmationModal() {
        console.log("showConfirmationModal called"); // Debugging log

        // Customer Details
        document.getElementById('confirm_customer_name').textContent = document.getElementById('customer_name').value;
        document.getElementById('confirm_contact').textContent = document.getElementById('country').value + ' ' + document.getElementById('contact').value;
        document.getElementById('confirm_priority').textContent = document.querySelector('input[name="priority"]:checked').value;
        document.getElementById('confirm_pickup').textContent = document.getElementById('pickup').checked ? 'Yes' : 'No';

        //Delivery Details Section
        const deliveryDetailsSection = document.getElementById('confirm_delivery_details_section');
        if (document.getElementById('pickup').checked) {
            deliveryDetailsSection.style.display = 'none';
        } else {
            deliveryDetailsSection.style.display = 'block';
            document.getElementById('confirm_city').textContent = document.getElementById('city').value;
            document.getElementById('confirm_address_details').textContent = document.getElementById('address_details').value;
            document.getElementById('confirm_delivery_fee').textContent = document.getElementById('delivery_fee').value + ' KWD';
            document.getElementById('confirm_free_shipping').textContent = document.getElementById('free_shipping').checked ? 'Yes' : 'No';
        }

        // Delivery Date & Time
        const deliveryDate = document.getElementById('delivery_date').value;
        const deliveryTime = document.getElementById('delivery_time').value;
        document.getElementById('confirm_delivery_datetime').textContent = deliveryDate + ' ' + deliveryTime;

        // Payment Details
        document.getElementById('confirm_payment_method').textContent = document.getElementById('payment_method').value;
        const freeOrderReasonSection = document.getElementById('confirm_free_order_reason_section');
        if (document.getElementById('payment_method').value === 'Free Order') {
            freeOrderReasonSection.style.display = 'block';
            document.getElementById('confirm_free_order_reason').textContent = document.getElementById('free_order_reason').value;
        } else {
            freeOrderReasonSection.style.display = 'none';
        }

        // Notes
        document.getElementById('confirm_notes').textContent = document.getElementById('notes').value;

        // Product List
        const productList = document.getElementById('confirm_products_list');
        productList.innerHTML = ''; // Clear previous list
        const productRows = document.querySelectorAll('.product-row');

        console.log("productRows:", productRows); // Debugging log

        productRows.forEach(row => {
            console.log("Processing row:", row); // Debugging log
            const productNameSelect = row.querySelector('select[name="product_id[]"]');
            const selectedOption = productNameSelect.options[productNameSelect.selectedIndex];
            const productName = selectedOption ? selectedOption.textContent.trim() : 'Product Name Not Found'; // Handle case if no option selected

            const quantity = row.querySelector('input[name="quantity[]"]').value;
            const packaging = row.querySelector('input[name="packaging_preferences[]"]').value;
            let discountText = 'No Discount';
            if (row.querySelector('input[name^="apply_discount"]').checked) {
                const discountPercent = row.querySelector('input[name^="discount_percentage"]').value;
                const discountReason = row.querySelector('input[name^="discount_reason"]').value;
                discountText = `Discount: ${discountPercent}% - ${discountReason || 'No Reason'}`;
            }

            console.log("Product Name:", productName); // Debugging log
            console.log("Quantity:", quantity); // Debugging log
            console.log("Packaging:", packaging); // Debugging log
            console.log("Discount Text:", discountText); // Debugging log


            const listItem = document.createElement('li');
            listItem.textContent = `${productName}, Quantity: ${quantity}, Packaging: ${packaging || 'None'}, ${discountText}`;
            productList.appendChild(listItem);
        });


        document.getElementById('confirmationModal').classList.remove('hidden');
    }

    function closeConfirmationModal() {
        document.getElementById('confirmationModal').classList.add('hidden');
    }

    function submitForm() {
        document.getElementById('submitBtn').click(); // Programmatically click the hidden submit button
        closeConfirmationModal(); // Optionally close modal after submit starts
    }


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

        togglePickup(); // Initialize delivery details visibility
        toggleFreeOrderReason();  //Initialize based on pre-selected/posted value

        flatpickr("#delivery_date", {
            dateFormat: "Y-m-d",
            minDate: "today"
        });
        flatpickr("#delivery_time", {
            enableTime: true,
            noCalendar: true,
            dateFormat: "H:i"
        });
    });
</script>
</body>
</html>

<?php
ob_end_flush();
?>) and amke it sure working well and i want to fix add order button and make it working