fix this codes please (<?php
// public/orders/view_order_customer.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 necessary functions
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // For sanitize_input()

// Helper Function: Generate WhatsApp link
/**
 * Generate a WhatsApp link from a contact number.
 *
 * @param string|null $contact The contact number.
 * @return string The WhatsApp URL or a placeholder if contact is empty.
 */
function generate_whatsapp_link($contact) {
    if (empty($contact)) {
        return '#'; // Placeholder or you can handle it as per your requirement
    }

    // Remove any non-digit characters except the plus sign
    $digits = preg_replace('/[^\d+]/', '', $contact);

    // Ensure the number starts with '+'
    if (strpos($digits, '+') !== 0) {
        $digits = '+' . $digits;
    }

    // Remove '+' for WhatsApp URL
    $digits = ltrim($digits, '+');

    return "https://wa.me/" . $digits;
}

// Helper Function: Format currency
/**
 * Format a number into currency format.
 *
 * @param float|null $amount The amount to format.
 * @return string The formatted currency string.
 */
function format_currency($amount) {
    $amount = $amount ?? 0.00; // Default to 0.00 if null
    return "KWD " . number_format((float)$amount, 2);
}

// Helper Function: Get day name from datetime
/**
 * Get the day name from a datetime string.
 *
 * @param string|null $datetime The datetime string.
 * @return string The day name or 'N/A' if datetime is null or invalid.
 */
function get_day_name($datetime) {
    if ($datetime && strtotime($datetime)) {
        return date("l", strtotime($datetime));
    }
    return 'N/A';
}

// Helper Function: Calculate totals
/**
 * Calculate totals for a given set of order items.
 *
 * @param array $order_items The array of order items.
 * @param float $delivery_fee The delivery fee for the order.
 * @param int $free_shipping Indicates if free shipping is applied (1 for yes, 0 for no).
 * @param int $pickup Indicates if the order is for pickup (1 for yes, 0 for no).
 * @return array An associative array containing total_before_discounts, total_discounts, delivery_fee, and final_total.
 */
function calculate_order_totals($order_items, $delivery_fee, $free_shipping, $pickup) {
    $total_before_discounts = 0;
    $total_discounts = 0;
    $final_total = 0;

    foreach ($order_items as &$item) {
        $quantity = isset($item['quantity']) ? (int)$item['quantity'] : 0;
        $product_price = isset($item['product_price']) ? (float)$item['product_price'] : 0.00;
        $discount_percentage = isset($item['discount_percentage']) ? (float)$item['discount_percentage'] : 0.00;

        $item_total = $quantity * $product_price;
        $discount_amount = ($discount_percentage / 100) * $item_total;

        // Ensure that discount_amount and total_after_discount are always set
        $item['discount_amount'] = $discount_amount ?? 0.00;
        $item['total_after_discount'] = $item_total - ($discount_amount ?? 0.00);

        $total_before_discounts += $item_total;
        $total_discounts += $discount_amount ?? 0.00;
    }
    unset($item); // Break reference

    $final_total = $total_before_discounts - $total_discounts;

    // Add delivery fee if not free shipping and not pickup
    if (!$free_shipping && !$pickup) {
        $delivery_fee = $delivery_fee ?? 0.00;
        $final_total += $delivery_fee;
    }

    return [
        'total_before_discounts' => $total_before_discounts,
        'total_discounts' => $total_discounts,
        'delivery_fee' => (!$free_shipping && !$pickup) ? $delivery_fee : 0.00,
        'final_total' => $final_total
    ];
}

// Now include the header after handling actions
require_once __DIR__ . '/../../includes/header.php';

// Initialize variables for messages
$success_message = '';
$error_message = '';

// Check if order_id is provided and valid
$order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

if ($order_id <= 0) {
    header("Location: view_orders.php?error=6"); // Invalid order ID
    exit();
}

// Fetch order details along with customer information and is_paid status
$order_sql = "
    SELECT 
        orders.id AS order_id,
        orders.status,
        orders.priority,
        orders.order_date,
        orders.delivery_datetime,
        orders.delivery_fee,
        orders.free_shipping,
        orders.is_paid,
        orders.pickup,
        customers.name AS customer_name,
        customers.contact,
        customers.delivery_address
    FROM 
        orders
    JOIN 
        customers ON orders.customer_id = customers.id
    WHERE 
        orders.id = ?
";
$order_stmt = $conn->prepare($order_sql);
if (!$order_stmt) {
    die("Prepare failed: (" . $conn->errno . ") " . htmlspecialchars($conn->error));
}
$order_stmt->bind_param("i", $order_id);
$order_stmt->execute();
$order_result = $order_stmt->get_result();
$order = $order_result->fetch_assoc();
$order_stmt->close();

if (!$order) {
    header("Location: view_orders.php?error=7"); // Order not found
    exit();
}

// Handle Status Update Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    // Sanitize and validate inputs
    $new_status = isset($_POST['status']) ? sanitize_input($_POST['status']) : '';
    $allowed_statuses = ['Pending', 'In Progress', 'Completed', 'Delivered'];

    if (in_array($new_status, $allowed_statuses)) {
        // If setting to 'Delivered', ensure delivery_datetime is set
        if ($new_status === 'Delivered' && empty($order['delivery_datetime'])) {
            $error_message = "Cannot set status to Delivered without a delivery date and time.";
        } else {
            // Prepare SQL to update status
            $update_sql = "UPDATE orders SET status = ? WHERE id = ?";
            $update_stmt = $conn->prepare($update_sql);
            if ($update_stmt) {
                $update_stmt->bind_param("si", $new_status, $order_id);
                if ($update_stmt->execute()) {
                    $success_message = "Order status updated successfully to '" . htmlspecialchars($new_status) . "'.";
                    $order['status'] = $new_status; // Reflect change locally
                } else {
                    $error_message = "Failed to update order status. Please try again.";
                }
                $update_stmt->close();
            } else {
                $error_message = "Database error: " . htmlspecialchars($conn->error);
            }
        }
    } else {
        $error_message = "Invalid status selected.";
    }
}

// Handle Payment Status Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_payment'])) {
    // Sanitize and validate inputs
    // Expecting 'is_paid' to be present if checked
    $is_paid = isset($_POST['is_paid']) ? 1 : 0;

    // Prepare SQL to update payment status
    $update_payment_sql = "UPDATE orders SET is_paid = ? WHERE id = ?";
    $update_payment_stmt = $conn->prepare($update_payment_sql);
    if ($update_payment_stmt) {
        $update_payment_stmt->bind_param("ii", $is_paid, $order_id);
        if ($update_payment_stmt->execute()) {
            if ($is_paid) {
                $success_message = "Order marked as <strong>Paid</strong> successfully.";
            } else {
                $success_message = "Order marked as <strong>Not Paid</strong> successfully.";
            }
            $order['is_paid'] = $is_paid; // Reflect change locally
        } else {
            $error_message = "Failed to update payment status. Please try again.";
        }
        $update_payment_stmt->close();
    } else {
        $error_message = "Database error: " . htmlspecialchars($conn->error);
    }
}

// Fetch order items with product details
$order_items_sql = "
    SELECT 
        order_items.id AS item_id,
        order_items.product_id,
        order_items.quantity,
        order_items.packaging_preferences,
        order_items.discount_percentage,
        order_items.discount_reason,
        products.name AS product_name,
        products.size AS product_size,
        products.price AS product_price
    FROM 
        order_items
    JOIN 
        products ON order_items.product_id = products.id
    WHERE 
        order_items.order_id = ?
";
$item_stmt = $conn->prepare($order_items_sql);
if (!$item_stmt) {
    die("Prepare failed: (" . $conn->errno . ") " . htmlspecialchars($conn->error));
}
$item_stmt->bind_param("i", $order_id);
$item_stmt->execute();
$order_items_result = $item_stmt->get_result();
$order_items = [];
while ($item = $order_items_result->fetch_assoc()) {
    $order_items[] = $item;
}
$item_stmt->close();

// Calculate totals, including delivery fee and free shipping
$totals = calculate_order_totals($order_items, $order['delivery_fee'], $order['free_shipping'], $order['pickup']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Order #<?= htmlspecialchars($order['order_id']) ?> Details - 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">
    
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    
    <!-- Flatpickr CSS for Date Picker (if needed in future) -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

    <!-- Custom Styles -->
    <style>
        /* Custom scrollbar for better UX */
        ::-webkit-scrollbar {
            width: 8px;
        }

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

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

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

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

        /* Enhanced Card Hover Effects */
        .order-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.15);
        }

        /* Tooltip */
        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: #333;
            color: #fff;
            text-align: left;
            border-radius: 6px;
            padding: 8px;
            position: absolute;
            z-index: 10;
            bottom: 125%; /* Position above the icon */
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 0.875rem;
        }
    </style>

    <!-- Additional JavaScript for Print, Copy, and Interactivity -->
    <script>
        // Function to print the order details
        function printOrder() {
            window.print();
        }

        // Function to copy order details to clipboard
        function copyOrderDetails() {
            // Gather the required information
            const orderId = "<?= htmlspecialchars($order['order_id']) ?>";
            const status = "<?= htmlspecialchars($order['status']) ?>";
            const priority = "<?= htmlspecialchars($order['priority']) ?>";
            const orderDate = "<?= date("l, d M Y, h:i A", strtotime($order['order_date'])) ?>";
            const deliveryDateTime = "<?= get_day_name($order['delivery_datetime']) ?>, <?= $order['delivery_datetime'] ? date("l, d M Y, h:i A", strtotime($order['delivery_datetime'])) : 'N/A' ?>";
            const customerName = "<?= htmlspecialchars($order['customer_name']) ?>";
            const contactNumber = "<?= htmlspecialchars($order['contact']) ?>";
            const deliveryAddress = "<?= !empty($order['delivery_address']) ? nl2br(htmlspecialchars($order['delivery_address'])) : 'N/A' ?>";
            const deliveryFee = <?= htmlspecialchars($order['free_shipping']) == 1 ? '0.00' : htmlspecialchars($order['delivery_fee']) ?>;
            const freeShippingStatus = <?= htmlspecialchars($order['free_shipping']) == 1 ? '"Yes"' : '"No"' ?>;
            const isPaidStatus = <?= htmlspecialchars($order['is_paid']) == 1 ? '"Paid"' : '"Not Paid"' ?>;

            let productSummary = '';
            <?php foreach ($order_items as $item): ?>
                productSummary += `• Product: <?= addslashes(htmlspecialchars($item['product_name'])) ?>\n  Size: <?= addslashes(htmlspecialchars($item['product_size'])) ?>\n  Quantity: <?= addslashes(htmlspecialchars($item['quantity'])) ?>\n  Packaging: <?= addslashes(htmlspecialchars($item['packaging_preferences'])) ?>\n\n`;
            <?php endforeach; ?>

            // Construct the formatted text
            const formattedText = `🔴 Order Details 🔴
• Order ID: ${orderId}
• Status: ${status}
• Priority: ${priority}
• Order Date: ${orderDate}
• Delivery Date & Time: ${deliveryDateTime}
• Customer Name: ${customerName}

📦 Product Summary:
${productSummary}📍 Delivery Address:
${deliveryAddress}

💰 Delivery Fee: KWD ${deliveryFee} (${freeShippingStatus} Shipping)
💵 Payment Status: ${isPaidStatus}
📞 Contact Number: ${contactNumber}`;

            // Copy to clipboard using Clipboard API
            navigator.clipboard.writeText(formattedText).then(() => {
                alert('Order details copied to clipboard!');
            }).catch(err => {
                alert('Failed to copy: ' + err);
            });
        }

        // Function to toggle payment status via checkbox
        function togglePaymentStatus() {
            const paymentForm = document.getElementById('payment-form');
            paymentForm.submit();
        }

        // Close alerts after 5 seconds
        window.setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                alert.style.display = 'none';
            });
        }, 5000);
    </script>
</head>
<body class="bg-gray-100 font-roboto">
    <!-- Header Already Included via header.php -->

    <main class="container mx-auto p-6">
        <!-- Welcome Section -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <h3 class="text-2xl font-poppins font-bold text-teal-600 flex items-center">
                <i class="bi bi-box-seam-fill mr-3 text-teal-500 text-3xl"></i>
                Order #<?= htmlspecialchars($order['order_id']) ?>
            </h3>
            <hr class="my-4 border-t border-teal-500 w-32">
            <!-- Copy Info Button -->
            <button class="mt-3 flex items-center bg-gray-200 text-gray-800 px-4 py-2 rounded hover:bg-gray-300 transition duration-300" onclick="copyOrderDetails()">
                <i class="bi bi-clipboard-fill mr-2"></i> Copy Order Info
            </button>
        </div>

        <!-- Display Success or Error Messages -->
        <?php if (!empty($success_message)): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4 alert" role="alert">
                <strong class="font-bold">Success!</strong>
                <span class="block sm:inline"><?= $success_message ?></span>
                <span class="absolute top-0 bottom-0 right-0 px-4 py-3">
                    <svg class="fill-current h-6 w-6 text-green-500" role="button" onclick="this.parentElement.parentElement.style.display='none';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                        <title>Close</title>
                        <path d="M14.348 5.652a1 1 0 10-1.414-1.414L10 7.172 7.066 4.238a1 1 0 10-1.414 1.414L8.828 10l-3.176 3.176a1 1 0 101.414 1.414L10 12.828l2.934 2.934a1 1 0 001.414-1.414L11.172 10l3.176-3.176z"/>
                    </svg>
                </span>
            </div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 alert" role="alert">
                <strong class="font-bold">Error!</strong>
                <span class="block sm:inline"><?= $error_message ?></span>
                <span class="absolute top-0 bottom-0 right-0 px-4 py-3">
                    <svg class="fill-current h-6 w-6 text-red-500" role="button" onclick="this.parentElement.parentElement.style.display='none';" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                        <title>Close</title>
                        <path d="M14.348 5.652a1 1 0 10-1.414-1.414L10 7.172 7.066 4.238a1 1 0 10-1.414 1.414L8.828 10l-3.176 3.176a1 1 0 101.414 1.414L10 12.828l2.934 2.934a1 1 0 001.414-1.414L11.172 10l3.176-3.176z"/>
                    </svg>
                </span>
            </div>
        <?php endif; ?>

        <!-- Payment Status Section -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <form method="POST" id="payment-form" class="flex items-center space-x-4">
                <div class="flex items-center">
                    <input type="checkbox" id="is_paid" name="is_paid" <?= $order['is_paid'] ? 'checked' : '' ?> class="w-6 h-6 text-teal-500 bg-gray-300 rounded focus:ring-teal-500 border-gray-300" onclick="togglePaymentStatus()">
                    <label for="is_paid" class="ml-2 text-lg font-medium text-gray-700">
                        <?= $order['is_paid'] ? '<span class="text-green-600">Paid</span>' : '<span class="text-red-600">Not Paid</span>' ?>
                    </label>
                </div>
                <input type="hidden" name="update_payment" value="1">
            </form>
        </div>

        <!-- Product Summary Section -->
        <div class="bg-teal-50 border-l-4 border-teal-500 rounded-lg shadow-lg p-6 mb-8">
            <div class="flex items-center mb-4">
                <i class="bi bi-bag-fill text-teal-500 text-2xl mr-2"></i>
                <h4 class="text-xl font-semibold text-teal-700">Product Summary</h4>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php if (!empty($order_items)): ?>
                    <?php foreach ($order_items as $item): ?>
                        <div class="bg-white rounded-lg shadow p-4 flex items-start space-x-4 hover:shadow-lg transition-shadow duration-300 order-card">
                            <i class="bi bi-box-seam-fill text-teal-500 text-3xl"></i>
                            <div>
                                <p class="text-lg font-semibold text-gray-800"><?= htmlspecialchars($item['product_name']) ?></p>
                                <p class="text-gray-600"><strong>Size:</strong> <?= htmlspecialchars($item['product_size']) ?></p>
                                <p class="text-gray-600"><strong>Quantity:</strong> <?= htmlspecialchars($item['quantity']) ?></p>
                                <p class="text-gray-600"><strong>Packaging:</strong> <?= htmlspecialchars($item['packaging_preferences']) ?: 'N/A' ?></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-gray-600">No products found in this order.</p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Order Information Section -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <div class="flex items-center mb-6">
                <i class="bi bi-info-circle-fill text-teal-500 text-2xl mr-2"></i>
                <h4 class="text-xl font-semibold text-gray-800">Order Information</h4>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Status Update -->
                <div>
                    <form method="POST" class="flex items-center space-x-2">
                        <label for="status" class="text-gray-700 font-medium">Status:</label>
                        <select name="status" id="status" class="block w-full px-4 py-2 mt-1 text-gray-700 bg-white border border-gray-300 rounded-md focus:outline-none focus:ring-teal-500 focus:border-teal-500" required>
                            <?php
                                $statuses = ['Pending', 'In Progress', 'Completed', 'Delivered'];
                                foreach ($statuses as $status) {
                                    $selected = ($order['status'] === $status) ? 'selected' : '';
                                    echo "<option value=\"{$status}\" {$selected}>{$status}</option>";
                                }
                            ?>
                        </select>
                        <button type="submit" name="update_status" class="flex items-center px-4 py-2 bg-teal-500 text-white text-sm font-medium rounded-md hover:bg-teal-600 transition duration-300">
                            <i class="bi bi-arrow-repeat mr-1"></i> Update
                        </button>
                    </form>
                </div>

                <!-- Priority -->
                <div class="flex items-center">
                    <i class="bi bi-exclamation-triangle-fill text-teal-500 mr-2"></i>
                    <span class="text-gray-700 font-medium">Priority:</span>
                    <span class="ml-2 text-gray-600"><?= htmlspecialchars($order['priority']) ?></span>
                </div>

                <!-- Order Date -->
                <div class="flex items-center">
                    <i class="bi bi-calendar-event-fill text-teal-500 mr-2"></i>
                    <span class="text-gray-700 font-medium">Order Date:</span>
                    <span class="ml-2 text-gray-600"><?= date("l, d M Y, h:i A", strtotime($order['order_date'])) ?></span>
                </div>

                <!-- Delivery Date & Time -->
                <div class="flex items-center">
                    <i class="bi bi-clock-fill text-teal-500 mr-2"></i>
                    <span class="text-gray-700 font-medium">Delivery Date & Time:</span>
                    <span class="ml-2 text-gray-600">
                        <?= get_day_name($order['delivery_datetime']) ?>, 
                        <?= $order['delivery_datetime'] ? date("l, d M Y, h:i A", strtotime($order['delivery_datetime'])) : 'N/A' ?>
                    </span>
                </div>

                <!-- Customer Name -->
                <div class="flex items-center">
                    <i class="bi bi-person-fill text-teal-500 mr-2"></i>
                    <span class="text-gray-700 font-medium">Customer Name:</span>
                    <span class="ml-2 text-gray-600"><?= htmlspecialchars($order['customer_name']) ?></span>
                </div>

                <!-- Contact -->
                <div class="flex items-center">
                    <i class="bi bi-whatsapp text-teal-500 mr-2"></i>
                    <span class="text-gray-700 font-medium">Contact:</span>
                    <a href="<?= generate_whatsapp_link($order['contact']) ?>" target="_blank" class="ml-2 text-teal-600 hover:underline flex items-center">
                        <i class="bi bi-whatsapp mr-1"></i>
                        <?= htmlspecialchars($order['contact']) ?>
                    </a>
                </div>

                <!-- Delivery Address -->
                <?php if (!$order['pickup'] && !empty($order['delivery_address'])): ?>
                    <div class="flex items-start">
                        <i class="bi bi-geo-alt-fill text-teal-500 mr-2 mt-1"></i>
                        <div>
                            <span class="text-gray-700 font-medium">Delivery Address:</span>
                            <p class="ml-2 text-gray-600"><?= nl2br(htmlspecialchars($order['delivery_address'])) ?></p>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Pickup Location -->
                <?php if ($order['pickup']): ?>
                    <div class="flex items-center">
                        <i class="bi bi-shop text-teal-500 mr-2"></i>
                        <span class="text-gray-700 font-medium">Pickup Location:</span>
                        <span class="ml-2 text-indigo-600 font-semibold">Our Storefront</span>
                    </div>
                <?php endif; ?>

                <!-- Delivery Fee and Free Shipping -->
                <div class="flex items-center">
                    <i class="bi bi-cash-stack text-teal-500 mr-2"></i>
                    <span class="text-gray-700 font-medium">Delivery Fee:</span>
                    <span class="ml-2 text-gray-600">
                        <?= $order['free_shipping'] == 1 ? '<span class="text-green-600 font-semibold">Free</span>' : format_currency($order['delivery_fee']) ?>
                    </span>
                </div>

                <!-- Payment Status -->
                <div class="flex items-center">
                    <i class="bi bi-credit-card-fill text-teal-500 mr-2"></i>
                    <span class="text-gray-700 font-medium">Payment Status:</span>
                    <?php if ($order['is_paid']): ?>
                        <span class="ml-2 text-green-600 font-semibold">Paid</span>
                    <?php else: ?>
                        <span class="ml-2 text-red-600 font-semibold">Not Paid</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Order Items Table Section -->
        <div class="bg-white rounded-lg shadow-lg p-6 mb-8">
            <h4 class="text-xl font-semibold text-gray-800 mb-4 flex items-center">
                <i class="bi bi-table text-teal-500 mr-2"></i> Order Items
            </h4>
            <div class="overflow-x-auto">
                <table class="min-w-full bg-white">
                    <thead class="bg-teal-50">
                        <tr>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">#</th>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">Product</th>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">Size</th>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">Price per Unit (KWD)</th>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">Quantity</th>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">Packaging Preferences</th>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">Discount (%)</th>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">Discount Amount (KWD)</th>
                            <th class="py-2 px-4 border-b-2 border-teal-200 text-left text-teal-600 text-sm uppercase font-semibold">Total (KWD)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($order_items)): ?>
                            <?php foreach ($order_items as $index => $item): ?>
                                <tr class="hover:bg-teal-50">
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= $index + 1 ?></td>
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= htmlspecialchars($item['product_name']) ?></td>
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= htmlspecialchars($item['product_size']) ?></td>
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= format_currency($item['product_price']) ?></td>
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= htmlspecialchars($item['quantity']) ?></td>
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= htmlspecialchars($item['packaging_preferences']) ?: 'N/A' ?></td>
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= number_format((float)$item['discount_percentage'], 2) ?>%</td>
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= format_currency($item['discount_amount'] ?? 0.00) ?></td>
                                    <td class="py-2 px-4 border-b text-sm text-gray-700"><?= format_currency($item['total_after_discount'] ?? 0.00) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="9" class="py-4 text-center text-gray-500">No items found in this order.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Order Summary -->
            <div class="mt-6 flex justify-end space-x-8">
                <div class="text-right">
                    <p class="text-gray-700"><strong>Total Before Discounts:</strong> <?= format_currency($totals['total_before_discounts']) ?></p>
                    <p class="text-gray-700"><strong>Total Discounts:</strong> <?= format_currency($totals['total_discounts']) ?></p>
                    <?php if (!$order['free_shipping']): ?>
                        <p class="text-gray-700"><strong>Delivery Fee:</strong> <?= format_currency($order['delivery_fee']) ?></p>
                    <?php endif; ?>
                    <hr class="my-2 border-t border-teal-200">
                    <p class="text-xl text-teal-600"><strong>Final Total:</strong> <?= format_currency($totals['final_total']) ?></p>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="flex flex-col sm:flex-row items-center justify-end space-y-4 sm:space-y-0 sm:space-x-4 mb-8">
            <a href="edit_order.php?id=<?= htmlspecialchars($order['order_id']) ?>" class="flex items-center px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition duration-300">
                <i class="bi bi-pencil-square mr-2"></i> Edit Order
            </a>
            <button onclick="printOrder()" class="flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition duration-300">
                <i class="bi bi-printer-fill mr-2"></i> Print Order
            </button>
            <button onclick="copyOrderDetails()" class="flex items-center px-4 py-2 bg-teal-500 text-white rounded-lg hover:bg-teal-600 transition duration-300">
                <i class="bi bi-clipboard-fill mr-2"></i> Copy Order Details
            </button>
        </div>

        <!-- Footer -->
        <div class="bg-gray-800 text-white text-center p-4 rounded-lg shadow">
            &copy; <?= date("Y") ?> Kaak Alia Bakery. All rights reserved.
        </div>
    </main>

    <!-- Flatpickr JS for Date Picker (if needed in future) -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <!-- Bootstrap JS Bundle (includes Popper) -->
    <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>) and thsi info database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 16, 2024 at 10:08 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 `ads`
--

CREATE TABLE `ads` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `ad_type` enum('Post','Story') NOT NULL,
  `related_id` int(11) NOT NULL,
  `budget` decimal(10,2) NOT NULL,
  `total_spent` decimal(10,2) DEFAULT 0.00,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL,
  `status` enum('Active','Paused','Completed') DEFAULT 'Active',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

--
-- Table structure for table `ad_spend_logs`
--

CREATE TABLE `ad_spend_logs` (
  `id` int(11) NOT NULL,
  `ad_id` int(11) NOT NULL,
  `amount` decimal(10,2) NOT NULL,
  `spend_date` datetime DEFAULT current_timestamp(),
  `description` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

--
-- 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;

--
-- Dumping data for table `customers`
--

INSERT INTO `customers` (`id`, `name`, `contact`, `delivery_address`) VALUES
(1, 'Order_3121', '012345689', 'Qena'),
(2, 'order_3212', '51648963', 'Luxor'),
(3, 'Order_323', '01119235049', 'Qena, Egypt'),
(4, 'Order_3231', '0155648963', 'Luxor'),
(5, 'Order_3548464852', '0110215489', 'Qena'),
(6, 'Order_mahmoud', '50495049', 'Qena'),
(7, 'Ahmed', '01119235049', 'Assuit'),
(8, 'Mahmoud Tawfik', '01119235049', 'Qena, Center Qena'),
(9, 'Ahmed', '0101549463', 'Luxor'),
(10, 'Yossef', '0154949463', 'Aswan'),
(11, 'Mona', '0154984315', 'Qena'),
(12, 'Order_132323', '0119548463', 'CXA'),
(13, 'Mostafa', '154946123', 'Assuit'),
(14, 'Order_66960907', '+96566960907', 'kuwait'),
(15, 'Order_84569845', '+96584569845', 'Kuwait'),
(16, 'Order_84656222', '+96584656222', 'Mashrif'),
(17, 'Order_84549651', '+96584549651', 'Luxor'),
(18, 'Order_94531154', '+96594531154', 'Qena'),
(19, 'Order_56123548', '+96556123548', 'luxor'),
(20, 'Order_84562148', '+96584562148', NULL),
(21, 'Order_54632154', '+96554632154', NULL);

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

--
-- Table structure for table `drivers`
--

CREATE TABLE `drivers` (
  `id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `number` varchar(15) NOT NULL,
  `is_star` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `drivers`
--

INSERT INTO `drivers` (`id`, `name`, `number`, `is_star`) VALUES
(1, 'Fox توصيل', '+965 9944 6116', 0),
(2, 'Perfect M توصيل 3kd', '+965 555 72147', 0),
(3, 'توصيل ٥', '+965 505 02769', 0),
(4, 'Shipping Company توصيل Delivery', '+965 9940 7010', 0),
(5, 'توصيلكم توصيل Delivery', '+965 517 66244', 0),
(6, 'توصيل الكويت ٢', '+965 557 25712', 0),
(7, 'توصيل الكويت 2.5kd', '+965 6049 4960', 0),
(8, 'كلاسك توصيل', '+965 6969 1459', 0),
(9, 'سايق On Call5 Delivery Freelance', '+965 6698 8976', 1),
(10, 'سايق On Call 3 Delivery Freelance', '+965 555 86442', 0),
(11, 'سايق On Call 2 Delivery Freelance', '+965 555 12101', 0),
(12, 'Delivery توصيل', '+965 9851 8182', 0),
(13, 'Kumar Driver', '+965 6673 8688', 1),
(14, 'Pawan Driver', '+965 9733 1565', 0),
(15, 'توصيل - صلاح', '+965 6576 2337', 0);

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

--
-- Table structure for table `notifications`
--

CREATE TABLE `notifications` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `type` enum('order','post','plan','note','ad') NOT NULL,
  `message` varchar(255) NOT NULL,
  `link` varchar(255) NOT NULL,
  `created_at` datetime DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

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

CREATE TABLE `orders` (
  `id` int(11) NOT NULL,
  `customer_id` int(11) NOT NULL,
  `status` enum('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
  `priority` enum('Normal','Important','Quick') DEFAULT 'Normal',
  `order_date` datetime DEFAULT current_timestamp(),
  `delivery_datetime` datetime DEFAULT NULL,
  `delivery_date` date DEFAULT NULL,
  `delivery_fee` decimal(10,2) NOT NULL DEFAULT 0.00,
  `free_shipping` tinyint(1) NOT NULL DEFAULT 0,
  `is_paid` tinyint(1) NOT NULL DEFAULT 0,
  `pickup` tinyint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `orders`
--

INSERT INTO `orders` (`id`, `customer_id`, `status`, `priority`, `order_date`, `delivery_datetime`, `delivery_date`, `delivery_fee`, `free_shipping`, `is_paid`, `pickup`) VALUES
(4, 4, 'Delivered', 'Normal', '2024-11-09 14:48:25', '2024-11-16 08:50:00', NULL, 0.00, 0, 0, 0),
(5, 5, 'Delivered', 'Normal', '2024-11-09 18:28:01', '2024-11-10 09:00:00', NULL, 0.00, 0, 0, 0),
(6, 6, 'Delivered', 'Important', '2024-11-12 09:49:43', '2024-11-13 16:00:00', NULL, 0.00, 0, 0, 0),
(8, 8, 'Delivered', 'Important', '2024-11-12 17:57:16', '2024-11-13 12:00:00', NULL, 0.00, 0, 0, 0),
(9, 9, 'Delivered', 'Important', '2024-11-12 18:16:47', '2024-11-13 15:00:00', NULL, 1.00, 0, 0, 0),
(10, 10, 'Pending', 'Quick', '2024-11-12 18:50:43', '2024-11-13 18:00:00', NULL, 0.00, 0, 0, 0),
(12, 12, 'Pending', 'Quick', '2024-11-13 12:25:55', NULL, NULL, 0.00, 1, 1, 0),
(17, 17, 'Pending', 'Important', '2024-11-14 22:49:41', '2024-11-16 12:00:00', NULL, 1.00, 0, 1, 0),
(18, 18, 'Pending', 'Important', '2024-11-14 23:03:27', '2024-11-16 14:00:00', NULL, 1.00, 0, 1, 0),
(19, 19, 'Delivered', 'Normal', '2024-11-15 12:18:46', '2024-11-16 14:00:00', NULL, 1.00, 0, 1, 0),
(20, 20, 'Pending', 'Important', '2024-11-16 21:28:35', '2024-11-17 11:00:00', NULL, 0.00, 0, 0, 1),
(21, 21, 'Pending', 'Important', '2024-11-16 21:52:46', '2024-11-18 12:00:00', NULL, 0.00, 0, 0, 1);

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

--
-- 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;

--
-- Dumping data for table `order_items`
--

INSERT INTO `order_items` (`id`, `order_id`, `product_id`, `quantity`, `packaging_preferences`, `discount_percentage`, `discount_reason`) VALUES
(5, 4, 8, 1, 'This Order type one Mahmoud Tawfik', 0.00, '<br /><b>Deprecated</b>:  htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in <b>/home/u406552082/domains/longevacare.com/public_html/kaakalia/public/orders/edit_order.php</b> on line <b>692</b><br />'),
(6, 5, 2, 1, '0', 20.00, 'خصم مشرف'),
(7, 4, 6, 2, 'Add Card on it', 30.00, ''),
(8, 6, 6, 1, '0', 0.00, NULL),
(10, 8, 2, 2, 'add Card on box, this card is &quot;Mahmoud Tawfik&quot;', 30.00, 'خصم المشرف'),
(11, 9, 7, 1, 'type on \"Mahmoud\"', 0.00, '<br /><b>Deprecated</b>:  htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in <b>/home/u406552082/domains/longevacare.com/public_html/kaakalia/public/orders/edit_order.php</b> on line <b>749</b><br />'),
(12, 10, 3, 1, 'Type: Mahmoud Tawfik', 0.00, NULL),
(14, 12, 8, 5, '', 0.00, ''),
(19, 12, 8, 1, '0', 0.00, '0'),
(20, 17, 6, 1, '', 30.00, 'خصم مشرف'),
(21, 17, 5, 2, '0', 25.00, '0'),
(22, 18, 7, 1, 'Add Card, Mahmoud', 30.00, 'خصم المشرف'),
(23, 18, 1, 1, 'Add Card, Ahmed', 30.00, 'خصم المشرف'),
(24, 18, 5, 1, 'Add Card, ASC', 30.00, '0'),
(25, 19, 2, 5, 'Add Card :Mahmoud Tawfik:', 30.00, 'خصم مشرف'),
(26, 20, 7, 1, 'Add New Card \"Mahmoud Tawfik\"', 30.00, 'خصم مشرف'),
(27, 21, 9, 1, '', 0.00, '');

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

--
-- 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;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`, `size`, `price`, `category`, `thumbnail`) VALUES
(1, 'Shabora', 'Half Kilo', 6.00, 'Cakes', NULL),
(2, 'Shabora', 'One Kilo', 8.00, 'Cakes', NULL),
(3, 'Shabora', 'Small Basket', 8.00, 'Cakes', NULL),
(4, 'Shabora', 'Large Basket', 10.00, 'Cakes', NULL),
(5, 'Shabora', 'Presentation Plate (Ivory)', 14.00, 'Cakes', NULL),
(6, 'Mahalbiya Crunch', '12 Pieces', 12.00, 'Desserts', NULL),
(7, 'Monkey Bread', 'Large', 12.00, 'Breads', NULL),
(8, 'Monkey Bread Mini', '12 Pieces', 6.00, 'Breads', NULL),
(9, 'Monkey Bread Mini', '9 Pieces', 9.00, 'Breads', NULL),
(11, 'Monkey Bread', 'Presentation Plate', 16.00, 'Breads', NULL);

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

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

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

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

INSERT INTO `users` (`id`, `username`, `email`, `password`, `role`, `profile_image`) VALUES
(1, 'kaakalia', 'user@example.com', '$2y$10$tEdSPRwL8WTXljuAxNh.m.af/8sHd/ouDB21Bgs1bC7GkbRq/h0D6', 'admin', 'uploads/profile_images/profile_kaakalia_1731274341.png'),
(2, 'mahmoudtawfik', 'mahmoudtawfikh@gmail.com', '$2y$10$0yxg1R.kfbVV7GL4G9/Q3u5PK.cvv8p29R3ggkfUMC2.aRiAXb2cO', 'admin', 'uploads/profile_images/profile_mahmoudtawfik_1731274427.jpg'),
(3, 'haya', 'haya@gmail.com', '$2y$10$ri1wzOhcmT2YVGkoPYjwu.3fY8xayakQEWHjTaAFGkPfDwJ50PIh6', 'admin', 'uploads/profile_images/profile_haya_1731304053.jpg');

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

--
-- Table structure for table `workspace_notes`
--

CREATE TABLE `workspace_notes` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `workspace_notes`
--

INSERT INTO `workspace_notes` (`id`, `user_id`, `title`, `content`, `created_at`, `updated_at`) VALUES
(2, 2, 'This important notes', 'HaloHaloHaloHaloHaloHaloHaloHaloHaloHalo', '2024-11-11 09:37:10', '2024-11-11 09:37:10');

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

--
-- Table structure for table `workspace_plans`
--

CREATE TABLE `workspace_plans` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text DEFAULT NULL,
  `audio_path` varchar(255) DEFAULT NULL,
  `due_date` datetime DEFAULT NULL,
  `status` enum('Not Started','In Progress','Completed') DEFAULT 'Not Started',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `priority` enum('Normal','Important','Critical') NOT NULL DEFAULT 'Normal'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

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

--
-- Table structure for table `workspace_posts`
--

CREATE TABLE `workspace_posts` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `platform` enum('Instagram','Facebook','Twitter','Other') NOT NULL,
  `content` text NOT NULL,
  `media_url` varchar(255) DEFAULT NULL,
  `scheduled_datetime` datetime DEFAULT NULL,
  `status` enum('Scheduled','Posted','Failed') DEFAULT 'Scheduled',
  `created_at` datetime DEFAULT current_timestamp(),
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `type` enum('Post','Story') DEFAULT 'Post'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `workspace_posts`
--

INSERT INTO `workspace_posts` (`id`, `user_id`, `platform`, `content`, `media_url`, `scheduled_datetime`, `status`, `created_at`, `updated_at`, `type`) VALUES
(2, 1, 'Instagram', 'Hello', NULL, '2024-11-11 01:19:00', 'Scheduled', '2024-11-10 11:16:10', '2024-11-10 11:16:10', 'Post');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `ads`
--
ALTER TABLE `ads`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `related_id` (`related_id`);

--
-- Indexes for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  ADD PRIMARY KEY (`id`),
  ADD KEY `ad_id` (`ad_id`);

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

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

--
-- Indexes for table `notifications`
--
ALTER TABLE `notifications`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `created_at` (`created_at`);

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

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

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

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

--
-- Indexes for table `workspace_notes`
--
ALTER TABLE `workspace_notes`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- Indexes for table `workspace_plans`
--
ALTER TABLE `workspace_plans`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- Indexes for table `workspace_posts`
--
ALTER TABLE `workspace_posts`
  ADD PRIMARY KEY (`id`),
  ADD KEY `user_id` (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

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

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

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

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

--
-- AUTO_INCREMENT for table `notifications`
--
ALTER TABLE `notifications`
  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=22;

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

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

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

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

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

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

--
-- Constraints for dumped tables
--

--
-- Constraints for table `ads`
--
ALTER TABLE `ads`
  ADD CONSTRAINT `fk_ads_related_id` FOREIGN KEY (`related_id`) REFERENCES `workspace_posts` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `fk_ads_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `ad_spend_logs`
--
ALTER TABLE `ad_spend_logs`
  ADD CONSTRAINT `fk_ad_spend_logs_ad_id` FOREIGN KEY (`ad_id`) REFERENCES `ads` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `notifications`
--
ALTER TABLE `notifications`
  ADD CONSTRAINT `notifications_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

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

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

--
-- Constraints for table `workspace_notes`
--
ALTER TABLE `workspace_notes`
  ADD CONSTRAINT `fk_workspace_notes_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `workspace_plans`
--
ALTER TABLE `workspace_plans`
  ADD CONSTRAINT `fk_workspace_plans_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;

--
-- Constraints for table `workspace_posts`
--
ALTER TABLE `workspace_posts`
  ADD CONSTRAINT `fk_workspace_posts_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`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 */;) so make sure everything is shwoing well and type full codes