in this order (<?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 and database connection **before** any output
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';

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

// 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
    $customer_name = sanitize_input($_POST['customer_name']);
    $contact = sanitize_input($_POST['contact']);
    $delivery_address = sanitize_input($_POST['delivery_address']);
    $delivery_datetime = isset($_POST['delivery_datetime']) && !empty($_POST['delivery_datetime']) ? sanitize_input($_POST['delivery_datetime']) : null;
    $priority = isset($_POST['priority']) ? sanitize_input($_POST['priority']) : 'Normal';

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

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

    // Basic validation
    if (empty($customer_name)) {
        $error = "Customer name is required.";
    } elseif (empty($product_ids) || !is_array($product_ids)) {
        $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 (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
        if ($delivery_datetime && !preg_match("/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/", $delivery_datetime)) {
            $error = "Invalid delivery date and time format.";
        } elseif ($delivery_datetime && strtotime(str_replace('T', ' ', $delivery_datetime)) < strtotime(date('Y-m-d H:i'))) {
            $error = "Delivery date and time cannot be in the past.";
        }
    }

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

        try {
            // 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, $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) VALUES (?, ?, ?, ?)");
            if (!$stmt) {
                throw new Exception("Prepare statement failed: " . $conn->error);
            }
            $stmt->bind_param("isss", $customer_id, $status, $priority, $delivery_datetime);
            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("iiidds", $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=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
    
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="/kaak_alia_management_system/assets/bootstrap/css/bootstrap.min.css">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Flatpickr CSS for Date Picker -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <!-- Embedded Custom Styles -->
    <style>
        /* ---------------------------------------------------
           1. CSS Variables for Consistent Design
        ---------------------------------------------------- */
        :root {
            --dark-gray: #515151; /* Primary text and key elements */
            --soft-brown: #b78d67; /* Secondary color for accents and buttons */
            --deep-brown: #8e6a51; /* Accent color for interactive elements */
            --white: #ffffff; /* White background and button text */
            --light-gray: #f9f9f9; /* Light gray for input backgrounds and alternate table rows */
            --divider-color: #FFD166; /* Yellow for dividers */
            --error-color: #EF476F; /* Red-pink for error messages */
            --success-color: #06D6A0; /* Green for success messages */
            --hover-shadow: rgba(0, 0, 0, 0.2);
            --transition-speed: 0.3s;
        }

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

        h3, h5, label {
            color: var(--dark-gray);
            font-weight: 600;
        }

        .form-section {
            margin-bottom: 20px;
        }

        /* ---------------------------------------------------
           3. Header Styles
        ---------------------------------------------------- */
        .header {
            padding: 20px 30px;
            background-color: var(--dark-gray);
            border-radius: 8px;
            text-align: center;
            margin-bottom: 30px;
            color: var(--white);
            font-size: 24px;
            font-weight: bold;
        }

        /* ---------------------------------------------------
           4. Welcome Section
        ---------------------------------------------------- */
        .welcome-section {
            background-color: #ffffff;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin-bottom: 30px;
        }

        .welcome-section h3 {
            font-size: 20px;
            color: var(--dark-gray);
            margin-bottom: 10px;
        }

        .welcome-section hr {
            width: 50px;
            height: 3px;
            background-color: var(--divider-color);
            border: none;
            margin: 10px auto 0;
        }

        /* ---------------------------------------------------
           5. Form Container Styles
        ---------------------------------------------------- */
        .form-container {
            background-color: #ffffff;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border-radius: 8px;
            padding: 30px;
            max-width: 900px;
            margin: auto;
        }

        .form-container h3 {
            text-align: center;
            margin-bottom: 20px;
            color: var(--soft-brown);
        }

        /* ---------------------------------------------------
           6. Form Styles
        ---------------------------------------------------- */
        .form-control {
            border-radius: 8px;
            border: 1px solid #ccc;
            background-color: var(--light-gray);
            padding: 12px 15px;
            transition: border-color var(--transition-speed), box-shadow var(--transition-speed);
            width: 100%;
            margin: 0 auto 15px auto;
            display: block;
        }

        .form-control:focus {
            border-color: var(--deep-brown);
            box-shadow: 0 0 5px rgba(142, 106, 81, 0.3);
            background-color: #ffffff;
        }

        .form-label {
            margin-bottom: 5px;
            font-size: 14px;
            display: block;
            text-align: left;
            width: 100%;
            margin: 0 auto 5px auto;
        }

        .add-product-button {
            background-color: var(--soft-brown);
            color: var(--white);
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
            transition: background-color var(--transition-speed);
        }

        .add-product-button:hover {
            background-color: var(--deep-brown);
        }

        .remove-product-button {
            background-color: #dc3545;
            color: var(--white);
            border: none;
            padding: 6px 10px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color var(--transition-speed);
        }

        .remove-product-button:hover {
            background-color: #c82333;
        }

        /* ---------------------------------------------------
           7. Buttons Section
        ---------------------------------------------------- */
        .submit-button {
            width: 100%;
            height: 50px;
            font-size: 18px;
            font-weight: bold;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            transition: transform var(--transition-speed), box-shadow var(--transition-speed);
            padding: 10px 20px;
            display: block;
            margin: 20px auto 0 auto;
            text-align: center;
            background-color: #FFD166;
            color: var(--white);
        }

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

        /* ---------------------------------------------------
           8. Alert Styles
        ---------------------------------------------------- */
        .alert-success {
            background-color: var(--success-color);
            color: var(--white);
            border-radius: 8px;
            padding: 15px 20px;
            margin-bottom: 20px;
            text-align: center;
            width: 100%;
            margin: 20px auto;
        }

        .alert-danger {
            background-color: var(--error-color);
            color: var(--white);
            border-radius: 8px;
            padding: 15px 20px;
            margin-bottom: 20px;
            text-align: center;
            width: 100%;
            margin: 20px auto;
        }

        /* ---------------------------------------------------
           9. Responsive Design Enhancements
        ---------------------------------------------------- */
        @media (max-width: 768px) {
            .form-control, .form-label, .submit-button, .alert-success, .alert-danger {
                width: 100%;
            }
        }

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

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

            .form-control, .form-label, .submit-button, .alert-success, .alert-danger {
                width: 100%;
            }

            .submit-button {
                height: 50px;
                font-size: 16px;
            }
        }
    </style>

    <!-- Additional JavaScript for dynamic product addition and discount handling -->
    <script>
        function addProductRow() {
            const productContainer = document.getElementById('products-container');
            const productCount = productContainer.children.length;

            const productRow = document.createElement('div');
            productRow.className = 'product-row border p-3 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}" 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);
            });
        }

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

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

</head>
<body>

    <!-- Header Already Included via header.php -->
<main class='container-body'>
    <!-- Welcome Section -->
    <div class="welcome-section mt-20">
        <h3>Add a New Order</h3>
        <hr>
    </div>

    <!-- Form Container -->
    <div class="form-container">
        <h3>Add New Order</h3>
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <form method="POST" action="add_order.php">
            <!-- Customer Details -->
            <div class="form-section">
                <h5>Customer Details</h5>
                <label class="form-label" for="customer_name">Name <span class="text-danger">*</span></label>
                <input type="text" id="customer_name" name="customer_name" class="form-control" 
                       value="<?= isset($_POST['customer_name']) ? htmlspecialchars($_POST['customer_name']) : '' ?>" 
                       required>
                
                <label class="form-label" for="contact">Contact</label>
                <input type="text" id="contact" name="contact" class="form-control" 
                       value="<?= isset($_POST['contact']) ? htmlspecialchars($_POST['contact']) : '' ?>">
                
                <label class="form-label" for="delivery_address">Delivery Address</label>
                <textarea id="delivery_address" name="delivery_address" class="form-control"><?= isset($_POST['delivery_address']) ? htmlspecialchars($_POST['delivery_address']) : '' ?></textarea>
            </div>
            <hr>
            <!-- Order Details -->
            <div class="form-section">
                <h5>Order Details</h5>
                <!-- Priority Selection -->
                <label class="form-label">Order Priority</label>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="priority" id="priority_normal" value="Normal" <?= (isset($_POST['priority']) && $_POST['priority'] === 'Normal') || !isset($_POST['priority']) ? 'checked' : '' ?>>
                    <label class="form-check-label" for="priority_normal">
                        Normal (Default)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="priority" id="priority_important" value="Important" <?= isset($_POST['priority']) && $_POST['priority'] === 'Important' ? 'checked' : '' ?>>
                    <label class="form-check-label" for="priority_important">
                        Important
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="priority" id="priority_quick" value="Quick" <?= isset($_POST['priority']) && $_POST['priority'] === 'Quick' ? 'checked' : '' ?>>
                    <label class="form-check-label" for="priority_quick">
                        Quick
                    </label>
                </div>
                <hr>
                <!-- 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 border p-3 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="<?= isset($packaging_preferences[$i]) ? 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 ?>" 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_<?= $i ?>" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage" value="<?= isset($discount_percentages[$i]) ? 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_<?= $i ?>" class="form-control" placeholder="Enter reason for discount" value="<?= isset($discount_reasons[$i]) ? 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 border p-3 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" 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 DateTime Field -->
                <hr>
                <div class="form-section">
                    <h5>Delivery Details</h5>
                    <label class="form-label" for="delivery_datetime">Delivery Date and Time</label>
                    <input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="form-control" 
                           value="<?= isset($_POST['delivery_datetime']) ? htmlspecialchars($_POST['delivery_datetime']) : '' ?>">
                </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 text-center mt-10">
        &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>

    <!-- 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
?>) it shows error (Fatal error: Uncaught Error: Call to undefined function sanitize_input() in /home/u406552082/domains/longevacare.com/public_html/kaakalia/public/orders/add_order.php:31 Stack trace: #0 {main} thrown in /home/u406552082/domains/longevacare.com/public_html/kaakalia/public/orders/add_order.php on line 31) when add new order so fix plz and type full codes, and this info database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 09, 2024 at 12:13 PM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34

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


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

--
-- Database: `u406552082_kaakalia`
--

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `password`, `role`) VALUES
(1, 'kaakalia', '$2y$10$tEdSPRwL8WTXljuAxNh.m.af/8sHd/ouDB21Bgs1bC7GkbRq/h0D6', 'admin');

--
-- Indexes for dumped tables
--

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

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

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

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

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

--
-- AUTO_INCREMENT for dumped tables
--

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

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

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

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

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

--
-- Constraints for dumped tables
--

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

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

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;) and i want to show products and addicaotnal products to customer on dataabae andtype full codes