based on this view customer (<?php // public/orders/viewordercustomer.php // Enable…
- User
based on this view customer (<?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 handle as per requirement }
// Remove any non-digit characters except the plus sign contact);
// Ensure the number starts with '+' if (strpos(digits, '+') !== 0) { digits = '+' . $digits; }
// Remove '+' for WhatsApp URL 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, 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 (passed by reference).
-
@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(&delivery_fee, pickup) { total_discounts = 0;
foreach (order_items as &item) { item['quantity']) ? (int)product_price = isset(item['product_price'] : 0.00; item['discount_percentage']) ? (float)$item['discount_percentage'] : 0.00;
$item_total = $quantity * $product_price; $discount_amount = ($discount_percentage / 100) * $item_total; // Assign calculated values back to the order item $item['discount_amount'] = $discount_amount; $item['total_after_discount'] = $item_total - $discount_amount; $total_before_discounts += $item_total; $total_discounts += $discount_amount;} unset($item); // Break reference
total_before_discounts - $total_discounts;
// Add delivery fee if not free shipping and not pickup if (!free_shipping && !pickup) { delivery_fee ?? 0.00; delivery_fee; }
return [ 'total_before_discounts' => total_discounts, 'delivery_fee' => (!free_shipping && !pickup) ? final_total ]; }
// Now include the header after handling actions require_once DIR . '/../../includes/header.php';
// Initialize variables for messages error_message = '';
// Check if order_id is provided and valid _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_stmt = order_sql); if (!order_stmt) { die("Prepare failed: (" . conn->errno . ") " . htmlspecialchars(conn->error)); } order_stmt->bind_param("i", order_stmt->execute(); order_stmt->get_result(); 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 _POST['status']) ? sanitize_input(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 _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 item_stmt = order_items_sql); if (!item_stmt) { die("Prepare failed: (" . conn->errno . ") " . htmlspecialchars(conn->error)); } item_stmt->bind_param("i", item_stmt->execute(); item_stmt->get_result(); item = order_items_result->fetch_assoc()) { // Clean up discount_reason if necessary item['discount_reason'] = !empty(item['discount_reason']) : 'N/A'; item; } $item_stmt->close();
// Calculate totals, including delivery fee and free shipping order_items, order['free_shipping'], $order['pickup']);
// Prepare data for JavaScript order['order_id'], 'status' => order['priority'], 'orderDate' => date("l, d M Y, h:i A", strtotime(order['delivery_datetime'] ? get_day_name(order['delivery_datetime'])) : 'N/A', 'customerName' => order['contact'], 'deliveryAddress' => !empty(order['delivery_address'])) : 'N/A', 'deliveryFee' => order['delivery_fee'], 'freeShippingStatus' => order['is_paid'] == 1 ? 'Paid' : 'Not Paid', 'productSummary' => array_map(function(item) { return "• Product: {item['product_name']}\n Size: {item['product_size']}\n Quantity: {item['quantity']}\n Packaging: {item['packaging_preferences']}\n"; }, order_items) ]; ?>
<!-- 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() { const orderData = <?= json_encode($copyData); ?>; let productSummary = ''; orderData.productSummary.forEach(item => { productSummary += item + '\n'; }); // Construct the formatted text const formattedText = `🔴 Order Details 🔴• Order ID: {orderData.status} • Priority: {orderData.orderDate} • Delivery Date & Time: {orderData.customerName}
📦 Product Summary: {orderData.deliveryAddress}
💰 Delivery Fee: KWD {orderData.freeShippingStatus} Shipping) 💵 Payment Status: {orderData.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><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=\"" . htmlspecialchars($status) . "\" {$selected}>" . htmlspecialchars($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']) ?></td> <td class="py-2 px-4 border-b text-sm text-gray-700"><?= format_currency($item['total_after_discount']) ?></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"> © <?= 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>// Enable comprehensive error reporting for debugging purposes ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
// Start output buffering to prevent "headers already sent" errors ob_start();
// Include authentication, database connection, and functions require_once DIR . '/../../includes/auth.php'; require_once DIR . '/../../includes/db_connect.php'; require_once DIR . '/../../includes/functions.php'; // Ensure sanitize_input() is defined
// Verify that sanitize_input() exists if (!function_exists('sanitize_input')) { die("Error: sanitize_input() function is not defined."); }
// Initialize variables success = '';
// Retrieve and sanitize the order ID from GET parameters _GET['id']) ? intval($_GET['id']) : 0;
// Redirect if no valid order ID is provided if ($order_id <= 0) { header("Location: view_orders.php?error=Invalid%20Order%20ID"); exit(); }
// Fetch order details along with customer information $order_sql = "SELECT o.*, c.name AS customer_name, c.contact AS customer_contact, c.delivery_address FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.id = ? LIMIT 1";
conn->prepare(order_stmt) { die("An unexpected error occurred. Please try again later."); } order_id); order_result = $order_stmt->get_result();
if ($order_result->num_rows != 1) { header("Location: view_orders.php?error=Order%20Not%20Found"); exit(); }
order_result->fetch_assoc(); $order_stmt->close();
// Fetch existing order items order_items_stmt = order_items_sql); if (!order_items_stmt->bind_param("i", order_items_stmt->execute(); order_items_stmt->get_result(); item = order_items_result->fetch_assoc()) { order_items[] = item; } order_items_stmt->close();
// Define an array of countries with their dialing codes $countries = [ "Afghanistan" => "+93", "Albania" => "+355", "Algeria" => "+213", "Andorra" => "+376", "Angola" => "+244", "Antigua and Barbuda" => "+1-268", "Argentina" => "+54", "Armenia" => "+374", "Australia" => "+61", "Austria" => "+43", "Azerbaijan" => "+994", "Bahamas" => "+1-242", "Bahrain" => "+973", "Bangladesh" => "+880", "Barbados" => "+1-246", "Belarus" => "+375", "Belgium" => "+32", "Belize" => "+501", "Benin" => "+229", "Bhutan" => "+975", "Bolivia" => "+591", "Bosnia and Herzegovina" => "+387", "Botswana" => "+267", "Brazil" => "+55", "Brunei" => "+673", "Bulgaria" => "+359", "Burkina Faso" => "+226", "Burundi" => "+257", "Kuwait" => "+965", // Add more countries as needed ];
// Function to extract country code from contact number function extract_country_code(countries) { foreach (country => code) { if (strpos(contact, code) === 0) { return [country, $code]; } } // Default to Kuwait if no match found return ["Kuwait", "+965"]; }
// Extract country and contact number list(current_country_code) = extract_country_code(countries); order['customer_contact'], strlen($current_country_code));
// Fetch products for selection products_result = products_sql); if (!products_result) { die("Error fetching products: " . conn->error); } products_result->fetch_all(MYSQLI_ASSOC);
// Initialize form variables order['customer_name']; current_country_code; order['delivery_address']; order['status']; order['priority']; order['free_shipping']; order['is_paid']; order['pickup']; order['delivery_datetime'];
// Handle form submission for updating the order if (_SERVER['REQUEST_METHOD'] === 'POST') { // Retrieve and sanitize form inputs customer_name = sanitize_input(contact_input = sanitize_input(selected_country = sanitize_input(delivery_address = sanitize_input(status = sanitize_input(priority = sanitize_input(free_shipping = isset(is_paid = isset(pickup = isset($_POST['pickup']) ? 1 : 0;
// Handle delivery_datetime conversion from 'Y-m-d\TH:i' to 'Y-m-d H:i:s' $delivery_datetime_input = $_POST['delivery_datetime'] ?? ''; if (!empty($delivery_datetime_input)) { $parsed_datetime = strtotime($delivery_datetime_input); if ($parsed_datetime !== false) { $delivery_datetime = date('Y-m-d H:i:s', $parsed_datetime); } else { $delivery_datetime = null; } } else { $delivery_datetime = null; } // Determine delivery_fee based on free_shipping and pickup if (!$free_shipping && !$pickup) { $delivery_fee = isset($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00; } else { $delivery_fee = 0.00; } // Handle existing order items $existing_item_ids = $_POST['existing_item_id'] ?? []; $existing_product_ids = $_POST['existing_product_id'] ?? []; $existing_quantities = $_POST['existing_quantity'] ?? []; $existing_packaging_preferences = $_POST['existing_packaging_preferences'] ?? []; $existing_apply_discount = $_POST['existing_apply_discount'] ?? []; $existing_discount_percentages = $_POST['existing_discount_percentage'] ?? []; $existing_discount_reasons = $_POST['existing_discount_reason'] ?? []; // Handle new order items $new_product_ids = $_POST['new_product_id'] ?? []; $new_quantities = $_POST['new_quantity'] ?? []; $new_packaging_preferences = $_POST['new_packaging_preferences'] ?? []; $new_apply_discount = $_POST['new_apply_discount'] ?? []; $new_discount_percentages = $_POST['new_discount_percentage'] ?? []; $new_discount_reasons = $_POST['new_discount_reason'] ?? []; // Handle deleted existing order items $deleted_existing_item_ids = $_POST['deleted_existing_item_ids'] ?? []; $active_existing_item_ids = array_diff($existing_item_ids, $deleted_existing_item_ids); // Initialize Error Array $errors = []; // Validate essential fields if (empty($customer_name)) { $errors[] = "Customer name is required."; } if (empty($contact_input)) { $errors[] = "Contact number is required."; } if (empty($status)) { $errors[] = "Order status is required."; } if (empty($priority)) { $errors[] = "Order priority is required."; } if (empty($active_existing_item_ids) && empty($new_product_ids)) { $errors[] = "At least one product must be selected."; } // Validate contact number $contact_digits = preg_replace('/\D/', '', $contact_input); if (empty($contact_digits)) { $errors[] = "A valid contact number is required."; } else { // Full contact number with country code $full_contact = $selected_country . $contact_digits; } // Validate delivery fee only if not free_shipping or pickup if (!$free_shipping && !$pickup && ($delivery_fee < 0)) { $errors[] = "Delivery fee cannot be negative."; } // Validate existing order items foreach ($active_existing_item_ids as $index => $item_id) { $item_index = array_search($item_id, $existing_item_ids); $product_id = intval($existing_product_ids[$item_index] ?? 0); $quantity = intval($existing_quantities[$item_index] ?? 0); if ($product_id <= 0) { $errors[] = "Product selection is required for all existing items."; break; } if ($quantity <= 0) { $errors[] = "Quantity must be at least 1 for all existing items."; break; } // Handle discounts for existing items if (isset($existing_apply_discount[$item_index])) { $discount_percentage = floatval(trim($existing_discount_percentages[$item_index] ?? 0)); $discount_reason = sanitize_input($existing_discount_reasons[$item_index] ?? ''); if ($discount_percentage <= 0 && !empty($existing_discount_percentages[$item_index])) { $errors[] = "Discount percentage must be greater than 0 if discount is applied for existing items."; break; } if ($discount_percentage < 0 || $discount_percentage > 100) { $errors[] = "Invalid discount percentage for existing items. It should be between 0 and 100."; break; } if (empty($discount_reason) && $discount_percentage > 0) { $errors[] = "Discount reason is required if discount is applied for existing items."; break; } } } // Validate new order items foreach ($new_product_ids as $index => $product_id) { $product_id = intval($product_id); $quantity = intval($new_quantities[$index] ?? 0); if ($product_id <= 0) { $errors[] = "Product selection is required for all new items."; break; } if ($quantity <= 0) { $errors[] = "Quantity must be at least 1 for all new items."; break; } // Handle discounts for new items if (isset($new_apply_discount[$index])) { $discount_percentage = floatval(trim($new_discount_percentages[$index] ?? 0)); $discount_reason = sanitize_input($new_discount_reasons[$index] ?? ''); if ($discount_percentage <= 0 && !empty($new_discount_percentages[$index])) { $errors[] = "Discount percentage must be greater than 0 if discount is applied for new items."; break; } if ($discount_percentage < 0 || $discount_percentage > 100) { $errors[] = "Invalid discount percentage for new items. It should be between 0 and 100."; break; } if (empty($discount_reason) && $discount_percentage > 0) { $errors[] = "Discount reason is required if discount is applied for new items."; break; } } } // If no errors, proceed to update the order if (empty($errors)) { // Start Transaction $conn->begin_transaction(); try { // Step 1: Update Customer Details // If pickup is selected, clear the delivery_address if ($pickup) { $delivery_address = ''; } $stmt = $conn->prepare("UPDATE customers SET name = ?, contact = ?, delivery_address = ? WHERE id = ?"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } $stmt->bind_param("sssi", $customer_name, $full_contact, $delivery_address, $order['customer_id']); if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); // Step 2: Update Order Table $stmt = $conn->prepare("UPDATE orders SET status = ?, priority = ?, delivery_fee = ?, free_shipping = ?, is_paid = ?, pickup = ?, delivery_datetime = ? WHERE id = ?"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } // Binding parameters. If $delivery_datetime is null, set to NULL in query if ($delivery_datetime !== null) { $stmt->bind_param("ssdiiiis", $status, $priority, $delivery_fee, $free_shipping, $is_paid, $pickup, $delivery_datetime, $order_id); } else { // Use null for delivery_datetime $stmt->bind_param("ssdiiiis", $status, $priority, $delivery_fee, $free_shipping, $is_paid, $pickup, $delivery_datetime, $order_id); } if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); // Step 3: Remove Deleted Existing Order Items if (!empty($deleted_existing_item_ids)) { // Prepare placeholders $placeholders = implode(',', array_fill(0, count($deleted_existing_item_ids), '?')); $types = str_repeat('i', count($deleted_existing_item_ids)); $stmt = $conn->prepare("DELETE FROM order_items WHERE id IN ($placeholders)"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } // Dynamically bind parameters $stmt->bind_param($types, ...array_map('intval', $deleted_existing_item_ids)); if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); } // Step 4: Update Existing Order Items foreach ($active_existing_item_ids as $index => $item_id) { $item_index = array_search($item_id, $existing_item_ids); $product_id = intval($existing_product_ids[$item_index]); $quantity = intval($existing_quantities[$item_index]); $packaging_preferences = sanitize_input($existing_packaging_preferences[$item_index] ?? ''); // Handle discounts $discount_percentage = 0.00; $discount_reason = ''; if (isset($existing_apply_discount[$item_index])) { $discount_percentage = floatval(trim($existing_discount_percentages[$item_index])); $discount_reason = sanitize_input($existing_discount_reasons[$item_index]); // If discount_percentage is 0, set discount_reason to empty if ($discount_percentage <= 0) { $discount_reason = ''; } } $stmt = $conn->prepare("UPDATE order_items SET product_id = ?, quantity = ?, packaging_preferences = ?, discount_percentage = ?, discount_reason = ? WHERE id = ?"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } $stmt->bind_param("iidssi", $product_id, $quantity, $packaging_preferences, $discount_percentage, $discount_reason, $item_id); if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); } // Step 5: Add New Order Items foreach ($new_product_ids as $index => $product_id) { $product_id = intval($product_id); $quantity = intval($new_quantities[$index]); $packaging_preferences = sanitize_input($new_packaging_preferences[$index] ?? ''); // Handle discounts $discount_percentage = 0.00; $discount_reason = ''; if (isset($new_apply_discount[$index])) { $discount_percentage = floatval(trim($new_discount_percentages[$index])); $discount_reason = sanitize_input($new_discount_reasons[$index]); // If discount_percentage is 0, set discount_reason to empty if ($discount_percentage <= 0) { $discount_reason = ''; } } $stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, packaging_preferences, discount_percentage, discount_reason) VALUES (?, ?, ?, ?, ?, ?)"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } $stmt->bind_param("iiidsi", $order_id, $product_id, $quantity, $packaging_preferences, $discount_percentage, $discount_reason); if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); } // Commit Transaction $conn->commit(); // Redirect to view_orders.php with success message header("Location: view_orders.php?success=Order+updated+successfully"); exit(); } catch (Exception $e) { // Rollback Transaction $conn->rollback(); $error = "Error updating order: " . sanitize_input($e->getMessage()); } } else { // If not a POST request, pre-fill the form with existing data // Ensure that $customer_name, $selected_country, etc., are already set above }} ?>
<!-- Tailwind CSS CDN --> <script src="https://cdn.tailwindcss.com"></script> <!-- Bootstrap Icons --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"> <!-- Flatpickr CSS for Date Picker --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> <!-- Custom Styles --> <style> /* Custom scrollbar for better UX */ ::-webkit-scrollbar { width: 8px; } ::-webkit-scrollbar-track { background: #f1f5f9; /* Tailwind's gray-100 */ } ::-webkit-scrollbar-thumb { background: #20B2AA; /* Teal-500 */ border-radius: 4px; } ::-webkit-scrollbar-thumb:hover { background: #0d9488; /* Teal-600 */ } /* Tooltip styles */ .tooltip { position: relative; display: inline-block; cursor: pointer; } .tooltip .tooltiptext { visibility: hidden; width: 250px; background-color: #6B7280; /* Tailwind's gray-500 */ color: #fff; text-align: left; border-radius: 4px; padding: 8px; position: absolute; z-index: 10; bottom: 125%; /* Position above the icon */ left: 50%; margin-left: -125px; opacity: 0; transition: opacity 0.3s; } .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } </style> <!-- Additional JavaScript for dynamic product addition, discount handling, delivery fee toggle, and pickup handling --> <script> let productCount = <?= count($order_items) > 0 ? count($order_items) : 1; ?>; function addProductRow() { const productContainer = document.getElementById('new-products-container'); const productRow = document.createElement('div'); productRow.className = 'product-row bg-gray-50 p-4 rounded-lg shadow-md mb-4'; productRow.innerHTML = ` <div class="grid grid-cols-1 md:grid-cols-4 gap-4"> <div> <label class="block text-sm font-medium text-gray-700" for="new_product_id_${productCount}"> Product <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Select the product from the dropdown menu. This list includes available items that can be added to the customer's order. </span> </span> </label> <select name="new_product_id[]" id="new_product_id_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required> <option value="">Select Product</option> <?php foreach($products as $product_option): ?> <option value="<?= htmlspecialchars($product_option['id'], ENT_QUOTES, 'UTF-8') ?>"> <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)", ENT_QUOTES, 'UTF-8') ?> </option> <?php endforeach; ?> </select> </div> <div> <label class="block text-sm font-medium text-gray-700" for="new_quantity_${productCount}"> Quantity <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter the number of units required for each selected product. Quantities must be in whole numbers and are defaulted to one (1) if not specified. </span> </span> </label> <input type="number" name="new_quantity[]" id="new_quantity_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="1" required> </div> <div> <label class="block text-sm font-medium text-gray-700" for="new_packaging_preferences_${productCount}"> Packaging Preferences <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Specify any particular packaging requests, such as 'Gift Wrap' or 'Fragile - Handle with Care,' to ensure customer satisfaction and safe delivery. </span> </span> </label> <input type="text" name="new_packaging_preferences[]" id="new_packaging_preferences_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap"> </div> <div> <label class="block text-sm font-medium text-gray-700" for="new_discount_${productCount}"> Apply Discount <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Check this box if the customer is eligible for a discount. Discounts will be applied to the total product cost at checkout. </span> </span> </label> <div class="flex items-center mt-1"> <input type="checkbox" name="new_apply_discount[]" id="new_discount_checkbox_${productCount}" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleNewDiscountFields(this, ${productCount})"> <label for="new_discount_checkbox_${productCount}" class="ml-2 block text-sm text-gray-700"> Yes </label> </div> <div id="new_discount_fields_${productCount}" class="discount-fields mt-2" style="display: none;"> <label class="block text-sm font-medium text-gray-700" for="new_discount_percentage_${productCount}"> Discount Percentage (%) <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter the discount percentage to be applied to this product. It should be between 0 and 100. </span> </span> </label> <input type="number" name="new_discount_percentage[]" id="new_discount_percentage_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage" required> <label class="block text-sm font-medium text-gray-700 mt-2" for="new_discount_reason_${productCount}"> Discount Reason <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Provide a reason for the discount applied to this product. </span> </span> </label> <input type="text" name="new_discount_reason[]" id="new_discount_reason_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" required> </div> </div> </div> <div class="flex justify-end mt-2"> <button type="button" class="remove-product-button bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition duration-300 flex items-center gap-2" onclick="removeProductRow(this)"> <i class="bi bi-trash-fill"></i> Remove Product </button> </div> `; productContainer.appendChild(productRow); productCount++; } function removeProductRow(button) { const productRow = button.closest('.product-row'); productRow.remove(); } // Toggle discount fields based on checkbox for existing items function toggleDiscountFields(checkbox, count) { const discountFields = document.getElementById(`discount_fields_${count}`); if (checkbox.checked) { discountFields.style.display = 'block'; } else { discountFields.style.display = 'none'; // Clear discount inputs discountFields.querySelectorAll('input').forEach(input => input.value = ''); } } // Toggle discount fields based on checkbox for new items function toggleNewDiscountFields(checkbox, count) { const discountFields = document.getElementById(`new_discount_fields_${count}`); if (checkbox.checked) { discountFields.style.display = 'block'; } else { discountFields.style.display = 'none'; // Clear discount inputs discountFields.querySelectorAll('input').forEach(input => input.value = ''); } } // Toggle delivery fee field based on free shipping and pickup checkboxes function toggleDeliveryFee() { const freeShippingCheckbox = document.getElementById('free_shipping'); const pickupCheckbox = document.getElementById('pickup'); const deliveryFeeField = document.getElementById('delivery_fee_field'); const deliveryFeeInput = document.getElementById('delivery_fee'); if (freeShippingCheckbox.checked || pickupCheckbox.checked) { deliveryFeeField.style.display = 'none'; deliveryFeeInput.value = '0.00'; deliveryFeeInput.disabled = true; } else { deliveryFeeField.style.display = 'block'; deliveryFeeInput.disabled = false; } } // Toggle specific delivery details based on pickup checkbox function togglePickup() { const pickupCheckbox = document.getElementById('pickup'); const freeShippingCheckbox = document.getElementById('free_shipping'); const deliveryFeeInput = document.getElementById('delivery_fee'); const deliveryFeeField = document.getElementById('delivery_fee_field'); const deliveryAddressField = document.getElementById('delivery_address_field'); if (pickupCheckbox.checked) { // Hide Delivery Address deliveryAddressField.style.display = 'none'; // Uncheck and hide Free Shipping if it's checked if (freeShippingCheckbox.checked) { freeShippingCheckbox.checked = false; toggleDeliveryFee(); } // Hide Delivery Fee deliveryFeeField.style.display = 'none'; deliveryFeeInput.value = '0.00'; deliveryFeeInput.disabled = true; } else { // Show Delivery Address deliveryAddressField.style.display = 'block'; // Show Delivery Fee based on Free Shipping status toggleDeliveryFee(); } } // Auto-generate Customer Name based on Contact Number function autoGenerateCustomerName() { const contactInput = document.getElementById('contact'); const customerNameInput = document.getElementById('customer_name'); // Extract digits from contact number const digits = contactInput.value.replace(/\D/g, ''); if (digits.length > 0) { customerNameInput.value = 'Order_' + digits; } else { customerNameInput.value = ''; } } // Initialize on DOM content loaded document.addEventListener('DOMContentLoaded', function() { // Initialize delivery fee toggle toggleDeliveryFee(); const freeShippingEl = document.getElementById('free_shipping'); if (freeShippingEl) { freeShippingEl.addEventListener('change', toggleDeliveryFee); } // Initialize pickup toggle togglePickup(); const pickupEl = document.getElementById('pickup'); if (pickupEl) { pickupEl.addEventListener('change', togglePickup); } // Initialize Customer Name auto-generation const contactEl = document.getElementById('contact'); if (contactEl) { contactEl.addEventListener('input', autoGenerateCustomerName); } // Initialize tooltip functionality var tooltipTriggerList = [].slice.call(document.querySelectorAll('.tooltip')) tooltipTriggerList.forEach(function (tooltipTriggerEl) { var tooltipText = tooltipTriggerEl.querySelector('.tooltiptext'); tooltipTriggerEl.addEventListener('mouseenter', function() { tooltipText.style.visibility = 'visible'; tooltipText.style.opacity = '1'; }); tooltipTriggerEl.addEventListener('mouseleave', function() { tooltipText.style.visibility = 'hidden'; tooltipText.style.opacity = '0'; }); }); }); </script><!-- Include header.php inside the body --> <?php require_once '../../includes/header.php'; ?> <!-- Main Container --> <main class="container mx-auto p-6"> <!-- Page Header --> <div class="mb-8"> <h1 class="text-3xl font-bold text-blue-600 flex items-center"> <i class="bi bi-pencil-square mr-2"></i> Edit Order #<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?> </h1> </div> <!-- Welcome Section --> <div class="bg-white rounded-lg shadow-lg p-6 mb-8"> <p class="text-gray-700">Update the details of the order below. Ensure all changes are accurate before submission.</p> </div> <!-- Form Container --> <div class="bg-white rounded-lg shadow-lg p-6"> <?php if (!empty($error)): ?> <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 flex items-center"> <i class="bi bi-exclamation-triangle-fill mr-2"></i> <span><?= $error ?></span> </div> <?php endif; ?> <?php if (!empty($success)): ?> <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4 flex items-center"> <i class="bi bi-check-circle-fill mr-2"></i> <span><?= $success ?></span> </div> <?php endif; ?> <form method="POST" action="edit_order.php?id=<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?>"> <!-- Customer Details --> <div class="mb-6"> <h2 class="text-xl font-semibold text-gray-800 mb-4">Customer Details</h2> <div class="flex flex-col md:flex-row md:space-x-6"> <div class="flex-1 mb-4 md:mb-0"> <label class="block text-sm font-medium text-gray-700 mb-1" for="customer_name"> Customer Name <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Automatically generated based on contact number. If unavailable, enter the customer's full name for record purposes. </span> </span> </label> <input type="text" id="customer_name" name="customer_name" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" value="<?= htmlspecialchars($customer_name ?? $order['customer_name'], ENT_QUOTES, 'UTF-8') ?>" placeholder="Enter customer name" required> </div> <div class="flex-1 mb-4 md:mb-0"> <label class="block text-sm font-medium text-gray-700 mb-1" for="country"> Country <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Select the customer’s country to ensure accurate address formatting and delivery options. Default is set based on existing contact. </span> </span> </label> <select name="country" id="country" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required> <?php foreach($countries as $country => $code): ?> <option value="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>" <?= ($selected_country === $code) ? 'selected' : '' ?>> <?= htmlspecialchars($country . " (" . $code . ")", ENT_QUOTES, 'UTF-8') ?> </option> <?php endforeach; ?> </select> </div> </div> <div class="flex flex-col md:flex-row md:space-x-6 mt-4"> <div class="flex-1 mb-4 md:mb-0" id="contact_field"> <label class="block text-sm font-medium text-gray-700 mb-1" for="contact"> Contact Number <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter a valid contact number without the country code. The country code is auto-prepended based on selected country. </span> </span> </label> <input type="text" id="contact" name="contact" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" value="<?= htmlspecialchars($contact_number, ENT_QUOTES, 'UTF-8') ?>" required placeholder="Enter contact number without country code"> </div> <div class="flex-1" id="delivery_address_field"> <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_address"> Delivery Address <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Provide the full delivery address, including building name, street, area, and any special instructions to facilitate easy and efficient delivery. </span> </span> </label> <textarea id="delivery_address" name="delivery_address" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" rows="3" placeholder="Enter delivery address"><?= htmlspecialchars($delivery_address ?? '', ENT_QUOTES, 'UTF-8') ?></textarea> </div> </div> </div> <hr class="my-6"> <!-- Order Details --> <div class="mb-6"> <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Details</h2> <!-- Priority Selection --> <div class="mb-4"> <label class="block text-sm font-medium text-gray-700 mb-1"> Order Priority <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Choose a priority level for this order based on urgency: Normal for standard processing, Important for prioritized handling, and Quick for immediate attention. </span> </span> </label> <div class="flex space-x-4"> <?php $priorities = ['Normal', 'Important', 'Quick']; foreach ($priorities as $priority_option): $checked = ($priority === $priority_option) ? 'checked' : ''; ?> <label class="inline-flex items-center"> <input type="radio" name="priority" value="<?= htmlspecialchars($priority_option, ENT_QUOTES, 'UTF-8') ?>" class="form-radio text-teal-600" <?= $checked ?> required> <span class="ml-2"><?= htmlspecialchars($priority_option, ENT_QUOTES, 'UTF-8') ?></span> </label> <?php endforeach; ?> </div> </div> <!-- Status Selection --> <div class="mb-4"> <label class="block text-sm font-medium text-gray-700 mb-1"> Order Status <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Update the current status of the order: Pending, In Progress, Completed, or Delivered. </span> </span> </label> <select name="status" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required> <option value="Pending" <?= ($status == 'Pending') ? 'selected' : '' ?>>Pending</option> <option value="In Progress" <?= ($status == 'In Progress') ? 'selected' : '' ?>>In Progress</option> <option value="Completed" <?= ($status == 'Completed') ? 'selected' : '' ?>>Completed</option> <option value="Delivered" <?= ($status == 'Delivered') ? 'selected' : '' ?>>Delivered</option> </select> </div> <!-- Delivery Fee and Free Shipping --> <div class="mb-4" id="delivery_fee_field"> <label class="block text-sm font-medium text-gray-700 mb-1"> Delivery Fee (KWD) <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter any applicable delivery fee in Kuwaiti Dinar (KWD). This field will automatically set to 0 if ‘Free Shipping’ is selected or if pickup is chosen. </span> </span> </label> <input type="number" step="0.01" min="0" name="delivery_fee" id="delivery_fee" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" value="<?= htmlspecialchars($delivery_fee, ENT_QUOTES, 'UTF-8') ?>" <?= ($free_shipping || $pickup) ? 'disabled' : '' ?> required> </div> <div class="flex items-center mb-4"> <input type="checkbox" id="free_shipping" name="free_shipping" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= $free_shipping ? 'checked' : '' ?> onchange="toggleDeliveryFee()"> <label for="free_shipping" class="ml-2 block text-sm text-gray-700"> Free Shipping <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Select this option if the customer qualifies for free shipping based on promotional offers or order amount. Delivery fees will automatically update. </span> </span> </label> </div> <!-- Pickup Checkbox --> <div class="flex items-center mb-4"> <input type="checkbox" id="pickup" name="pickup" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= $pickup ? 'checked' : '' ?> onchange="togglePickup()"> <label for="pickup" class="ml-2 block text-sm text-gray-700"> Customer Pickup <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Select this option if the customer will pick up the order directly from our kitchen, eliminating the need for delivery. </span> </span> </label> </div> <!-- Delivery Date and Time --> <div class="mb-4"> <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_datetime"> Delivery Date and Time <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Choose a specific date and time for the order delivery or pickup. Ensure the date aligns with the customer’s availability and our schedule to avoid delays. </span> </span> </label> <input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" value="<?= htmlspecialchars($delivery_datetime ? date('Y-m-d\TH:i', strtotime($delivery_datetime)) : '', ENT_QUOTES, 'UTF-8') ?>" required> </div> </div> <hr class="my-6"> <!-- Order Items --> <div class="mb-6"> <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Items</h2> <!-- Existing Order Items --> <div class="mb-4"> <h3 class="text-lg font-semibold mb-2">Existing Items</h3> <?php if (empty($order_items)): ?> <p>No existing items for this order.</p> <?php else: ?> <?php foreach ($order_items as $index => $item): ?> <div class="border border-gray-300 rounded-lg p-4 mb-4"> <input type="hidden" name="existing_item_id[]" value="<?= htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') ?>"> <div class="grid grid-cols-1 md:grid-cols-5 gap-4"> <div> <label class="block text-sm font-medium text-gray-700" for="existing_product_id_<?= $index ?>"> Product <span class="text-red-500">*</span> </label> <select name="existing_product_id[]" id="existing_product_id_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required> <option value="">Select Product</option> <?php foreach($products as $product_option): ?> <option value="<?= htmlspecialchars($product_option['id'], ENT_QUOTES, 'UTF-8') ?>" <?= ($product_option['id'] == $item['product_id']) ? 'selected' : '' ?>> <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)", ENT_QUOTES, 'UTF-8') ?> </option> <?php endforeach; ?> </select> </div> <div> <label class="block text-sm font-medium text-gray-700" for="existing_quantity_<?= $index ?>"> Quantity <span class="text-red-500">*</span> </label> <input type="number" name="existing_quantity[]" id="existing_quantity_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="<?= htmlspecialchars($item['quantity'], ENT_QUOTES, 'UTF-8') ?>" required> </div> <div> <label class="block text-sm font-medium text-gray-700" for="existing_packaging_preferences_<?= $index ?>"> Packaging Preferences </label> <input type="text" name="existing_packaging_preferences[]" id="existing_packaging_preferences_<?= $index ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($item['packaging_preferences'], ENT_QUOTES, 'UTF-8') ?>"> </div> <div> <label class="block text-sm font-medium text-gray-700" for="existing_discount_<?= $index ?>"> Apply Discount </label> <div class="flex items-center mt-1"> <input type="checkbox" name="existing_apply_discount[]" id="existing_discount_checkbox_<?= $index ?>" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, <?= $index ?>)" <?= ($item['discount_percentage'] > 0) ? 'checked' : '' ?>> <label for="existing_discount_checkbox_<?= $index ?>" class="ml-2 block text-sm text-gray-700"> Yes </label> </div> <div id="discount_fields_<?= $index ?>" class="discount-fields mt-2" style="display: <?= ($item['discount_percentage'] > 0) ? 'block' : 'none' ?>;"> <label class="block text-sm font-medium text-gray-700" for="existing_discount_percentage_<?= $index ?>"> Discount Percentage (%) <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter the discount percentage to be applied to this product. It should be between 0 and 100. </span> </span> </label> <input type="number" name="existing_discount_percentage[]" id="existing_discount_percentage_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" value="<?= htmlspecialchars($item['discount_percentage'], ENT_QUOTES, 'UTF-8') ?>" required> <label class="block text-sm font-medium text-gray-700 mt-2" for="existing_discount_reason_<?= $index ?>"> Discount Reason <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Provide a reason for the discount applied to this product. </span> </span> </label> <input type="text" name="existing_discount_reason[]" id="existing_discount_reason_<?= $index ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" value="<?= htmlspecialchars($item['discount_reason'], ENT_QUOTES, 'UTF-8') ?>" required> </div> </div> <div class="flex items-center"> <label class="flex items-center"> <input type="checkbox" name="deleted_existing_item_ids[]" value="<?= htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') ?>" class="h-4 w-4 text-red-600 border-gray-300 rounded"> <span class="ml-2 text-sm text-gray-700">Delete</span> </label> </div> </div> </div> <?php endforeach; ?> <?php endif; ?> </div> <!-- New Order Items --> <div class="mb-4"> <h3 class="text-lg font-semibold mb-2">Add New Items</h3> <div id="new-products-container"> <!-- New Product Rows will be added here --> </div> <button type="button" class="bg-teal-500 text-white px-4 py-2 rounded-lg hover:bg-teal-600 transition duration-300 flex items-center gap-2 mt-4" onclick="addProductRow()"> <i class="bi bi-plus-circle-fill"></i> Add Another Product </button> </div> </div> <hr class="my-6"> <!-- Submit Button --> <div class="mb-6"> <button type="submit" class="w-full bg-green-500 text-white px-4 py-3 rounded-lg hover:bg-green-600 transition duration-300 flex justify-center items-center gap-2"> <i class="bi bi-save"></i> Update Order </button> </div> </form> </div> <!-- Footer --> <div class="mt-12 text-center text-gray-600"> © <?= date("Y") ?> Kaak Alia Bakery. All rights reserved. </div> </main> <!-- Bootstrap JS Bundle (optional if using Bootstrap components) --> <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Flatpickr JS for Date Picker --> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> <!-- Flatpickr Initialization --> <script> flatpickr("#delivery_datetime", { enableTime: true, dateFormat: "Y-m-d\\TH:i", minDate: "today" }); </script> -
- Assistant
It appears that there's an inconsistency in how the
order_idis being handled between different scripts in your system. Specifically:- In
view_order_customer.php, theorder_idis retrieved using$_GET['order_id']. - In
edit_order.php, theorder_idis retrieved using$_GET['id'].
This inconsistency can lead to confusion and potential bugs, especially when integrating different parts of your system. To ensure consistency and improve the security and maintainability of your code, it's essential to standardize the parameter names and thoroughly validate the
order_idacross all scripts.Below is a complete and revised version of
edit_order.phpwith the following improvements:- Consistent Parameter Naming: Uses
order_idconsistently across the script. - Enhanced Security: Implements better sanitization and validation of inputs to prevent SQL injection and other security vulnerabilities.
- Error Handling: Provides comprehensive error messages and handles potential database errors gracefully.
- Code Organization: Organizes the code for better readability and maintainability.
<?php // public/orders/edit_order.php // Enable comprehensive error reporting for debugging purposes ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); // Start output buffering to prevent "headers already sent" errors ob_start(); // Include authentication, database connection, and necessary functions require_once __DIR__ . '/../../includes/auth.php'; require_once __DIR__ . '/../../includes/db_connect.php'; require_once __DIR__ . '/../../includes/functions.php'; // Ensure sanitize_input() is defined // Verify that sanitize_input() exists if (!function_exists('sanitize_input')) { die("Error: sanitize_input() function is not defined."); } // Initialize variables for messages $error = ''; $success = ''; // Retrieve and sanitize the order ID from GET parameters $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0; // Redirect if no valid order ID is provided if ($order_id <= 0) { header("Location: view_orders.php?error=Invalid%20Order%20ID"); exit(); } // Fetch order details along with customer information $order_sql = "SELECT o.*, c.name AS customer_name, c.contact AS customer_contact, c.delivery_address FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.id = ? LIMIT 1"; $order_stmt = $conn->prepare($order_sql); if (!$order_stmt) { die("An unexpected error occurred. Please try again later."); } $order_stmt->bind_param("i", $order_id); $order_stmt->execute(); $order_result = $order_stmt->get_result(); if ($order_result->num_rows != 1) { header("Location: view_orders.php?error=Order%20Not%20Found"); exit(); } $order = $order_result->fetch_assoc(); $order_stmt->close(); // Fetch existing order items $order_items_sql = "SELECT oi.*, p.name AS product_name, p.size, p.price FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = ?"; $order_items_stmt = $conn->prepare($order_items_sql); if (!$order_items_stmt) { die("An unexpected error occurred. Please try again later."); } $order_items_stmt->bind_param("i", $order_id); $order_items_stmt->execute(); $order_items_result = $order_items_stmt->get_result(); $order_items = []; while ($item = $order_items_result->fetch_assoc()) { $order_items[] = $item; } $order_items_stmt->close(); // Define an array of countries with their dialing codes $countries = [ "Afghanistan" => "+93", "Albania" => "+355", "Algeria" => "+213", "Andorra" => "+376", "Angola" => "+244", "Antigua and Barbuda" => "+1-268", "Argentina" => "+54", "Armenia" => "+374", "Australia" => "+61", "Austria" => "+43", "Azerbaijan" => "+994", "Bahamas" => "+1-242", "Bahrain" => "+973", "Bangladesh" => "+880", "Barbados" => "+1-246", "Belarus" => "+375", "Belgium" => "+32", "Belize" => "+501", "Benin" => "+229", "Bhutan" => "+975", "Bolivia" => "+591", "Bosnia and Herzegovina" => "+387", "Botswana" => "+267", "Brazil" => "+55", "Brunei" => "+673", "Bulgaria" => "+359", "Burkina Faso" => "+226", "Burundi" => "+257", "Kuwait" => "+965", // Add more countries as needed ]; // Function to extract country code from contact number function extract_country_code($contact, $countries) { foreach ($countries as $country => $code) { if (strpos($contact, $code) === 0) { return [$country, $code]; } } // Default to Kuwait if no match found return ["Kuwait", "+965"]; } // Extract country and contact number list($current_country, $current_country_code) = extract_country_code($order['customer_contact'] ?? '', $countries); $contact_number = substr($order['customer_contact'], strlen($current_country_code)); // Fetch products for selection $products_sql = "SELECT * FROM products ORDER BY name ASC"; $products_result = $conn->query($products_sql); if (!$products_result) { die("Error fetching products: " . $conn->error); } $products = $products_result->fetch_all(MYSQLI_ASSOC); // Initialize form variables $customer_name = $order['customer_name']; $selected_country = $current_country_code; $delivery_address = $order['delivery_address']; $status = $order['status']; $priority = $order['priority']; $free_shipping = $order['free_shipping']; $is_paid = $order['is_paid']; $pickup = $order['pickup']; $delivery_datetime = $order['delivery_datetime']; // Handle form submission for updating the order if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Retrieve and sanitize form inputs $customer_name = sanitize_input($_POST['customer_name'] ?? ''); $contact_input = sanitize_input($_POST['contact'] ?? ''); $selected_country = sanitize_input($_POST['country'] ?? '+965'); $delivery_address = sanitize_input($_POST['delivery_address'] ?? ''); $status = sanitize_input($_POST['status'] ?? ''); $priority = sanitize_input($_POST['priority'] ?? ''); $free_shipping = isset($_POST['free_shipping']) ? 1 : 0; $is_paid = isset($_POST['is_paid']) ? 1 : 0; $pickup = isset($_POST['pickup']) ? 1 : 0; // Handle delivery_datetime conversion from 'Y-m-d\TH:i' to 'Y-m-d H:i:s' $delivery_datetime_input = $_POST['delivery_datetime'] ?? ''; if (!empty($delivery_datetime_input)) { $parsed_datetime = strtotime($delivery_datetime_input); if ($parsed_datetime !== false) { $delivery_datetime = date('Y-m-d H:i:s', $parsed_datetime); } else { $delivery_datetime = null; } } else { $delivery_datetime = null; } // Determine delivery_fee based on free_shipping and pickup if (!$free_shipping && !$pickup) { $delivery_fee = isset($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00; } else { $delivery_fee = 0.00; } // Handle existing order items $existing_item_ids = $_POST['existing_item_id'] ?? []; $existing_product_ids = $_POST['existing_product_id'] ?? []; $existing_quantities = $_POST['existing_quantity'] ?? []; $existing_packaging_preferences = $_POST['existing_packaging_preferences'] ?? []; $existing_apply_discount = $_POST['existing_apply_discount'] ?? []; $existing_discount_percentages = $_POST['existing_discount_percentage'] ?? []; $existing_discount_reasons = $_POST['existing_discount_reason'] ?? []; // Handle new order items $new_product_ids = $_POST['new_product_id'] ?? []; $new_quantities = $_POST['new_quantity'] ?? []; $new_packaging_preferences = $_POST['new_packaging_preferences'] ?? []; $new_apply_discount = $_POST['new_apply_discount'] ?? []; $new_discount_percentages = $_POST['new_discount_percentage'] ?? []; $new_discount_reasons = $_POST['new_discount_reason'] ?? []; // Handle deleted existing order items $deleted_existing_item_ids = $_POST['deleted_existing_item_ids'] ?? []; $active_existing_item_ids = array_diff($existing_item_ids, $deleted_existing_item_ids); // Initialize Error Array $errors = []; // Validate essential fields if (empty($customer_name)) { $errors[] = "Customer name is required."; } if (empty($contact_input)) { $errors[] = "Contact number is required."; } if (empty($status)) { $errors[] = "Order status is required."; } if (empty($priority)) { $errors[] = "Order priority is required."; } if (empty($active_existing_item_ids) && empty($new_product_ids)) { $errors[] = "At least one product must be selected."; } // Validate contact number $contact_digits = preg_replace('/\D/', '', $contact_input); if (empty($contact_digits)) { $errors[] = "A valid contact number is required."; } else { // Full contact number with country code $full_contact = $selected_country . $contact_digits; } // Validate delivery fee only if not free_shipping or pickup if (!$free_shipping && !$pickup && ($delivery_fee < 0)) { $errors[] = "Delivery fee cannot be negative."; } // Validate existing order items foreach ($active_existing_item_ids as $index => $item_id) { $item_index = array_search($item_id, $existing_item_ids); $product_id = intval($existing_product_ids[$item_index] ?? 0); $quantity = intval($existing_quantities[$item_index] ?? 0); if ($product_id <= 0) { $errors[] = "Product selection is required for all existing items."; break; } if ($quantity <= 0) { $errors[] = "Quantity must be at least 1 for all existing items."; break; } // Handle discounts for existing items if (isset($existing_apply_discount[$item_index])) { $discount_percentage = floatval(trim($existing_discount_percentages[$item_index] ?? 0)); $discount_reason = sanitize_input($existing_discount_reasons[$item_index] ?? ''); if ($discount_percentage <= 0 && !empty($existing_discount_percentages[$item_index])) { $errors[] = "Discount percentage must be greater than 0 if discount is applied for existing items."; break; } if ($discount_percentage < 0 || $discount_percentage > 100) { $errors[] = "Invalid discount percentage for existing items. It should be between 0 and 100."; break; } if (empty($discount_reason) && $discount_percentage > 0) { $errors[] = "Discount reason is required if discount is applied for existing items."; break; } } } // Validate new order items foreach ($new_product_ids as $index => $product_id) { $product_id = intval($product_id); $quantity = intval($new_quantities[$index] ?? 0); if ($product_id <= 0) { $errors[] = "Product selection is required for all new items."; break; } if ($quantity <= 0) { $errors[] = "Quantity must be at least 1 for all new items."; break; } // Handle discounts for new items if (isset($new_apply_discount[$index])) { $discount_percentage = floatval(trim($new_discount_percentages[$index] ?? 0)); $discount_reason = sanitize_input($new_discount_reasons[$index] ?? ''); if ($discount_percentage <= 0 && !empty($new_discount_percentages[$index])) { $errors[] = "Discount percentage must be greater than 0 if discount is applied for new items."; break; } if ($discount_percentage < 0 || $discount_percentage > 100) { $errors[] = "Invalid discount percentage for new items. It should be between 0 and 100."; break; } if (empty($discount_reason) && $discount_percentage > 0) { $errors[] = "Discount reason is required if discount is applied for new items."; break; } } } // If no errors, proceed to update the order if (empty($errors)) { // Start Transaction $conn->begin_transaction(); try { // Step 1: Update Customer Details // If pickup is selected, clear the delivery_address if ($pickup) { $delivery_address = ''; } $stmt = $conn->prepare("UPDATE customers SET name = ?, contact = ?, delivery_address = ? WHERE id = ?"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } $stmt->bind_param("sssi", $customer_name, $full_contact, $delivery_address, $order['customer_id']); if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); // Step 2: Update Order Table $stmt = $conn->prepare("UPDATE orders SET status = ?, priority = ?, delivery_fee = ?, free_shipping = ?, is_paid = ?, pickup = ?, delivery_datetime = ? WHERE id = ?"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } // Handle NULL for delivery_datetime if ($delivery_datetime !== null) { $stmt->bind_param("ssdiiisi", $status, $priority, $delivery_fee, $free_shipping, $is_paid, $pickup, $delivery_datetime, $order_id); } else { // If delivery_datetime is null, set it as NULL in the database $stmt = $conn->prepare("UPDATE orders SET status = ?, priority = ?, delivery_fee = ?, free_shipping = ?, is_paid = ?, pickup = ?, delivery_datetime = NULL WHERE id = ?"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } $stmt->bind_param("ssdiiis", $status, $priority, $delivery_fee, $free_shipping, $is_paid, $pickup, $order_id); } if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); // Step 3: Remove Deleted Existing Order Items if (!empty($deleted_existing_item_ids)) { // Prepare placeholders $placeholders = implode(',', array_fill(0, count($deleted_existing_item_ids), '?')); $types = str_repeat('i', count($deleted_existing_item_ids)); $stmt = $conn->prepare("DELETE FROM order_items WHERE id IN ($placeholders)"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } // Dynamically bind parameters $stmt->bind_param($types, ...array_map('intval', $deleted_existing_item_ids)); if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); } // Step 4: Update Existing Order Items foreach ($active_existing_item_ids as $index => $item_id) { $item_index = array_search($item_id, $existing_item_ids); $product_id = intval($existing_product_ids[$item_index]); $quantity = intval($existing_quantities[$item_index]); $packaging_preferences = sanitize_input($existing_packaging_preferences[$item_index] ?? ''); // Handle discounts $discount_percentage = 0.00; $discount_reason = ''; if (isset($existing_apply_discount[$item_index])) { $discount_percentage = floatval(trim($existing_discount_percentages[$item_index])); $discount_reason = sanitize_input($existing_discount_reasons[$item_index]); // If discount_percentage is 0, set discount_reason to empty if ($discount_percentage <= 0) { $discount_reason = ''; } } $stmt = $conn->prepare("UPDATE order_items SET product_id = ?, quantity = ?, packaging_preferences = ?, discount_percentage = ?, discount_reason = ? WHERE id = ?"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } $stmt->bind_param("iidssi", $product_id, $quantity, $packaging_preferences, $discount_percentage, $discount_reason, $item_id); if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); } // Step 5: Add New Order Items foreach ($new_product_ids as $index => $product_id) { $product_id = intval($product_id); $quantity = intval($new_quantities[$index]); $packaging_preferences = sanitize_input($new_packaging_preferences[$index] ?? ''); // Handle discounts $discount_percentage = 0.00; $discount_reason = ''; if (isset($new_apply_discount[$index])) { $discount_percentage = floatval(trim($new_discount_percentages[$index])); $discount_reason = sanitize_input($new_discount_reasons[$index]); // If discount_percentage is 0, set discount_reason to empty if ($discount_percentage <= 0) { $discount_reason = ''; } } $stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, packaging_preferences, discount_percentage, discount_reason) VALUES (?, ?, ?, ?, ?, ?)"); if (!$stmt) { throw new Exception("Prepare statement failed: " . $conn->error); } $stmt->bind_param("iiidsi", $order_id, $product_id, $quantity, $packaging_preferences, $discount_percentage, $discount_reason); if (!$stmt->execute()) { throw new Exception("Execute failed: " . $stmt->error); } $stmt->close(); } // Commit Transaction $conn->commit(); // Redirect to view_orders.php with success message header("Location: view_orders.php?success=Order+updated+successfully"); exit(); } catch (Exception $e) { // Rollback Transaction $conn->rollback(); $error = "Error updating order: " . sanitize_input($e->getMessage()); } } else { // If there are validation errors, concatenate them $error = implode(' ', $errors); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Edit Order #<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?> - Kaak Alia Management System</title> <!-- Tailwind CSS CDN --> <script src="https://cdn.tailwindcss.com"></script> <!-- Bootstrap Icons --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"> <!-- Flatpickr CSS for Date Picker --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> <!-- Custom Styles --> <style> /* Custom scrollbar for better UX */ ::-webkit-scrollbar { width: 8px; } ::-webkit-scrollbar-track { background: #f1f5f9; /* Tailwind's gray-100 */ } ::-webkit-scrollbar-thumb { background: #20B2AA; /* Teal-500 */ border-radius: 4px; } ::-webkit-scrollbar-thumb:hover { background: #0d9488; /* Teal-600 */ } /* Tooltip styles */ .tooltip { position: relative; display: inline-block; cursor: pointer; } .tooltip .tooltiptext { visibility: hidden; width: 250px; background-color: #6B7280; /* Tailwind's gray-500 */ color: #fff; text-align: left; border-radius: 4px; padding: 8px; position: absolute; z-index: 10; bottom: 125%; /* Position above the icon */ left: 50%; margin-left: -125px; opacity: 0; transition: opacity 0.3s; } .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } </style> <!-- Additional JavaScript for dynamic product addition, discount handling, delivery fee toggle, and pickup handling --> <script> let productCount = <?= count($order_items) > 0 ? count($order_items) : 1; ?>; function addProductRow() { const productContainer = document.getElementById('new-products-container'); const productRow = document.createElement('div'); productRow.className = 'product-row bg-gray-50 p-4 rounded-lg shadow-md mb-4'; productRow.innerHTML = ` <div class="grid grid-cols-1 md:grid-cols-4 gap-4"> <div> <label class="block text-sm font-medium text-gray-700" for="new_product_id_${productCount}"> Product <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Select the product from the dropdown menu. This list includes available items that can be added to the customer's order. </span> </span> </label> <select name="new_product_id[]" id="new_product_id_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required> <option value="">Select Product</option> <?php foreach($products as $product_option): ?> <option value="<?= htmlspecialchars($product_option['id'], ENT_QUOTES, 'UTF-8') ?>"> <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)", ENT_QUOTES, 'UTF-8') ?> </option> <?php endforeach; ?> </select> </div> <div> <label class="block text-sm font-medium text-gray-700" for="new_quantity_${productCount}"> Quantity <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter the number of units required for each selected product. Quantities must be in whole numbers and are defaulted to one (1) if not specified. </span> </span> </label> <input type="number" name="new_quantity[]" id="new_quantity_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="1" required> </div> <div> <label class="block text-sm font-medium text-gray-700" for="new_packaging_preferences_${productCount}"> Packaging Preferences <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Specify any particular packaging requests, such as 'Gift Wrap' or 'Fragile - Handle with Care,' to ensure customer satisfaction and safe delivery. </span> </span> </label> <input type="text" name="new_packaging_preferences[]" id="new_packaging_preferences_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap"> </div> <div> <label class="block text-sm font-medium text-gray-700" for="new_discount_${productCount}"> Apply Discount <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Check this box if the customer is eligible for a discount. Discounts will be applied to the total product cost at checkout. </span> </span> </label> <div class="flex items-center mt-1"> <input type="checkbox" name="new_apply_discount[]" id="new_discount_checkbox_${productCount}" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleNewDiscountFields(this, ${productCount})"> <label for="new_discount_checkbox_${productCount}" class="ml-2 block text-sm text-gray-700"> Yes </label> </div> <div id="new_discount_fields_${productCount}" class="discount-fields mt-2" style="display: none;"> <label class="block text-sm font-medium text-gray-700" for="new_discount_percentage_${productCount}"> Discount Percentage (%) <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter the discount percentage to be applied to this product. It should be between 0 and 100. </span> </span> </label> <input type="number" name="new_discount_percentage[]" id="new_discount_percentage_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage" required> <label class="block text-sm font-medium text-gray-700 mt-2" for="new_discount_reason_${productCount}"> Discount Reason <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Provide a reason for the discount applied to this product. </span> </span> </label> <input type="text" name="new_discount_reason[]" id="new_discount_reason_${productCount}" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" required> </div> </div> </div> <div class="flex justify-end mt-2"> <button type="button" class="remove-product-button bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition duration-300 flex items-center gap-2" onclick="removeProductRow(this)"> <i class="bi bi-trash-fill"></i> Remove Product </button> </div> `; productContainer.appendChild(productRow); productCount++; } function removeProductRow(button) { const productRow = button.closest('.product-row'); productRow.remove(); } // Toggle discount fields based on checkbox for existing items function toggleDiscountFields(checkbox, count) { const discountFields = document.getElementById(`discount_fields_${count}`); if (checkbox.checked) { discountFields.style.display = 'block'; } else { discountFields.style.display = 'none'; // Clear discount inputs discountFields.querySelectorAll('input').forEach(input => input.value = ''); } } // Toggle discount fields based on checkbox for new items function toggleNewDiscountFields(checkbox, count) { const discountFields = document.getElementById(`new_discount_fields_${count}`); if (checkbox.checked) { discountFields.style.display = 'block'; } else { discountFields.style.display = 'none'; // Clear discount inputs discountFields.querySelectorAll('input').forEach(input => input.value = ''); } } // Toggle delivery fee field based on free shipping and pickup checkboxes function toggleDeliveryFee() { const freeShippingCheckbox = document.getElementById('free_shipping'); const pickupCheckbox = document.getElementById('pickup'); const deliveryFeeField = document.getElementById('delivery_fee_field'); const deliveryFeeInput = document.getElementById('delivery_fee'); if (freeShippingCheckbox.checked || pickupCheckbox.checked) { deliveryFeeField.style.display = 'none'; deliveryFeeInput.value = '0.00'; deliveryFeeInput.disabled = true; } else { deliveryFeeField.style.display = 'block'; deliveryFeeInput.disabled = false; } } // Toggle specific delivery details based on pickup checkbox function togglePickup() { const pickupCheckbox = document.getElementById('pickup'); const freeShippingCheckbox = document.getElementById('free_shipping'); const deliveryFeeInput = document.getElementById('delivery_fee'); const deliveryFeeField = document.getElementById('delivery_fee_field'); const deliveryAddressField = document.getElementById('delivery_address_field'); if (pickupCheckbox.checked) { // Hide Delivery Address deliveryAddressField.style.display = 'none'; // Uncheck and hide Free Shipping if it's checked if (freeShippingCheckbox.checked) { freeShippingCheckbox.checked = false; toggleDeliveryFee(); } // Hide Delivery Fee deliveryFeeField.style.display = 'none'; deliveryFeeInput.value = '0.00'; deliveryFeeInput.disabled = true; } else { // Show Delivery Address deliveryAddressField.style.display = 'block'; // Show Delivery Fee based on Free Shipping status toggleDeliveryFee(); } } // Auto-generate Customer Name based on Contact Number function autoGenerateCustomerName() { const contactInput = document.getElementById('contact'); const customerNameInput = document.getElementById('customer_name'); // Extract digits from contact number const digits = contactInput.value.replace(/\D/g, ''); if (digits.length > 0) { customerNameInput.value = 'Order_' + digits; } else { customerNameInput.value = ''; } } // Initialize on DOM content loaded document.addEventListener('DOMContentLoaded', function() { // Initialize delivery fee toggle toggleDeliveryFee(); const freeShippingEl = document.getElementById('free_shipping'); if (freeShippingEl) { freeShippingEl.addEventListener('change', toggleDeliveryFee); } // Initialize pickup toggle togglePickup(); const pickupEl = document.getElementById('pickup'); if (pickupEl) { pickupEl.addEventListener('change', togglePickup); } // Initialize Customer Name auto-generation const contactEl = document.getElementById('contact'); if (contactEl) { contactEl.addEventListener('input', autoGenerateCustomerName); } // Initialize tooltip functionality var tooltipTriggerList = [].slice.call(document.querySelectorAll('.tooltip')) tooltipTriggerList.forEach(function (tooltipTriggerEl) { var tooltipText = tooltipTriggerEl.querySelector('.tooltiptext'); tooltipTriggerEl.addEventListener('mouseenter', function() { tooltipText.style.visibility = 'visible'; tooltipText.style.opacity = '1'; }); tooltipTriggerEl.addEventListener('mouseleave', function() { tooltipText.style.visibility = 'hidden'; tooltipText.style.opacity = '0'; }); }); }); </script> </head> <body class="font-inter bg-gray-100"> <!-- Include header.php inside the body --> <?php require_once '../../includes/header.php'; ?> <!-- Main Container --> <main class="container mx-auto p-6"> <!-- Page Header --> <div class="mb-8"> <h1 class="text-3xl font-bold text-blue-600 flex items-center"> <i class="bi bi-pencil-square mr-2"></i> Edit Order #<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?> </h1> </div> <!-- Welcome Section --> <div class="bg-white rounded-lg shadow-lg p-6 mb-8"> <p class="text-gray-700">Update the details of the order below. Ensure all changes are accurate before submission.</p> </div> <!-- Form Container --> <div class="bg-white rounded-lg shadow-lg p-6"> <?php if (!empty($error)): ?> <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4 flex items-center"> <i class="bi bi-exclamation-triangle-fill mr-2"></i> <span><?= $error ?></span> </div> <?php endif; ?> <?php if (!empty($success)): ?> <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4 flex items-center"> <i class="bi bi-check-circle-fill mr-2"></i> <span><?= $success ?></span> </div> <?php endif; ?> <form method="POST" action="edit_order.php?order_id=<?= htmlspecialchars($order_id, ENT_QUOTES, 'UTF-8') ?>"> <!-- Customer Details --> <div class="mb-6"> <h2 class="text-xl font-semibold text-gray-800 mb-4">Customer Details</h2> <div class="flex flex-col md:flex-row md:space-x-6"> <div class="flex-1 mb-4 md:mb-0"> <label class="block text-sm font-medium text-gray-700 mb-1" for="customer_name"> Customer Name <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Automatically generated based on contact number. If unavailable, enter the customer's full name for record purposes. </span> </span> </label> <input type="text" id="customer_name" name="customer_name" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" value="<?= htmlspecialchars($customer_name ?? $order['customer_name'], ENT_QUOTES, 'UTF-8') ?>" placeholder="Enter customer name" required> </div> <div class="flex-1 mb-4 md:mb-0"> <label class="block text-sm font-medium text-gray-700 mb-1" for="country"> Country <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Select the customer’s country to ensure accurate address formatting and delivery options. Default is set based on existing contact. </span> </span> </label> <select name="country" id="country" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required> <?php foreach($countries as $country => $code): ?> <option value="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>" <?= ($selected_country === $code) ? 'selected' : '' ?>> <?= htmlspecialchars($country . " (" . $code . ")", ENT_QUOTES, 'UTF-8') ?> </option> <?php endforeach; ?> </select> </div> </div> <div class="flex flex-col md:flex-row md:space-x-6 mt-4"> <div class="flex-1 mb-4 md:mb-0" id="contact_field"> <label class="block text-sm font-medium text-gray-700 mb-1" for="contact"> Contact Number <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter a valid contact number without the country code. The country code is auto-prepended based on selected country. </span> </span> </label> <input type="text" id="contact" name="contact" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" value="<?= htmlspecialchars($contact_number, ENT_QUOTES, 'UTF-8') ?>" required placeholder="Enter contact number without country code"> </div> <div class="flex-1" id="delivery_address_field"> <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_address"> Delivery Address <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Provide the full delivery address, including building name, street, area, and any special instructions to facilitate easy and efficient delivery. </span> </span> </label> <textarea id="delivery_address" name="delivery_address" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" rows="3" placeholder="Enter delivery address"><?= htmlspecialchars($delivery_address ?? '', ENT_QUOTES, 'UTF-8') ?></textarea> </div> </div> </div> <hr class="my-6"> <!-- Order Details --> <div class="mb-6"> <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Details</h2> <!-- Priority Selection --> <div class="mb-4"> <label class="block text-sm font-medium text-gray-700 mb-1"> Order Priority <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Choose a priority level for this order based on urgency: Normal for standard processing, Important for prioritized handling, and Quick for immediate attention. </span> </span> </label> <div class="flex space-x-4"> <?php $priorities = ['Normal', 'Important', 'Quick']; foreach ($priorities as $priority_option): $checked = ($priority === $priority_option) ? 'checked' : ''; ?> <label class="inline-flex items-center"> <input type="radio" name="priority" value="<?= htmlspecialchars($priority_option, ENT_QUOTES, 'UTF-8') ?>" class="form-radio text-teal-600" <?= $checked ?> required> <span class="ml-2"><?= htmlspecialchars($priority_option, ENT_QUOTES, 'UTF-8') ?></span> </label> <?php endforeach; ?> </div> </div> <!-- Status Selection --> <div class="mb-4"> <label class="block text-sm font-medium text-gray-700 mb-1"> Order Status <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Update the current status of the order: Pending, In Progress, Completed, or Delivered. </span> </span> </label> <select name="status" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required> <option value="Pending" <?= ($status == 'Pending') ? 'selected' : '' ?>>Pending</option> <option value="In Progress" <?= ($status == 'In Progress') ? 'selected' : '' ?>>In Progress</option> <option value="Completed" <?= ($status == 'Completed') ? 'selected' : '' ?>>Completed</option> <option value="Delivered" <?= ($status == 'Delivered') ? 'selected' : '' ?>>Delivered</option> </select> </div> <!-- Delivery Fee and Free Shipping --> <div class="mb-4" id="delivery_fee_field"> <label class="block text-sm font-medium text-gray-700 mb-1"> Delivery Fee (KWD) <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter any applicable delivery fee in Kuwaiti Dinar (KWD). This field will automatically set to 0 if ‘Free Shipping’ is selected or if pickup is chosen. </span> </span> </label> <input type="number" step="0.01" min="0" name="delivery_fee" id="delivery_fee" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" value="<?= htmlspecialchars($delivery_fee, ENT_QUOTES, 'UTF-8') ?>" <?= ($free_shipping || $pickup) ? 'disabled' : '' ?> required> </div> <div class="flex items-center mb-4"> <input type="checkbox" id="free_shipping" name="free_shipping" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= $free_shipping ? 'checked' : '' ?> onchange="toggleDeliveryFee()"> <label for="free_shipping" class="ml-2 block text-sm text-gray-700"> Free Shipping <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Select this option if the customer qualifies for free shipping based on promotional offers or order amount. Delivery fees will automatically update. </span> </span> </label> </div> <!-- Pickup Checkbox --> <div class="flex items-center mb-4"> <input type="checkbox" id="pickup" name="pickup" class="h-4 w-4 text-teal-600 border-gray-300 rounded" <?= $pickup ? 'checked' : '' ?> onchange="togglePickup()"> <label for="pickup" class="ml-2 block text-sm text-gray-700"> Customer Pickup <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Select this option if the customer will pick up the order directly from our kitchen, eliminating the need for delivery. </span> </span> </label> </div> <!-- Delivery Date and Time --> <div class="mb-4"> <label class="block text-sm font-medium text-gray-700 mb-1" for="delivery_datetime"> Delivery Date and Time <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Choose a specific date and time for the order delivery or pickup. Ensure the date aligns with the customer’s availability and our schedule to avoid delays. </span> </span> </label> <input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" value="<?= htmlspecialchars($delivery_datetime ? date('Y-m-d\TH:i', strtotime($delivery_datetime)) : '', ENT_QUOTES, 'UTF-8') ?>" required> </div> </div> <hr class="my-6"> <!-- Order Items --> <div class="mb-6"> <h2 class="text-xl font-semibold text-gray-800 mb-4">Order Items</h2> <!-- Existing Order Items --> <div class="mb-4"> <h3 class="text-lg font-semibold mb-2">Existing Items</h3> <?php if (empty($order_items)): ?> <p class="text-gray-600">No existing items for this order.</p> <?php else: ?> <?php foreach ($order_items as $index => $item): ?> <div class="border border-gray-300 rounded-lg p-4 mb-4"> <input type="hidden" name="existing_item_id[]" value="<?= htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') ?>"> <div class="grid grid-cols-1 md:grid-cols-5 gap-4"> <div> <label class="block text-sm font-medium text-gray-700" for="existing_product_id_<?= $index ?>"> Product <span class="text-red-500">*</span> </label> <select name="existing_product_id[]" id="existing_product_id_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required> <option value="">Select Product</option> <?php foreach($products as $product_option): ?> <option value="<?= htmlspecialchars($product_option['id'], ENT_QUOTES, 'UTF-8') ?>" <?= ($product_option['id'] == $item['product_id']) ? 'selected' : '' ?>> <?= htmlspecialchars($product_option['name'] . " - " . $product_option['size'] . " (" . number_format($product_option['price'], 2) . " KD)", ENT_QUOTES, 'UTF-8') ?> </option> <?php endforeach; ?> </select> </div> <div> <label class="block text-sm font-medium text-gray-700" for="existing_quantity_<?= $index ?>"> Quantity <span class="text-red-500">*</span> </label> <input type="number" name="existing_quantity[]" id="existing_quantity_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="<?= htmlspecialchars($item['quantity'], ENT_QUOTES, 'UTF-8') ?>" required> </div> <div> <label class="block text-sm font-medium text-gray-700" for="existing_packaging_preferences_<?= $index ?>"> Packaging Preferences </label> <input type="text" name="existing_packaging_preferences[]" id="existing_packaging_preferences_<?= $index ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($item['packaging_preferences'], ENT_QUOTES, 'UTF-8') ?>"> </div> <div> <label class="block text-sm font-medium text-gray-700" for="existing_discount_<?= $index ?>"> Apply Discount </label> <div class="flex items-center mt-1"> <input type="checkbox" name="existing_apply_discount[]" id="existing_discount_checkbox_<?= $index ?>" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, <?= $index ?>)" <?= ($item['discount_percentage'] > 0) ? 'checked' : '' ?>> <label for="existing_discount_checkbox_<?= $index ?>" class="ml-2 block text-sm text-gray-700"> Yes </label> </div> <div id="discount_fields_<?= $index ?>" class="discount-fields mt-2" style="display: <?= ($item['discount_percentage'] > 0) ? 'block' : 'none' ?>;"> <label class="block text-sm font-medium text-gray-700" for="existing_discount_percentage_<?= $index ?>"> Discount Percentage (%) <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Enter the discount percentage to be applied to this product. It should be between 0 and 100. </span> </span> </label> <input type="number" name="existing_discount_percentage[]" id="existing_discount_percentage_<?= $index ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" value="<?= htmlspecialchars($item['discount_percentage'], ENT_QUOTES, 'UTF-8') ?>" required> <label class="block text-sm font-medium text-gray-700 mt-2" for="existing_discount_reason_<?= $index ?>"> Discount Reason <span class="text-red-500">*</span> <span class="tooltip"> <i class="bi bi-question-circle text-gray-400 text-sm"></i> <span class="tooltiptext"> Provide a reason for the discount applied to this product. </span> </span> </label> <input type="text" name="existing_discount_reason[]" id="existing_discount_reason_<?= $index ?>" class="block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" value="<?= htmlspecialchars($item['discount_reason'], ENT_QUOTES, 'UTF-8') ?>" required> </div> </div> <div class="flex items-center"> <label class="flex items-center"> <input type="checkbox" name="deleted_existing_item_ids[]" value="<?= htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') ?>" class="h-4 w-4 text-red-600 border-gray-300 rounded"> <span class="ml-2 text-sm text-gray-700">Delete</span> </label> </div> </div> </div> <?php endforeach; ?> <?php endif; ?> </div> <!-- New Order Items --> <div class="mb-4"> <h3 class="text-lg font-semibold mb-2">Add New Items</h3> <div id="new-products-container"> <!-- New Product Rows will be added here --> </div> <button type="button" class="bg-teal-500 text-white px-4 py-2 rounded-lg hover:bg-teal-600 transition duration-300 flex items-center gap-2 mt-4" onclick="addProductRow()"> <i class="bi bi-plus-circle-fill"></i> Add Another Product </button> </div> </div> <hr class="my-6"> <!-- Submit Button --> <div class="mb-6"> <button type="submit" class="w-full bg-green-500 text-white px-4 py-3 rounded-lg hover:bg-green-600 transition duration-300 flex justify-center items-center gap-2"> <i class="bi bi-save"></i> Update Order </button> </div> </form> </div> <!-- Footer --> <div class="mt-12 text-center text-gray-600"> © <?= date("Y") ?> Kaak Alia Bakery. All rights reserved. </div> </main> <!-- Bootstrap JS Bundle (optional if using Bootstrap components) --> <script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Flatpickr JS for Date Picker --> <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> <!-- Flatpickr Initialization --> <script> flatpickr("#delivery_datetime", { enableTime: true, dateFormat: "Y-m-d\\TH:i", minDate: "today" }); </script> </body> </html> <?php // Flush the output buffer ob_end_flush(); // No closing PHP tag to prevent unwanted output ?>
Key Changes and Improvements
-
Consistent Parameter Naming:
- Before:
edit_order.phpused$_GET['id']to retrieve theorder_id. - After: Changed to use
$_GET['order_id']to maintain consistency withview_order_customer.php.
- Before:
-
Enhanced Security:
- Input Sanitization: All user inputs are sanitized using the
sanitize_input()function to prevent malicious data from being processed. - Prepared Statements: Utilizes prepared statements with bound parameters (
bind_param) to prevent SQL injection attacks.
- Input Sanitization: All user inputs are sanitized using the
-
Error Handling:
- Comprehensive Error Messages: All potential errors during form submission are captured and displayed to the user in a user-friendly manner.
- Database Error Handling: Catches and handles database-related errors gracefully by rolling back transactions if any step fails.
-
Code Organization:
- Separation of Concerns: Distinct sections for fetching data, handling form submissions, and rendering the HTML form.
- Comments: Added comments throughout the code to explain functionality and improve readability.
-
User Experience Enhancements:
- Dynamic Form Fields: JavaScript functions handle the addition and removal of new product rows, as well as the display of discount fields based on user interactions.
- Tooltips: Enhanced tooltips provide users with contextual information about various form fields, improving usability.
- Auto-Generation of Customer Name: The
autoGenerateCustomerNamefunction auto-fills the customer name based on the contact number entered, ensuring consistency.
-
Responsive Design:
- Utilizes Tailwind CSS classes to ensure the form is responsive and mobile-friendly.
-
Consistent HTML Structure:
- The form's
actionattribute now properly includes theorder_idas a GET parameter, ensuring that the server can accurately process the correct order.
- The form's
Recommendations
-
Cross-Script Consistency: Ensure that all scripts interacting with orders (like viewing, editing, deleting) use the same parameter naming conventions and validation procedures to prevent discrepancies.
-
Input Validation: While server-side validation is robust, consider adding additional client-side validations to enhance user experience.
-
Security Practices: Regularly audit your scripts for potential vulnerabilities, especially if new features are added. Consider implementing CSRF protection and other security measures as needed.
-
User Feedback: Enhance the feedback mechanisms (like success and error messages) to provide clearer guidance to the users during form interactions.
By implementing these changes, your
edit_order.phpscript will handle theorder_idmore reliably and securely, ensuring a smoother and safer experience for both administrators and customers interacting with your system. - In