please fix this codes weell (<?php //… · The Chat Archive
Explore / Programming o1-mini-2024-09-12 · OpenAI WildChat-4.8M (AI2)please fix this codes weell (<?php // public/orders/editorder.php // Enable error… Save Share Download ▾ Reportplease fix this codes weell (<?php
// public/orders/edit_order.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 0); // Set to 0 in production
ini_set('display_startup_errors', 0); // Set to 0 in production
error_reporting(E_ALL);
// Start output buffering to prevent "headers already sent" errors
ob_start();
// Include authentication, database connection, and functions
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
require_once DIR . '/../../includes/functions.php'; // Include the functions.php for sanitize_input()
// Function to sanitize input
function sanitize_input(input) {
return htmlspecialchars(trim( input), ENT_QUOTES, 'UTF-8');
}
// Initialize success and error variables
s u c c e s s = ′ ′ ; success = '';
s u ccess = ′′ ; error = '';
// Retrieve and sanitize the order ID from GET parameters
o r d e r i d = _GET['id']) ? intval($_GET['id']) : 0;
Assistant2024-11-14 23:22 UTC Copy response
Copy first prompt
Details
Model o1-mini-2024-09-12
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Nov 14, 2024
Added to archive Nov 16, 2026
ID 01m7h4294gxtwez8npj294t3d5Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: df397e49ba1820b4a7ba62639cf4b191
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
i s s e t ( order_id = isset( or d e r i d = i sse t (
// Redirect if no valid order ID is provided
if ($order_id <= 0) {
header("Location: view_orders.php?error=Invalid Order ID");
exit();
}
// Fetch order details along with customer information and is_paid status
o r d e r s q l = " S E L E C T o . ∗ , c . n a m e A S c u s t o m e r n a m e , c . c o n t a c t A S c u s t o m e r c o n t a c t , c . d e l i v e r y a d d r e s s F R O M o r d e r s o J O I N c u s t o m e r s c O N o . c u s t o m e r i d = c . i d W H E R E o . i d = ? L I M I T 1 " ; 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";
or d e r s q l = " S E L E C T o . ∗ , c . nam e A S c u s t o m e r order_stmt = c o n n − > p r e p a r e ( conn->prepare( co nn − > p r e p a r e ( order_sql);
if (!order_stmt) {
die("Prepare statement failed: " . conn->error);
}
o r d e r s t m t − > b i n d p a r a m ( " i " , order_stmt->bind_param("i", or d e r s t m t − > bin d p a r am order_id);
o r d e r s t m t − > e x e c u t e ( ) ; order_stmt->execute();
or d e r s t m t − > e x ec u t e ( ) ; order_result = $order_stmt->get_result();
if ($order_result->num_rows != 1) {
header("Location: view_orders.php?error=Order Not Found");
exit();
}
o r d e r = order = or d er = order_result->fetch_assoc();
$order_stmt->close();
// Fetch existing order items
o r d e r i t e m s s q l = " S E L E C T o i . ∗ , p . n a m e A S p r o d u c t n a m e , p . s i z e , p . p r i c e F R O M o r d e r i t e m s o i J O I N p r o d u c t s p O N o i . p r o d u c t i d = p . i d W H E R E o i . o r d e r i d = ? " ; 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 = ?";
or d e r i t e m s s q l = " S E L E C T o i . ∗ , p . nam e A S order_items_stmt = c o n n − > p r e p a r e ( conn->prepare( co nn − > p r e p a r e ( order_items_sql);
if (!order_items_stmt) {
die("Prepare statement failed: " . conn->error);
}
o r d e r i t e m s s t m t − > b i n d p a r a m ( " i " , order_items_stmt->bind_param("i", or d e r i t e m s s t m t − > order_id);
o r d e r i t e m s s t m t − > e x e c u t e ( ) ; order_items_stmt->execute();
or d e r i t e m s s t m t − > e x order_items_result = o r d e r i t e m s s t m t − > g e t r e s u l t ( ) ; order_items_stmt->get_result();
or d e r i t e m s s t m t − > order_items = [];
while (i t e m = item = i t e m = order_items_result->fetch_assoc()) {
o r d e r i t e m s [ ] = order_items[] = or d e r i t e m s [ ] = item;
}
$order_items_stmt->close();
// Fetch products for selection
p r o d u c t s s q l = " S E L E C T ∗ F R O M p r o d u c t s O R D E R B Y n a m e A S C " ; products_sql = "SELECT * FROM products ORDER BY name ASC";
p r o d u c t s s q l = " S E L E C T ∗ F R O M p r o d u c t s O R D E R B Y nam e A S C " ; products_result = c o n n − > q u e r y ( conn->query( co nn − > q u er y ( products_sql);
// Handle form submission for updating the order
if (_SERVER['REQUEST_METHOD'] == 'POST') {
// Retrieve and sanitize form inputs
customer_name = sanitize_input(P O S T [ ′ c u s t o m e r n a m e ′ ] ) ; _POST['customer_name']);
P O S T [ ′ c u s t o m e r n am e ′ ]) ; contact = sanitize_input(P O S T [ ′ c o n t a c t ′ ] ) ; _POST['contact']);
P O S T [ ′ co n t a c t ′ ]) ; delivery_address = sanitize_input(P O S T [ ′ d e l i v e r y a d d r e s s ′ ] ) ; _POST['delivery_address']);
P O S T [ ′ d e l i v er y status = sanitize_input(P O S T [ ′ s t a t u s ′ ] ) ; _POST['status']);
P O S T [ ′ s t a t u s ′ ]) ; priority = sanitize_input(P O S T [ ′ p r i o r i t y ′ ] ? ? ′ N o r m a l ′ ) ; / / I n i t i a l i z e s _POST['priority'] ?? 'Normal'); // Initializes P O S T [ ′ p r i priority
d e l i v e r y d a t e t i m e = i s s e t ( delivery_datetime = isset( d e l i v er y d a t e t im e = i sse t ( _POST['delivery_datetime']) && !empty(P O S T [ ′ d e l i v e r y d a t e t i m e ′ ] ) ? s a n i t i z e i n p u t ( _POST['delivery_datetime']) ? sanitize_input( P O S T [ ′ d e l i v er _POST['delivery_datetime']) : null;
d e l i v e r y d a t e = i s s e t ( delivery_date = isset( d e l i v er y d a t e = i sse t ( _POST['delivery_date']) && !empty(P O S T [ ′ d e l i v e r y d a t e ′ ] ) ? s a n i t i z e i n p u t ( _POST['delivery_date']) ? sanitize_input( P O S T [ ′ d e l i v er _POST['delivery_date']) : null;
// New fields based on database schema
$delivery_fee = isset($_POST['delivery_fee']) && is_numeric($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00;
$free_shipping = isset($_POST['free_shipping']) ? 1 : 0;
$is_paid = isset($_POST['is_paid']) ? 1 : 0; // New field
// If free shipping is selected, set delivery_fee to 0.00
if ($free_shipping) {
$delivery_fee = 0.00;
}
// Handle existing order items
$existing_item_ids = isset($_POST['existing_item_id']) ? $_POST['existing_item_id'] : [];
$product_ids = isset($_POST['product_id']) ? $_POST['product_id'] : [];
$quantities = isset($_POST['quantity']) ? $_POST['quantity'] : [];
$packaging_preferences = isset($_POST['packaging_preferences']) ? $_POST['packaging_preferences'] : [];
$discount_percentages = isset($_POST['discount_percentage']) ? $_POST['discount_percentage'] : [];
$discount_reasons = isset($_POST['discount_reason']) ? $_POST['discount_reason'] : [];
// Handle new order items
$new_product_ids = isset($_POST['new_product_id']) ? $_POST['new_product_id'] : [];
$new_quantities = isset($_POST['new_quantity']) ? $_POST['new_quantity'] : [];
$new_packaging_preferences = isset($_POST['new_packaging_preferences']) ? $_POST['new_packaging_preferences'] : [];
$new_discount_percentages = isset($_POST['new_discount_percentage']) ? $_POST['new_discount_percentage'] : [];
$new_discount_reasons = isset($_POST['new_discount_reason']) ? $_POST['new_discount_reason'] : [];
// Basic validation
if (empty($customer_name)) {
$error = "Customer name is required.";
} elseif (empty($status)) {
$error = "Order status is required.";
} elseif (empty($priority)) {
$error = "Order priority is required.";
} elseif ((empty($existing_item_ids) && empty($new_product_ids))) {
$error = "At least one product must be selected.";
} else {
// Validate each existing product entry
foreach ($existing_item_ids as $index => $item_id) {
if (empty($product_ids[$index])) {
$error = "Product selection is required for all existing items.";
break;
}
if (!isset($quantities[$index]) || intval($quantities[$index]) <= 0) {
$error = "Quantity must be at least 1 for all existing items.";
break;
}
if ($discount_percentages[$index] !== '' && (floatval($discount_percentages[$index]) < 0 || floatval($discount_percentages[$index]) > 100)) {
$error = "Discount percentage must be between 0 and 100.";
break;
}
}
// Validate new product entries
foreach ($new_product_ids as $index => $pid) {
if (!empty($pid)) {
if (intval($new_quantities[$index]) <= 0) {
$error = "Quantity must be at least 1 for all new items.";
break;
}
if ($new_discount_percentages[$index] !== '' && (floatval($new_discount_percentages[$index]) < 0 || floatval($new_discount_percentages[$index]) > 100)) {
$error = "Discount percentage must be between 0 and 100 for all new items.";
break;
}
}
}
if ($delivery_datetime && strtotime(str_replace('T', ' ', $delivery_datetime)) < strtotime(date('Y-m-d H:i'))) {
$error = "Delivery date and time cannot be in the past.";
}
if ($delivery_date && strtotime($delivery_date) < strtotime(date('Y-m-d'))) {
$error = "Delivery date cannot be in the past.";
}
}
if (empty($error)) {
// Start transaction
$conn->begin_transaction();
try {
// Update customer details
$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, $contact, $delivery_address, $order['customer_id']);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$stmt->close();
// Update orders table with new fields including is_paid
$stmt = $conn->prepare("UPDATE orders SET status = ?, priority = ?, delivery_datetime = ?, delivery_date = ?, delivery_fee = ?, free_shipping = ?, is_paid = ? WHERE id = ?");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("ssssdiii", $status, $priority, $delivery_datetime, $delivery_date, $delivery_fee, $free_shipping, $is_paid, $order_id);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$stmt->close();
// Update existing order items
foreach ($existing_item_ids as $index => $item_id) {
$item_id = intval($item_id);
$pid = intval($product_ids[$index]);
$qty = intval($quantities[$index]);
$pack_pref = sanitize_input($packaging_preferences[$index]);
$discount_pct = $discount_percentages[$index] !== '' ? floatval($discount_percentages[$index]) : 0.00;
$discount_rsn = sanitize_input($discount_reasons[$index]);
$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("iiisdi", $pid, $qty, $pack_pref, $discount_pct, $discount_rsn, $item_id);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$stmt->close();
}
// Insert new order items
$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);
}
for ($i = 0; $i < count($new_product_ids); $i++) {
$new_pid = intval($new_product_ids[$i]);
$new_qty = intval($new_quantities[$i]);
$new_pack_pref = sanitize_input($new_packaging_preferences[$i]);
$new_discount_pct = $new_discount_percentages[$i] !== '' ? floatval($new_discount_percentages[$i]) : 0.00;
$new_discount_rsn = sanitize_input($new_discount_reasons[$i]);
if (!empty($new_pid)) {
$stmt->bind_param("iiisds", $order_id, $new_pid, $new_qty, $new_pack_pref, $new_discount_pct, $new_discount_rsn);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
}
}
$stmt->close();
// Commit transaction
$conn->commit();
$success = "Order updated successfully!";
// Refresh order data
// Fetch updated 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) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$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();
} catch (Exception $e) {
// Rollback transaction
$conn->rollback();
$error = "Error updating order: " . sanitize_input($e->getMessage());
}
}
// Now include the header AFTER form handling
require_once '../../includes/header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Order #<?= htmlspecialchars($order_id) ?> - 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 */
}
/* Responsive Table */
@media (max-width: 768px) {
table {
min-width: 600px;
}
}
</style>
<!-- Additional JavaScript for dynamic product addition, form enhancements, and payment functionality -->
<script>
let productCount = <?= isset($product_ids) ? count($product_ids) : 1; ?>;
function addOrderItemRow() {
const orderItemsContainer = document.getElementById('order-items-container');
const itemCount = orderItemsContainer.children.length + 1;
const orderItemRow = document.createElement('div');
orderItemRow.className = 'order-item-row border p-4 mb-4 shadow-sm rounded-lg';
orderItemRow.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_${itemCount}">Product <span class="text-red-500">*</span></label>
<select name="new_product_id[]" id="new_product_id_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" required>
<option value="">Select Product</option>
<?php
// Reset the products_result pointer
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($product['id']) ?>">
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="new_quantity_${itemCount}">Quantity <span class="text-red-500">*</span></label>
<input type="number" name="new_quantity[]" id="new_quantity_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm 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_${itemCount}">Packaging Preferences</label>
<input type="text" name="new_packaging_preferences[]" id="new_packaging_preferences_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm 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="discount_${itemCount}">Apply Discount</label>
<div class="flex items-center mt-1">
<input type="checkbox" name="apply_discount[]" id="discount_checkbox_${itemCount}" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, ${itemCount})">
<label for="discount_checkbox_${itemCount}" class="ml-2 block text-sm text-gray-700">
Yes
</label>
</div>
<div id="discount_fields_${itemCount}" class="discount-fields mt-2" style="display: none;">
<label class="block text-sm font-medium text-gray-700" for="discount_percentage_${itemCount}">Discount Percentage (%) <span class="text-red-500">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
<label class="block text-sm font-medium text-gray-700 mt-2" for="discount_reason_${itemCount}">Discount Reason <span class="text-red-500">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount">
</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="removeOrderItemRow(this)">
<i class="bi bi-trash-fill"></i> Remove Product
</button>
</div>
`;
orderItemsContainer.appendChild(orderItemRow);
}
function removeOrderItemRow(button) {
const orderItemRow = button.closest('.order-item-row');
orderItemRow.remove();
}
// Toggle discount fields based on checkbox
function toggleDiscountFields(checkbox, count) {
const discountFields = document.getElementById(`discount_fields_${count}`);
if (checkbox.checked) {
discountFields.style.display = 'block';
} else {
discountFields.style.display = 'none';
// Clear discount inputs
discountFields.querySelectorAll('input').forEach(input => input.value = '');
}
}
// Toggle delivery fee field based on free shipping checkbox
function toggleDeliveryFee() {
const freeShippingCheckbox = document.getElementById('free_shipping');
const deliveryFeeInput = document.getElementById('delivery_fee');
if (freeShippingCheckbox.checked) {
deliveryFeeInput.value = '0.00';
deliveryFeeInput.disabled = true;
} else {
deliveryFeeInput.disabled = false;
}
}
// Auto-generate Customer Name based on Contact Number
function autoGenerateCustomerName() {
const contactInput = document.getElementById('contact');
const customerNameInput = document.getElementById('customer_name');
// Extract digits from contact number
const digits = contactInput.value.replace(/\D/g, '');
if (digits.length > 0) {
customerNameInput.value = 'Order_' + digits;
} else {
customerNameInput.value = '';
}
}
// Initialize on DOM content loaded
document.addEventListener('DOMContentLoaded', function() {
// Initialize delivery fee toggle
toggleDeliveryFee();
document.getElementById('free_shipping').addEventListener('change', toggleDeliveryFee);
// Initialize Customer Name auto-generation
document.getElementById('contact').addEventListener('input', autoGenerateCustomerName);
// Initialize Flatpickr for date and datetime fields
flatpickr("#delivery_datetime", {
enableTime: true,
dateFormat: "Y-m-d\\TH:i",
});
flatpickr("#delivery_date", {
dateFormat: "Y-m-d",
});
});
</script>
</head>
<body class="bg-gray-100">
<!-- Main Container -->
<main class="container-custom">
<h3 class="mb-5">Edit Order #<?= htmlspecialchars($order_id) ?></h3>
<!-- Display Success or Error Messages -->
<?php if (!empty($success)): ?>
<div class="alert alert-custom alert-success-custom flex items-center">
<i class="bi bi-check-circle-fill mr-2"></i>
<span><?= htmlspecialchars($success) ?></span>
</div>
<?php endif; ?>
<?php if (!empty($error)): ?>
<div class="alert alert-custom alert-danger-custom flex items-center">
<i class="bi bi-exclamation-triangle-fill mr-2"></i>
<span><?= htmlspecialchars($error) ?></span>
</div>
<?php endif; ?>
<!-- Edit Order Form -->
<form method="POST" action="">
<!-- Customer Details -->
<div class="mb-6">
<h2 class="text-xl font-semibold text-gray-800 mb-4">Customer Details</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="form-label" for="customer_name">Customer Name <span class="text-red-500">*</span></label>
<input type="text" id="customer_name" name="customer_name" class="form-control"
value="<?= htmlspecialchars(isset($_POST['customer_name']) ? $_POST['customer_name'] : $order['customer_name']) ?>"
readonly placeholder="Auto-generated based on contact number" required>
</div>
<div>
<label class="form-label" for="contact">Contact</label>
<input type="text" id="contact" name="contact" class="form-control"
value="<?= htmlspecialchars(isset($_POST['contact']) ? $_POST['contact'] : $order['customer_contact']) ?>"
placeholder="Enter contact number without country code">
</div>
</div>
<div class="mt-4">
<label class="form-label" for="delivery_address">Delivery Address</label>
<textarea id="delivery_address" name="delivery_address" class="form-control" rows="3" placeholder="Enter delivery address"><?= htmlspecialchars(isset($_POST['delivery_address']) ? $_POST['delivery_address'] : $order['delivery_address']) ?></textarea>
</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="form-label">Order Priority <span class="text-red-500">*</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) ?>" class="form-radio text-teal-600" <?= $checked ?> required>
<span class="ml-2"><?= htmlspecialchars($priority_option) ?></span>
</label>
<?php endforeach; ?>
</div>
</div>
<!-- Order Status and Payment Status -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="form-label" for="status">Status <span class="text-red-500">*</span></label>
<select name="status" id="status" class="form-control" required>
<option value="">Select Status</option>
<option value="Pending" <?= (isset($_POST['status']) ? $_POST['status'] : $order['status']) == 'Pending' ? 'selected' : '' ?>>Pending</option>
<option value="In Progress" <?= (isset($_POST['status']) ? $_POST['status'] : $order['status']) == 'In Progress' ? 'selected' : '' ?>>In Progress</option>
<option value="Completed" <?= (isset($_POST['status']) ? $_POST['status'] : $order['status']) == 'Completed' ? 'selected' : '' ?>>Completed</option>
<option value="Delivered" <?= (isset($_POST['status']) ? $_POST['status'] : $order['status']) == 'Delivered' ? 'selected' : '' ?>>Delivered</option>
</select>
</div>
<div class="flex items-center">
<input type="checkbox" id="is_paid" name="is_paid" class="form-checkbox h-5 w-5 text-teal-600" <?= (isset($_POST['is_paid']) ? $_POST['is_paid'] : $order['is_paid']) ? 'checked' : '' ?>>
<label for="is_paid" class="ml-2 block text-sm text-gray-700">
<?= (isset($_POST['is_paid']) ? $_POST['is_paid'] : $order['is_paid']) ? 'Mark as Paid' : 'Mark as Not Paid' ?>
</label>
</div>
</div>
<!-- Delivery Date and Time -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
<div>
<label class="form-label" for="delivery_datetime">Delivery Date and Time</label>
<input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="form-control"
value="<?= htmlspecialchars(isset($_POST['delivery_datetime']) ? $_POST['delivery_datetime'] : ($order['delivery_datetime'] ? date('Y-m-d\TH:i', strtotime($order['delivery_datetime'])) : '')) ?>">
</div>
<div>
<label class="form-label" for="delivery_date">Delivery Date</label>
<input type="date" id="delivery_date" name="delivery_date" class="form-control"
value="<?= htmlspecialchars(isset($_POST['delivery_date']) ? $_POST['delivery_date'] : ($order['delivery_date'] ? date('Y-m-d', strtotime($order['delivery_date'])) : '')) ?>">
</div>
</div>
<!-- Delivery Fee -->
<div class="mt-4">
<label class="form-label" for="delivery_fee">Delivery Fee (KWD) <span class="text-red-500" id="delivery_fee_required">*</span></label>
<input type="number" step="0.01" id="delivery_fee" name="delivery_fee" class="form-control" min="0"
value="<?= isset($_POST['delivery_fee']) ? htmlspecialchars($_POST['delivery_fee']) : number_format($order['delivery_fee'], 2, '.', '') ?>"
<?= isset($_POST['free_shipping']) || $order['free_shipping'] ? 'disabled' : 'required' ?>>
</div>
<!-- Payment Status -->
<div class="mt-4 flex items-center">
<input type="checkbox" id="is_paid_status" name="is_paid" class="form-checkbox h-5 w-5 text-teal-600" <?= (isset($_POST['is_paid']) ? $_POST['is_paid'] : $order['is_paid']) ? 'checked' : '' ?>>
<label for="is_paid_status" class="ml-2 block text-sm text-gray-700">
<?= (isset($_POST['is_paid']) ? $_POST['is_paid'] : $order['is_paid']) ? 'Mark as Paid' : 'Mark as Not Paid' ?>
</label>
</div>
<!-- Existing Order Items -->
<div class="mb-6">
<h5 class="mb-4">Existing Order Items</h5>
<div id="existing-order-items-container">
<?php foreach ($order_items as $item): ?>
<div class="order-item-row border p-4 mb-4 rounded-lg shadow-sm">
<input type="hidden" name="existing_item_id[]" value="<?= htmlspecialchars($item['id']) ?>">
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div>
<label class="form-label" for="product_id_<?= htmlspecialchars($item['id']) ?>">Product <span class="text-red-500">*</span></label>
<select name="product_id[]" id="product_id_<?= htmlspecialchars($item['id']) ?>" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" required>
<option value="">Select Product</option>
<?php
// Reset the products_result pointer
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($product['id']) ?>" <?= ($product['id'] == $item['product_id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div>
<label class="form-label" for="quantity_<?= htmlspecialchars($item['id']) ?>">Quantity <span class="text-red-500">*</span></label>
<input type="number" name="quantity[]" id="quantity_<?= htmlspecialchars($item['id']) ?>" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" min="1" value="<?= htmlspecialchars($item['quantity']) ?>" required>
</div>
<div>
<label class="form-label" for="packaging_preferences_<?= htmlspecialchars($item['id']) ?>">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_<?= htmlspecialchars($item['id']) ?>" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($item['packaging_preferences']) ?>">
</div>
<div>
<label class="form-label" for="discount_percentage_<?= htmlspecialchars($item['id']) ?>">Discount (%)</label>
<input type="number" name="discount_percentage[]" id="discount_percentage_<?= htmlspecialchars($item['id']) ?>" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" value="<?= htmlspecialchars($item['discount_percentage']) ?>">
</div>
</div>
<div class="mt-3">
<label class="form-label" for="discount_reason_<?= htmlspecialchars($item['id']) ?>">Discount Reason</label>
<input type="text" name="discount_reason[]" id="discount_reason_<?= htmlspecialchars($item['id']) ?>" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" value="<?= htmlspecialchars($item['discount_reason']) ?>">
</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="removeExistingOrderItemRow(this)">
✕ Remove Product
</button>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<hr class="my-6">
<!-- Add New Order Items -->
<div class="mb-6">
<h5 class="mb-4">Add New Order Items</h5>
<div id="order-items-container">
<!-- New Order Item 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" onclick="addOrderItemRow()">
<i class="bi bi-plus-circle-fill"></i> Add Another Product
</button>
</div>
<!-- Submit Buttons -->
<div class="flex justify-between">
<button type="submit" class="btn-primary-custom">Update Order</button>
<a href="view_orders.php" class="btn-secondary-custom flex items-center gap-2">
<i class="bi bi-arrow-left-circle"></i> Cancel
</a>
</div>
</form>
</div>
<!-- Footer -->
<div class="footer mt-12">
© <?= 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"
});
flatpickr("#delivery_date", {
dateFormat: "Y-m-d",
minDate: "today"
});
</script>
<!-- Bootstrap Tooltip Initialization (if using tooltips in future) -->
<script>
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>) and this info database (-- phpMyAdmin SQL Dump
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 14, 2024 at 09:26 PM
-- Server version: 10.11.9-MariaDB
-- PHP Version: 7.2.34
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT /;
/ !40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS /;
/ !40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION /;
/ !40101 SET NAMES utf8mb4 */;
--
-- Database: u406552082_kaakalia
--
-- Table structure for table ads CREATE TABLE ads (
id int(11) NOT NULL,
user_id int(11) NOT NULL,
name varchar(255) NOT NULL,
ad_type enum('Post','Story') NOT NULL,
related_id int(11) NOT NULL,
budget decimal(10,2) NOT NULL,
total_spent decimal(10,2) DEFAULT 0.00,
start_date date NOT NULL,
end_date date NOT NULL,
status enum('Active','Paused','Completed') DEFAULT 'Active',
created_at datetime DEFAULT current_timestamp(),
updated_at datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table ad_spend_logs CREATE TABLE ad_spend_logs (
id int(11) NOT NULL,
ad_id int(11) NOT NULL,
amount decimal(10,2) NOT NULL,
spend_date datetime DEFAULT current_timestamp(),
description varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table customers CREATE TABLE customers (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
contact varchar(50) DEFAULT NULL,
delivery_address text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table drivers CREATE TABLE drivers (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
number varchar(15) NOT NULL,
is_star tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table notifications CREATE TABLE notifications (
id int(11) NOT NULL,
user_id int(11) NOT NULL,
type enum('order','post','plan','note','ad') NOT NULL,
message varchar(255) NOT NULL,
link varchar(255) NOT NULL,
created_at datetime DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table orders CREATE TABLE orders (
id int(11) NOT NULL,
customer_id int(11) NOT NULL,
status enum('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
priority enum('Normal','Important','Quick') DEFAULT 'Normal',
order_date datetime DEFAULT current_timestamp(),
delivery_datetime datetime DEFAULT NULL,
delivery_date date DEFAULT NULL,
delivery_fee decimal(10,2) NOT NULL DEFAULT 0.00,
free_shipping tinyint(1) NOT NULL DEFAULT 0,
is_paid tinyint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table order_items CREATE TABLE order_items (
id int(11) NOT NULL,
order_id int(11) NOT NULL,
product_id int(11) NOT NULL,
quantity int(11) NOT NULL DEFAULT 1,
packaging_preferences varchar(255) DEFAULT NULL,
discount_percentage decimal(5,2) DEFAULT 0.00,
discount_reason varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table products CREATE TABLE products (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
size varchar(50) DEFAULT NULL,
price decimal(10,2) NOT NULL,
category varchar(50) DEFAULT NULL,
thumbnail varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table users CREATE TABLE users (
id int(11) NOT NULL,
username varchar(50) NOT NULL,
email varchar(100) DEFAULT NULL,
password varchar(255) NOT NULL,
role enum('admin','staff') NOT NULL,
profile_image varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table workspace_notes CREATE TABLE workspace_notes (
id int(11) NOT NULL,
user_id int(11) NOT NULL,
title varchar(255) NOT NULL,
content text NOT NULL,
created_at datetime DEFAULT current_timestamp(),
updated_at datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table workspace_plans CREATE TABLE workspace_plans (
id int(11) NOT NULL,
user_id int(11) NOT NULL,
title varchar(255) NOT NULL,
description text DEFAULT NULL,
audio_path varchar(255) DEFAULT NULL,
due_date datetime DEFAULT NULL,
status enum('Not Started','In Progress','Completed') DEFAULT 'Not Started',
created_at datetime DEFAULT current_timestamp(),
updated_at datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
priority enum('Normal','Important','Critical') NOT NULL DEFAULT 'Normal'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table workspace_posts CREATE TABLE workspace_posts (
id int(11) NOT NULL,
user_id int(11) NOT NULL,
platform enum('Instagram','Facebook','Twitter','Other') NOT NULL,
content text NOT NULL,
media_url varchar(255) DEFAULT NULL,
scheduled_datetime datetime DEFAULT NULL,
status enum('Scheduled','Posted','Failed') DEFAULT 'Scheduled',
created_at datetime DEFAULT current_timestamp(),
updated_at datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
type enum('Post','Story') DEFAULT 'Post'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Indexes for dumped tables
--
-- Indexes for table ads ALTER TABLE ads
ADD PRIMARY KEY (id),
ADD KEY user_id (user_id),
ADD KEY related_id (related_id);
--
-- Indexes for table ad_spend_logs ALTER TABLE ad_spend_logs
ADD PRIMARY KEY (id),
ADD KEY ad_id (ad_id);
--
-- Indexes for table customers ALTER TABLE customers
ADD PRIMARY KEY (id);
--
-- Indexes for table drivers ALTER TABLE drivers
ADD PRIMARY KEY (id);
--
-- Indexes for table notifications ALTER TABLE notifications
ADD PRIMARY KEY (id),
ADD KEY user_id (user_id),
ADD KEY created_at (created_at);
--
-- Indexes for table orders ALTER TABLE orders
ADD PRIMARY KEY (id),
ADD KEY customer_id (customer_id),
ADD KEY idx_orders_customer_id (customer_id);
--
-- Indexes for table order_items ALTER TABLE order_items
ADD PRIMARY KEY (id),
ADD KEY order_id (order_id),
ADD KEY product_id (product_id),
ADD KEY idx_order_items_order_id (order_id),
ADD KEY idx_order_items_product_id (product_id);
--
-- Indexes for table products ALTER TABLE products
ADD PRIMARY KEY (id);
--
-- Indexes for table users ALTER TABLE users
ADD PRIMARY KEY (id),
ADD UNIQUE KEY username (username);
--
-- Indexes for table workspace_notes ALTER TABLE workspace_notes
ADD PRIMARY KEY (id),
ADD KEY user_id (user_id);
--
-- Indexes for table workspace_plans ALTER TABLE workspace_plans
ADD PRIMARY KEY (id),
ADD KEY user_id (user_id);
--
-- Indexes for table workspace_posts ALTER TABLE workspace_posts
ADD PRIMARY KEY (id),
ADD KEY user_id (user_id);
--
-- AUTO_INCREMENT for dumped tables
--
-- AUTO_INCREMENT for table ads ALTER TABLE ads
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table ad_spend_logs ALTER TABLE ad_spend_logs
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table customers ALTER TABLE customers
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table drivers ALTER TABLE drivers
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table notifications ALTER TABLE notifications
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table orders ALTER TABLE orders
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table order_items ALTER TABLE order_items
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table products ALTER TABLE products
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table users ALTER TABLE users
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table workspace_notes ALTER TABLE workspace_notes
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table workspace_plans ALTER TABLE workspace_plans
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table workspace_posts ALTER TABLE workspace_posts
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
-- Constraints for table ads ALTER TABLE ads
ADD CONSTRAINT fk_ads_related_id FOREIGN KEY (related_id) REFERENCES workspace_posts (id) ON DELETE CASCADE,
ADD CONSTRAINT fk_ads_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
--
-- Constraints for table ad_spend_logs ALTER TABLE ad_spend_logs
ADD CONSTRAINT fk_ad_spend_logs_ad_id FOREIGN KEY (ad_id) REFERENCES ads (id) ON DELETE CASCADE;
--
-- Constraints for table notifications ALTER TABLE notifications
ADD CONSTRAINT notifications_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
--
-- Constraints for table orders ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer_id FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT orders_ibfk_1 FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE;
--
-- Constraints for table order_items ALTER TABLE order_items
ADD CONSTRAINT fk_order_items_order_id FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT fk_order_items_product_id FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT order_items_ibfk_1 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE,
ADD CONSTRAINT order_items_ibfk_2 FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE;
--
-- Constraints for table workspace_notes ALTER TABLE workspace_notes
ADD CONSTRAINT fk_workspace_notes_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
--
-- Constraints for table workspace_plans ALTER TABLE workspace_plans
ADD CONSTRAINT fk_workspace_plans_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
--
-- Constraints for table workspace_posts ALTER TABLE workspace_posts
ADD CONSTRAINT fk_workspace_posts_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT /;
/ !40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS /;
/ !40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;)
Certainly! I'll help you fix and improve your PHP script for editing orders. Below are the key issues identified and their respective fixes:
Duplicated is_paid Checkbox:
Issue: The form contains two is_paid checkboxes (is_paid and is_paid_status) both using the same name attribute, which can lead to conflicts and unexpected behavior.
Fix: Remove the redundant is_paid_status checkbox to ensure there's only one is_paid field in the form.
Undefined JavaScript Function:
Issue: The existing order items have a removeExistingOrderItemRow(this) function call, but this function is not defined in the JavaScript. Instead, the correct function removeOrderItemRow(this) exists.
Fix: Update the function call in the existing order items to use removeOrderItemRow(this).
Incorrect require_once Path for header.php:
Issue: The inclusion of header.php uses a relative path without leveraging __DIR__, which can cause issues if the script's location changes.
Fix: Use __DIR__ to create an absolute path for including header.php.
Consistent Handling of Discount Fields:
Issue: While new order items have an apply_discount[] checkbox, the server-side PHP doesn't handle this input, potentially leading to inconsistencies.
Fix: Modify the PHP to check for apply_discount[] and handle discount fields accordingly.
Miscellaneous Enhancements:
Ensure all user inputs are properly sanitized.
Maintain consistent use of JavaScript for dynamic elements.
Ensure form fields retain user input after validation errors.
Below is the corrected and improved PHP script incorporating all the fixes and enhancements:
<?php
// public/orders/edit_order.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1); // Set to 1 for debugging, 0 in production
ini_set('display_startup_errors', 1); // Set to 1 for debugging, 0 in production
error_reporting(E_ALL);
// Start output buffering to prevent "headers already sent" errors
ob_start();
// Include authentication, database connection, and functions
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
require_once __DIR__ . '/../../includes/functions.php'; // Include the functions.php for sanitize_input()
// Function to sanitize input
function sanitize_input($input) {
return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}
// Initialize success and error variables
$success = '';
$error = '';
// Retrieve and sanitize the order ID from GET parameters
$order_id = isset($_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 Order ID");
exit();
}
// Fetch order details along with customer information and is_paid status
$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("Prepare statement failed: " . $conn->error);
}
$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 Not Found");
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("Prepare statement failed: " . $conn->error);
}
$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();
// Fetch products for selection
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);
if (!$products_result) {
die("Products query failed: " . $conn->error);
}
// 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 = sanitize_input($_POST['contact']);
$delivery_address = sanitize_input($_POST['delivery_address']);
$status = sanitize_input($_POST['status']);
$priority = sanitize_input($_POST['priority'] ?? 'Normal'); // Initializes $priority
$delivery_datetime = isset($_POST['delivery_datetime']) && !empty($_POST['delivery_datetime']) ? sanitize_input($_POST['delivery_datetime']) : null;
$delivery_date = isset($_POST['delivery_date']) && !empty($_POST['delivery_date']) ? sanitize_input($_POST['delivery_date']) : null;
// New fields based on database schema
$delivery_fee = isset($_POST['delivery_fee']) && is_numeric($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00;
$free_shipping = isset($_POST['free_shipping']) ? 1 : 0;
$is_paid = isset($_POST['is_paid']) ? 1 : 0; // New field
// If free shipping is selected, set delivery_fee to 0.00
if ($free_shipping) {
$delivery_fee = 0.00;
}
// Handle existing order items
$existing_item_ids = isset($_POST['existing_item_id']) ? $_POST['existing_item_id'] : [];
$product_ids = isset($_POST['product_id']) ? $_POST['product_id'] : [];
$quantities = isset($_POST['quantity']) ? $_POST['quantity'] : [];
$packaging_preferences = isset($_POST['packaging_preferences']) ? $_POST['packaging_preferences'] : [];
$discount_percentages = isset($_POST['discount_percentage']) ? $_POST['discount_percentage'] : [];
$discount_reasons = isset($_POST['discount_reason']) ? $_POST['discount_reason'] : [];
// Handle new order items
$new_product_ids = isset($_POST['new_product_id']) ? $_POST['new_product_id'] : [];
$new_quantities = isset($_POST['new_quantity']) ? $_POST['new_quantity'] : [];
$new_packaging_preferences = isset($_POST['new_packaging_preferences']) ? $_POST['new_packaging_preferences'] : [];
$new_discount_percentages = isset($_POST['new_discount_percentage']) ? $_POST['new_discount_percentage'] : [];
$new_discount_reasons = isset($_POST['new_discount_reason']) ? $_POST['new_discount_reason'] : [];
$apply_discounts = isset($_POST['apply_discount']) ? $_POST['apply_discount'] : [];
// Basic validation
if (empty($customer_name)) {
$error = "Customer name is required.";
} elseif (empty($status)) {
$error = "Order status is required.";
} elseif (empty($priority)) {
$error = "Order priority is required.";
} elseif ((empty($existing_item_ids) && empty($new_product_ids))) {
$error = "At least one product must be selected.";
} else {
// Validate each existing product entry
foreach ($existing_item_ids as $index => $item_id) {
if (empty($product_ids[$index])) {
$error = "Product selection is required for all existing items.";
break;
}
if (!isset($quantities[$index]) || intval($quantities[$index]) <= 0) {
$error = "Quantity must be at least 1 for all existing items.";
break;
}
if ($discount_percentages[$index] !== '' && (floatval($discount_percentages[$index]) < 0 || floatval($discount_percentages[$index]) > 100)) {
$error = "Discount percentage must be between 0 and 100.";
break;
}
}
// Validate new product entries
foreach ($new_product_ids as $index => $pid) {
if (!empty($pid)) {
if (intval($new_quantities[$index]) <= 0) {
$error = "Quantity must be at least 1 for all new items.";
break;
}
// Check if discount is applied for this new item
$is_discount_applied = isset($apply_discounts[$index]);
if ($is_discount_applied) {
if ($new_discount_percentages[$index] === '') {
$error = "Discount percentage is required when discount is applied.";
break;
}
if (floatval($new_discount_percentages[$index]) < 0 || floatval($new_discount_percentages[$index]) > 100) {
$error = "Discount percentage must be between 0 and 100 for all new items.";
break;
}
if (empty($new_discount_reasons[$index])) {
$error = "Discount reason is required when discount is applied.";
break;
}
}
}
}
if ($delivery_datetime && strtotime(str_replace('T', ' ', $delivery_datetime)) < strtotime(date('Y-m-d H:i'))) {
$error = "Delivery date and time cannot be in the past.";
}
if ($delivery_date && strtotime($delivery_date) < strtotime(date('Y-m-d'))) {
$error = "Delivery date cannot be in the past.";
}
}
if (empty($error)) {
// Start transaction
$conn->begin_transaction();
try {
// Update customer details
$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, $contact, $delivery_address, $order['customer_id']);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$stmt->close();
// Update orders table with new fields including is_paid
$stmt = $conn->prepare("UPDATE orders SET status = ?, priority = ?, delivery_datetime = ?, delivery_date = ?, delivery_fee = ?, free_shipping = ?, is_paid = ? WHERE id = ?");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("ssssdiii", $status, $priority, $delivery_datetime, $delivery_date, $delivery_fee, $free_shipping, $is_paid, $order_id);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$stmt->close();
// Update existing order items
foreach ($existing_item_ids as $index => $item_id) {
$item_id = intval($item_id);
$pid = intval($product_ids[$index]);
$qty = intval($quantities[$index]);
$pack_pref = sanitize_input($packaging_preferences[$index]);
$discount_pct = $discount_percentages[$index] !== '' ? floatval($discount_percentages[$index]) : 0.00;
$discount_rsn = sanitize_input($discount_reasons[$index]);
$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("iiisdi", $pid, $qty, $pack_pref, $discount_pct, $discount_rsn, $item_id);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$stmt->close();
}
// Insert new order items
$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);
}
foreach ($new_product_ids as $index => $new_pid) {
if (!empty($new_pid)) {
$new_pid = intval($new_pid);
$new_qty = intval($new_quantities[$index]);
$new_pack_pref = sanitize_input($new_packaging_preferences[$index]);
// Check if discount is applied for this item
$is_discount_applied = isset($apply_discounts[$index]);
$new_discount_pct = $is_discount_applied && $new_discount_percentages[$index] !== '' ? floatval($new_discount_percentages[$index]) : 0.00;
$new_discount_rsn = $is_discount_applied ? sanitize_input($new_discount_reasons[$index]) : null;
$stmt->bind_param("iiisds", $order_id, $new_pid, $new_qty, $new_pack_pref, $new_discount_pct, $new_discount_rsn);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
}
}
$stmt->close();
// Commit transaction
$conn->commit();
$success = "Order updated successfully!";
// Refresh order data
// Fetch updated 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) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$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();
} catch (Exception $e) {
// Rollback transaction
$conn->rollback();
$error = "Error updating order: " . sanitize_input($e->getMessage());
}
}
// Now include the header AFTER form handling
require_once __DIR__ . '/../../includes/header.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Order #<?= htmlspecialchars($order_id) ?> - 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 */
}
/* Responsive Table */
@media (max-width: 768px) {
table {
min-width: 600px;
}
}
</style>
<!-- Additional JavaScript for dynamic product addition, form enhancements, and payment functionality -->
<script>
let productCount = <?= count($order_items) + 1 ?>;
function addOrderItemRow() {
const orderItemsContainer = document.getElementById('order-items-container');
const itemCount = productCount++;
const orderItemRow = document.createElement('div');
orderItemRow.className = 'order-item-row border p-4 mb-4 shadow-sm rounded-lg';
orderItemRow.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_${itemCount}">Product <span class="text-red-500">*</span></label>
<select name="new_product_id[]" id="new_product_id_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" required>
<option value="">Select Product</option>
<?php
// Reset the products_result pointer
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($product['id']) ?>">
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="new_quantity_${itemCount}">Quantity <span class="text-red-500">*</span></label>
<input type="number" name="new_quantity[]" id="new_quantity_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm 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_${itemCount}">Packaging Preferences</label>
<input type="text" name="new_packaging_preferences[]" id="new_packaging_preferences_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm 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="discount_${itemCount}">Apply Discount</label>
<div class="flex items-center mt-1">
<input type="checkbox" name="apply_discount[]" id="discount_checkbox_${itemCount}" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, ${itemCount})">
<label for="discount_checkbox_${itemCount}" class="ml-2 block text-sm text-gray-700">
Yes
</label>
</div>
<div id="discount_fields_${itemCount}" class="discount-fields mt-2" style="display: none;">
<label class="block text-sm font-medium text-gray-700" for="new_discount_percentage_${itemCount}">Discount Percentage (%) <span class="text-red-500">*</span></label>
<input type="number" name="new_discount_percentage[]" id="new_discount_percentage_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
<label class="block text-sm font-medium text-gray-700 mt-2" for="new_discount_reason_${itemCount}">Discount Reason <span class="text-red-500">*</span></label>
<input type="text" name="new_discount_reason[]" id="new_discount_reason_${itemCount}" class="form-control mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount">
</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="removeOrderItemRow(this)">
<i class="bi bi-trash-fill"></i> Remove Product
</button>
</div>
`;
orderItemsContainer.appendChild(orderItemRow);
}
function removeOrderItemRow(button) {
const orderItemRow = button.closest('.order-item-row');
orderItemRow.remove();
}
// Toggle discount fields based on checkbox
function toggleDiscountFields(checkbox, count) {
const discountFields = document.getElementById(`discount_fields_${count}`);
if (checkbox.checked) {
discountFields.style.display = 'block';
} else {
discountFields.style.display = 'none';
// Clear discount inputs
discountFields.querySelectorAll('input').forEach(input => input.value = '');
}
}
// Toggle delivery fee field based on free shipping checkbox
function toggleDeliveryFee() {
const freeShippingCheckbox = document.getElementById('free_shipping');
const deliveryFeeInput = document.getElementById('delivery_fee');
if (freeShippingCheckbox.checked) {
deliveryFeeInput.value = '0.00';
deliveryFeeInput.disabled = true;
} else {
deliveryFeeInput.disabled = false;
}
}
// Auto-generate Customer Name based on Contact Number
function autoGenerateCustomerName() {
const contactInput = document.getElementById('contact');
const customerNameInput = document.getElementById('customer_name');
// Extract digits from contact number
const digits = contactInput.value.replace(/\D/g, '');
if (digits.length > 0) {
customerNameInput.value = 'Order_' + digits;
} else {
customerNameInput.value = '';
}
}
// Initialize on DOM content loaded
document.addEventListener('DOMContentLoaded', function() {
// Initialize delivery fee toggle
toggleDeliveryFee();
document.getElementById('free_shipping').addEventListener('change', toggleDeliveryFee);
// Initialize Customer Name auto-generation
document.getElementById('contact').addEventListener('input', autoGenerateCustomerName);
// Initialize Flatpickr for date and datetime fields
flatpickr("#delivery_datetime", {
enableTime: true,
dateFormat: "Y-m-d\\TH:i",
});
flatpickr("#delivery_date", {
dateFormat: "Y-m-d",
});
});
</script>
</head>
<body class="bg-gray-100">
<!-- Main Container -->
<main class="container-custom p-6">
<h3 class="mb-5 text-2xl font-bold">Edit Order #<?= htmlspecialchars($order_id) ?></h3>
<!-- Display Success or Error Messages -->
<?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 text-xl"></i>
<span><?= htmlspecialchars($success) ?></span>
</div>
<?php endif; ?>
<?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 text-xl"></i>
<span><?= htmlspecialchars($error) ?></span>
</div>
<?php endif; ?>
<!-- Edit Order Form -->
<form method="POST" action="">
<!-- Customer Details -->
<div class="mb-6">
<h2 class="text-xl font-semibold text-gray-800 mb-4">Customer Details</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="block text-sm font-medium text-gray-700" for="customer_name">Customer Name <span class="text-red-500">*</span></label>
<input type="text" id="customer_name" name="customer_name" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500"
value="<?= htmlspecialchars(isset($_POST['customer_name']) ? $_POST['customer_name'] : $order['customer_name']) ?>"
readonly placeholder="Auto-generated based on contact number" required>
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="contact">Contact</label>
<input type="text" id="contact" name="contact" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500"
value="<?= htmlspecialchars(isset($_POST['contact']) ? $_POST['contact'] : $order['customer_contact']) ?>"
placeholder="Enter contact number without country code">
</div>
</div>
<div class="mt-4">
<label class="block text-sm font-medium text-gray-700" for="delivery_address">Delivery Address</label>
<textarea id="delivery_address" name="delivery_address" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" rows="3" placeholder="Enter delivery address"><?= htmlspecialchars(isset($_POST['delivery_address']) ? $_POST['delivery_address'] : $order['delivery_address']) ?></textarea>
</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">Order Priority <span class="text-red-500">*</span></label>
<div class="flex space-x-4 mt-2">
<?php
$priorities = ['Normal', 'Important', 'Quick'];
foreach ($priorities as $priority_option):
$checked = (isset($_POST['priority']) ? $_POST['priority'] : $order['priority']) == $priority_option ? 'checked' : '';
?>
<label class="inline-flex items-center">
<input type="radio" name="priority" value="<?= htmlspecialchars($priority_option) ?>" class="form-radio text-teal-600" <?= $checked ?> required>
<span class="ml-2"><?= htmlspecialchars($priority_option) ?></span>
</label>
<?php endforeach; ?>
</div>
</div>
<!-- Order Status -->
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700" for="status">Status <span class="text-red-500">*</span></label>
<select name="status" id="status" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" required>
<option value="">Select Status</option>
<?php
$statuses = ['Pending', 'In Progress', 'Completed', 'Delivered'];
foreach ($statuses as $status_option):
$selected = (isset($_POST['status']) ? $_POST['status'] : $order['status']) == $status_option ? 'selected' : '';
?>
<option value="<?= htmlspecialchars($status_option) ?>" <?= $selected ?>><?= htmlspecialchars($status_option) ?></option>
<?php endforeach; ?>
</select>
</div>
<!-- Payment Status -->
<div class="flex items-center mb-4">
<input type="checkbox" id="is_paid" name="is_paid" class="form-checkbox h-5 w-5 text-teal-600" <?= (isset($_POST['is_paid']) ? $_POST['is_paid'] : $order['is_paid']) ? 'checked' : '' ?>>
<label for="is_paid" class="ml-2 block text-sm text-gray-700">
<?= (isset($_POST['is_paid']) ? $_POST['is_paid'] : $order['is_paid']) ? 'Mark as Paid' : 'Mark as Not Paid' ?>
</label>
</div>
<!-- Delivery Date and Time -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label class="block text-sm font-medium text-gray-700" for="delivery_datetime">Delivery Date and Time</label>
<input type="datetime-local" id="delivery_datetime" name="delivery_datetime" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500"
value="<?= htmlspecialchars(isset($_POST['delivery_datetime']) ? $_POST['delivery_datetime'] : ($order['delivery_datetime'] ? date('Y-m-d\TH:i', strtotime($order['delivery_datetime'])) : '')) ?>">
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="delivery_date">Delivery Date</label>
<input type="date" id="delivery_date" name="delivery_date" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500"
value="<?= htmlspecialchars(isset($_POST['delivery_date']) ? $_POST['delivery_date'] : ($order['delivery_date'] ? date('Y-m-d', strtotime($order['delivery_date'])) : '')) ?>">
</div>
</div>
<!-- Delivery Fee -->
<div class="mt-4">
<label class="block text-sm font-medium text-gray-700" for="delivery_fee">Delivery Fee (KWD) <span class="text-red-500" id="delivery_fee_required">*</span></label>
<input type="number" step="0.01" id="delivery_fee" name="delivery_fee" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" min="0"
value="<?= isset($_POST['delivery_fee']) ? htmlspecialchars($_POST['delivery_fee']) : number_format($order['delivery_fee'], 2, '.', '') ?>"
<?= (isset($_POST['free_shipping']) || $order['free_shipping']) ? 'disabled' : 'required' ?>>
</div>
<!-- Existing Order Items -->
<div class="mb-6">
<h5 class="text-lg font-semibold text-gray-800 mb-4">Existing Order Items</h5>
<div id="existing-order-items-container">
<?php foreach ($order_items as $item): ?>
<div class="order-item-row border p-4 mb-4 rounded-lg shadow-sm">
<input type="hidden" name="existing_item_id[]" value="<?= htmlspecialchars($item['id']) ?>">
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700" for="product_id_<?= htmlspecialchars($item['id']) ?>">Product <span class="text-red-500">*</span></label>
<select name="product_id[]" id="product_id_<?= htmlspecialchars($item['id']) ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" required>
<option value="">Select Product</option>
<?php
// Reset the products_result pointer
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($product['id']) ?>" <?= ($product['id'] == $item['product_id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="quantity_<?= htmlspecialchars($item['id']) ?>">Quantity <span class="text-red-500">*</span></label>
<input type="number" name="quantity[]" id="quantity_<?= htmlspecialchars($item['id']) ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" min="1" value="<?= htmlspecialchars($item['quantity']) ?>" required>
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="packaging_preferences_<?= htmlspecialchars($item['id']) ?>">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_<?= htmlspecialchars($item['id']) ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap" value="<?= htmlspecialchars($item['packaging_preferences']) ?>">
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="discount_percentage_<?= htmlspecialchars($item['id']) ?>">Discount (%)</label>
<input type="number" name="discount_percentage[]" id="discount_percentage_<?= htmlspecialchars($item['id']) ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" value="<?= htmlspecialchars($item['discount_percentage']) ?>">
</div>
</div>
<div class="mt-3">
<label class="block text-sm font-medium text-gray-700" for="discount_reason_<?= htmlspecialchars($item['id']) ?>">Discount Reason</label>
<input type="text" name="discount_reason[]" id="discount_reason_<?= htmlspecialchars($item['id']) ?>" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-teal-500 focus:border-teal-500" placeholder="Enter reason for discount" value="<?= htmlspecialchars($item['discount_reason']) ?>">
</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="removeOrderItemRow(this)">
✕ Remove Product
</button>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<hr class="my-6">
<!-- Add New Order Items -->
<div class="mb-6">
<h5 class="text-lg font-semibold text-gray-800 mb-4">Add New Order Items</h5>
<div id="order-items-container">
<!-- New Order Item 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="addOrderItemRow()">
<i class="bi bi-plus-circle-fill"></i> Add Another Product
</button>
</div>
<!-- Submit Buttons -->
<div class="flex justify-between">
<button type="submit" class="bg-teal-600 text-white px-6 py-2 rounded-lg hover:bg-teal-700 transition duration-300">Update Order</button>
<a href="view_orders.php" class="bg-gray-500 text-white px-6 py-2 rounded-lg hover:bg-gray-600 transition duration-300 flex items-center">
<i class="bi bi-arrow-left-circle mr-2"></i> Cancel
</a>
</div>
</form>
</div>
<!-- Footer -->
<div class="footer mt-12 text-center text-gray-500">
© <?= 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"
});
flatpickr("#delivery_date", {
dateFormat: "Y-m-d",
minDate: "today"
});
</script>
<!-- Bootstrap Tooltip Initialization (if using tooltips in future) -->
<script>
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
// No closing PHP tag to prevent unwanted output
?>
Summary of Fixes and Improvements:
Removed the Redundant is_paid_status Checkbox:
Ensured that only one is_paid checkbox exists in the form to prevent conflicts.
Corrected the JavaScript Function Call:
Changed removeExistingOrderItemRow(this) to removeOrderItemRow(this) in existing order items to match the defined JavaScript function.
Used Absolute Path for header.php:
Updated require_once '../../includes/header.php'; to require_once __DIR__ . '/../../includes/header.php'; for correct file inclusion.
Handled apply_discount[] in PHP:
Added handling for apply_discount[] to ensure discounts are only applied when the checkbox is checked.
Enhanced Form Validation and User Experience:
Improved validation messages.
Ensured form fields retain user inputs after validation errors.
Enhanced button styles for better UX.
Consistent Use of Tailwind CSS and Bootstrap Icons:
Ensured all UI elements are styled consistently using Tailwind CSS.
Utilized Bootstrap Icons effectively for better visual cues.
Sanitization and Security:
Continued using sanitize_input() and htmlspecialchars() to prevent XSS attacks.
Although not implemented, consider adding CSRF protection for enhanced security.
Code Readability and Maintenance:
Added comments for better understanding.
Structured the code for readability and easier maintenance.
Recommendations for Further Enhancements:
CSRF Protection: Implement CSRF tokens to protect against Cross-Site Request Forgery attacks.
Form Validation Enhancements: Consider using more robust validation techniques or libraries to handle complex validation rules.
Separation of Concerns: Utilize templating engines (like Twig or Blade) to separate PHP logic from HTML for better maintainability.
Error Logging: Implement proper error logging mechanisms instead of displaying errors directly to users, especially in production environments.
By applying these fixes and recommendations, your order editing functionality should work more reliably and securely.
Copy first response
n
am
e
,
c
.
co
n
t
a
c
t
A
S
c
u
s
t
o
m
e
r c
o
n
t
a
c
t
,
c
.
d
e
l
i
v
er
y a
dd
r
ess
F
R
O
M
or
d
er
so
J
O
I
N
c
u
s
t
o
m
er
sc
O
N
o
.
c
u
s
t
o
m
e
r i
d
=
c . i d W H E R E o . i d =
? L I M I T 1" ;
(
"
i
"
,
p
r
o
d
u
c
t n
am
e
,
p
.
s
i
z
e
,
p
.
p
r
i
ce
F
R
O
M
or
d
e
r i
t
e
m
so
i
J
O
I
N
p
r
o
d
u
c
t
s
pO
N
o
i
.
p
r
o
d
u
c
t i
d
=
p . i d W H E R E o i . or d e r i d =
? " ;
bin
d p
a
r
am
(
"
i
"
,
ec
u
t
e
(
)
;
g
e
t r
es
u
l
t
(
)
;
a
dd
r
es
s ′
])
;
or
i
t
y ′
]?
? ′
N
or
ma
l ′
)
;
//
I
ni
t
ia
l
i
z
es
y d
a
t
e
t
im
e ′
])?
s
ani
t
i
z
e i
n
p
u
t
(
y
d
a
t
e ′
])?
s
ani
t
i
z
e i
n
p
u
t
(