Certainly! To enhance your Kaak Alia Management System by adding and managing date and time functionalities, we'll walk through the necessary steps. This guide will help you:
- Understand the Current Setup
- Modify the Database (if necessary)
- Update the
add_order.php Script
- Update the
edit_order.php Script
- Update the
view_orders.php Script
- Ensure Proper Display and Validation
1. Understanding the Current Setup
Your current system manages orders with the following key aspects:
- Database Tables:
customers, orders, products, users
- Order Management Scripts:
add_order.php: Adds new orders
edit_order.php: Edits existing orders
view_orders.php: Views all orders
The orders table already includes an order_date field, which records the timestamp when an order is placed. However, to enhance functionality, you might want to:
- Add a
delivery_date field: To specify when an order should be delivered.
- Allow users to view and edit both
order_date and delivery_date.
2. Modify the Database
Adding a delivery_date Field
If you want to track when each order is to be delivered, you should add a delivery_date field to the orders table.
SQL Command to Add delivery_date:
ALTER TABLE `orders`
ADD COLUMN `delivery_date` DATE DEFAULT NULL AFTER `order_date`;
Explanation:
DATE Type: Stores only the date. If you need to store both date and time, use DATETIME.
DEFAULT NULL: Allows the field to be optional initially.
If you prefer to store date and time:
ALTER TABLE `orders`
ADD COLUMN `delivery_datetime` DATETIME DEFAULT NULL AFTER `order_date`;
Execute this SQL command using phpMyAdmin or your preferred database management tool.
3. Update add_order.php
Objective:
- Add Delivery Date Input: Allow users to specify the delivery date when placing an order.
- Handle the New Field in PHP and SQL.
Steps:
- Update the HTML Form to Include Delivery Date:
- Sanitize and Validate the
delivery_date Input:
- Modify the SQL Insert Statement to Include
delivery_date:
Detailed Implementation:
1. Update the HTML Form
Add a new input field for delivery_date in the form section where you collect order details.
<!-- Add this within the Order Details section in the form -->
<label class="form-label" for="delivery_date">Delivery Date</label>
<input type="date" id="delivery_date" name="delivery_date" class="form-control"
value="<?= isset($_POST['delivery_date']) ? htmlspecialchars($_POST['delivery_date']) : '' ?>">
Placement Example:
Place the delivery_date input after the order_date or any suitable location in your order details section.
<!-- Existing Order Details -->
<label class="form-label" for="packaging_preferences">Packaging Preferences</label>
<input type="text" id="packaging_preferences" name="packaging_preferences" class="form-control"
value="<?= isset($_POST['packaging_preferences']) ? htmlspecialchars($_POST['packaging_preferences']) : '' ?>">
<!-- New Delivery Date Field -->
<label class="form-label" for="delivery_date">Delivery Date</label>
<input type="date" id="delivery_date" name="delivery_date" class="form-control"
value="<?= isset($_POST['delivery_date']) ? htmlspecialchars($_POST['delivery_date']) : '' ?>">
2. Sanitize and Validate delivery_date
In your PHP form handling section, retrieve and sanitize the delivery_date.
// Retrieve and sanitize delivery_date
$delivery_date = isset($_POST['delivery_date']) ? trim($_POST['delivery_date']) : null;
// Validate delivery_date if provided
if ($delivery_date && !preg_match("/^\d{4}-\d{2}-\d{2}$/", $delivery_date)) {
$error = "Invalid delivery date format.";
}
Optional Enhancements:
- Ensure
delivery_date is not before order_date.
- Ensure
delivery_date is not in the past.
3. Modify the SQL Insert Statement
Update the SQL statement to include the delivery_date field.
Before:
$stmt = $conn->prepare("INSERT INTO orders (customer_id, product_id, quantity, packaging_preferences) VALUES (?, ?, ?, ?)");
After:
Assuming you added delivery_date as a DATE type.
$stmt = $conn->prepare("INSERT INTO orders (customer_id, product_id, quantity, packaging_preferences, delivery_date) VALUES (?, ?, ?, ?, ?)");
Bind the New Parameter:
$stmt->bind_param("iiiss", $customer_id, $product_id, $quantity, $packaging_preferences, $delivery_date);
Complete Modified add_order.php:
Here's the updated script with the new delivery_date functionality.
<?php
// public/orders/add_order.php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include authentication and database connection
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
// Initialize variables
$success = '';
$error = '';
// Fetch products for selection
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);
if (!$products_result) {
die("Error fetching products: " . $conn->error);
}
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Sanitize and validate input
$customer_name = trim($_POST['customer_name']);
$contact = trim($_POST['contact']);
$delivery_address = trim($_POST['delivery_address']);
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity']);
$packaging_preferences = trim($_POST['packaging_preferences']);
$delivery_date = isset($_POST['delivery_date']) ? trim($_POST['delivery_date']) : null;
// Basic validation
if (empty($customer_name)) {
$error = "Customer name is required.";
} elseif (empty($product_id)) {
$error = "Product selection is required.";
} elseif ($quantity <= 0) {
$error = "Quantity must be at least 1.";
} elseif ($delivery_date && !preg_match("/^\d{4}-\d{2}-\d{2}$/", $delivery_date)) {
$error = "Invalid delivery date format.";
} else {
// Optional: Ensure delivery_date is not 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 {
// Insert into customers table using prepared statement
$stmt = $conn->prepare("INSERT INTO customers (name, contact, delivery_address) VALUES (?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("sss", $customer_name, $contact, $delivery_address);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$customer_id = $stmt->insert_id;
$stmt->close();
// Insert into orders table using prepared statement
$stmt = $conn->prepare("INSERT INTO orders (customer_id, product_id, quantity, packaging_preferences, delivery_date) VALUES (?, ?, ?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("iiiss", $customer_id, $product_id, $quantity, $packaging_preferences, $delivery_date);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$stmt->close();
// Commit transaction
$conn->commit();
$success = "Order added successfully!";
// Reset form fields
$_POST = [];
} catch (Exception $e) {
// Rollback transaction
$conn->rollback();
$error = "Error adding order: " . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add New Order - Kaak Alia Management System</title>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/kaak_alia_management_system/assets/bootstrap/css/bootstrap.min.css">
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<!-- Embedded Custom Styles -->
<style>
/* Your existing CSS styles here */
/* ... */
</style>
</head>
<body>
<!-- Header -->
<div class="header">
Kaak Alia Dashboard
</div>
<!-- Welcome Section -->
<div class="welcome-section">
<h3>Welcome to the Kaak Alia Management System!</h3>
<hr>
</div>
<!-- Form Container -->
<div class="form-container">
<h3>Add New Order</h3>
<?php if ($success): ?>
<div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<form method="POST" action="">
<!-- Customer Details -->
<div class="form-section">
<h5>Customer Details</h5>
<label class="form-label" for="customer_name">Name <span class="text-danger">*</span></label>
<input type="text" id="customer_name" name="customer_name" class="form-control"
value="<?= isset($_POST['customer_name']) ? htmlspecialchars($_POST['customer_name']) : '' ?>"
required>
<label class="form-label" for="contact">Contact</label>
<input type="text" id="contact" name="contact" class="form-control"
value="<?= isset($_POST['contact']) ? htmlspecialchars($_POST['contact']) : '' ?>">
<label class="form-label" for="delivery_address">Delivery Address</label>
<textarea id="delivery_address" name="delivery_address" class="form-control"><?= isset($_POST['delivery_address']) ? htmlspecialchars($_POST['delivery_address']) : '' ?></textarea>
</div>
<hr>
<!-- Order Details -->
<div class="form-section">
<h5>Order Details</h5>
<label class="form-label" for="product_id">Product <span class="text-danger">*</span></label>
<select id="product_id" name="product_id" class="form-control" required>
<option value="">Select Product</option>
<?php while($product = $products_result->fetch_assoc()): ?>
<option value="<?= $product['id'] ?>" <?= (isset($_POST['product_id']) && $_POST['product_id'] == $product['id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
<label class="form-label" for="quantity">Quantity <span class="text-danger">*</span></label>
<input type="number" id="quantity" name="quantity" class="form-control" min="1"
value="<?= isset($_POST['quantity']) ? intval($_POST['quantity']) : '1' ?>" required>
<label class="form-label" for="packaging_preferences">Packaging Preferences</label>
<input type="text" id="packaging_preferences" name="packaging_preferences" class="form-control"
value="<?= isset($_POST['packaging_preferences']) ? htmlspecialchars($_POST['packaging_preferences']) : '' ?>">
<!-- New Delivery Date Field -->
<label class="form-label" for="delivery_date">Delivery Date</label>
<input type="date" id="delivery_date" name="delivery_date" class="form-control"
value="<?= isset($_POST['delivery_date']) ? htmlspecialchars($_POST['delivery_date']) : '' ?>">
</div>
<!-- Submit Button -->
<button type="submit" class="submit-button btn-add-order">Add Order</button>
</form>
</div>
<!-- Footer -->
<div class="footer">
© 2024 Kaak Alia Bakery. All rights reserved.
</div>
<!-- Bootstrap JS Bundle -->
<script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
4. Update edit_order.php
Objective:
- Allow Editing of
delivery_date: Enable users to update the delivery date when editing an order.
- Ensure Proper Validation and SQL Handling.
Steps:
- Fetch
delivery_date When Retrieving Order Details:
- Add Delivery Date Input to the Edit Form:
- Handle the
delivery_date in Form Submission:
- Update the SQL Update Statement to Include
delivery_date:
Detailed Implementation:
1. Fetch delivery_date
Ensure that delivery_date is fetched along with other order details.
Modify the Order Retrieval SQL:
$order_sql = "SELECT *, delivery_date FROM orders WHERE id = ? LIMIT 1";
Alternatively, if you've already added it, no change might be needed.
2. Add Delivery Date Input to the Form
Add a date input field in the edit form to allow updating the delivery_date.
<!-- Add this within the form in the Edit Order section -->
<label class="form-label" for="delivery_date">Delivery Date</label>
<input type="date" id="delivery_date" name="delivery_date" class="form-control"
value="<?= isset($_POST['delivery_date']) ? htmlspecialchars($_POST['delivery_date']) : htmlspecialchars($order['delivery_date']) ?>">
Placement Example:
Place it below the packaging_preferences or any suitable location in your order details section.
<!-- Existing Order Details -->
<label class="form-label" for="packaging_preferences">Packaging Preferences</label>
<input type="text" name="packaging_preferences" id="packaging_preferences" class="form-control" value="<?= htmlspecialchars($order['packaging_preferences']) ?>" placeholder="e.g., Gift Wrap">
<!-- New Delivery Date Field -->
<label class="form-label" for="delivery_date">Delivery Date</label>
<input type="date" name="delivery_date" id="delivery_date" class="form-control"
value="<?= isset($_POST['delivery_date']) ? htmlspecialchars($_POST['delivery_date']) : htmlspecialchars($order['delivery_date']) ?>">
3. Handle delivery_date in Form Submission
In the PHP handling section, retrieve, sanitize, and validate the delivery_date.
// Retrieve and sanitize delivery_date
$delivery_date = isset($_POST['delivery_date']) ? trim($_POST['delivery_date']) : null;
// Validate delivery_date if provided
if ($delivery_date && !preg_match("/^\d{4}-\d{2}-\d{2}$/", $delivery_date)) {
$error = "Invalid delivery date format.";
}
Optional Enhancements:
- Ensure
delivery_date is not before order_date.
- Ensure
delivery_date is not in the past.
4. Update the SQL Update Statement
Modify the SQL statement to include delivery_date.
Before:
$update_order_sql = "UPDATE orders
SET product_id = ?, quantity = ?, packaging_preferences = ?, status = ?
WHERE id = ?";
$stmt->bind_param("iissi", $product_id, $quantity, $packaging_preferences, $status, $order_id);
After:
$update_order_sql = "UPDATE orders
SET product_id = ?, quantity = ?, packaging_preferences = ?, status = ?, delivery_date = ?
WHERE id = ?";
$stmt->bind_param("iisssi", $product_id, $quantity, $packaging_preferences, $status, $delivery_date, $order_id);
Complete Modified edit_order.php:
Here's the updated script with the new delivery_date functionality.
<?php
// public/orders/edit_order.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include authentication and database connection
require_once '../../includes/auth.php';
require_once '../../includes/db_connect.php';
// 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");
exit();
}
// Fetch order details using prepared statements
$order_sql = "SELECT * FROM orders WHERE id = ? LIMIT 1";
$order_stmt = $conn->prepare($order_sql);
$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");
exit();
}
$order = $order_result->fetch_assoc();
$order_stmt->close();
// Fetch products for selection using prepared statements
$products_sql = "SELECT * FROM products ORDER BY name ASC";
$products_result = $conn->query($products_sql);
// Handle form submission for updating the order
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Retrieve and sanitize form inputs
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
$packaging_preferences = isset($_POST['packaging_preferences']) ? trim($_POST['packaging_preferences']) : '';
$status = isset($_POST['status']) ? trim($_POST['status']) : 'Pending';
$delivery_date = isset($_POST['delivery_date']) ? trim($_POST['delivery_date']) : null;
// Validate inputs
if ($product_id <= 0 || $quantity <= 0 || empty($status)) {
$error = "Please fill in all required fields with valid data.";
} elseif ($delivery_date && !preg_match("/^\d{4}-\d{2}-\d{2}$/", $delivery_date)) {
$error = "Invalid delivery date format.";
} else {
// Optional: Ensure delivery_date is not 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)) {
// Update order using prepared statements
$update_order_sql = "UPDATE orders
SET product_id = ?, quantity = ?, packaging_preferences = ?, status = ?, delivery_date = ?
WHERE id = ?";
$update_stmt = $conn->prepare($update_order_sql);
if ($update_stmt) {
$update_stmt->bind_param("iisssi", $product_id, $quantity, $packaging_preferences, $status, $delivery_date, $order_id);
if ($update_stmt->execute()) {
$success = "Order updated successfully!";
// Refresh order data
$order['product_id'] = $product_id;
$order['quantity'] = $quantity;
$order['packaging_preferences'] = $packaging_preferences;
$order['status'] = $status;
$order['delivery_date'] = $delivery_date;
} else {
$error = "Error updating order: " . $update_stmt->error;
}
$update_stmt->close();
} else {
$error = "Failed to prepare the update statement: " . $conn->error;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Order #<?= htmlspecialchars($order_id) ?> - Kaak Alia Management System</title>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="../../public/bootstrap/css/bootstrap.min.css">
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<!-- Embedded Custom Styles -->
<style>
/* Your existing CSS styles here */
/* ... */
</style>
</head>
<body>
<!-- Header -->
<div class="header">
<h1>Kaak Alia Management System</h1>
</div>
<!-- Container -->
<div class="container-custom">
<h3 class="mb-4">Edit Order #<?= htmlspecialchars($order_id) ?></h3>
<!-- Display Success or Error Messages -->
<?php if (!empty($success)): ?>
<div class="alert alert-custom alert-success-custom"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>
<?php if (!empty($error)): ?>
<div class="alert alert-custom alert-danger-custom"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<!-- Edit Order Form -->
<form method="POST" action="">
<div class="row mb-3">
<!-- Product Selection -->
<div class="col-md-6 mb-3">
<label for="product_id" class="form-label">Product <span class="text-danger">*</span></label>
<select name="product_id" id="product_id" class="form-control" required>
<option value="">Select Product</option>
<?php while($product = $products_result->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($product['id']) ?>" <?= ($product['id'] == $order['product_id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<!-- Quantity Input -->
<div class="col-md-6 mb-3">
<label for="quantity" class="form-label">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity" id="quantity" class="form-control" min="1" value="<?= htmlspecialchars($order['quantity']) ?>" required>
</div>
</div>
<!-- Packaging Preferences -->
<div class="mb-3">
<label for="packaging_preferences" class="form-label">Packaging Preferences</label>
<input type="text" name="packaging_preferences" id="packaging_preferences" class="form-control" value="<?= htmlspecialchars($order['packaging_preferences']) ?>" placeholder="e.g., Gift Wrap">
</div>
<!-- Delivery Date -->
<div class="mb-3">
<label for="delivery_date" class="form-label">Delivery Date</label>
<input type="date" name="delivery_date" id="delivery_date" class="form-control"
value="<?= isset($_POST['delivery_date']) ? htmlspecialchars($_POST['delivery_date']) : htmlspecialchars($order['delivery_date']) ?>">
</div>
<!-- Status Selection -->
<div class="mb-4">
<label for="status" class="form-label">Status <span class="text-danger">*</span></label>
<select name="status" id="status" class="form-control" required>
<option value="">Select Status</option>
<option value="Pending" <?= ($order['status'] == 'Pending') ? 'selected' : '' ?>>Pending</option>
<option value="In Progress" <?= ($order['status'] == 'In Progress') ? 'selected' : '' ?>>In Progress</option>
<option value="Completed" <?= ($order['status'] == 'Completed') ? 'selected' : '' ?>>Completed</option>
<option value="Delivered" <?= ($order['status'] == 'Delivered') ? 'selected' : '' ?>>Delivered</option>
</select>
</div>
<!-- Form Buttons -->
<div class="d-flex justify-content-between">
<button type="submit" class="btn btn-primary-custom">Update Order</button>
<a href="view_orders.php" class="btn btn-secondary-custom">Cancel</a>
</div>
</form>
</div>
<!-- Footer -->
<div class="footer">
© 2024 Kaak Alia Bakery. All rights reserved.
</div>
<!-- Bootstrap JS Bundle -->
<script src="../../public/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
5. Update view_orders.php
Objective:
- Display
delivery_date: Show the delivery date in the orders table.
- Allow Quick Updates of
delivery_date (Optional): If desired, enable inline editing or quick status updates related to delivery.
Steps:
- Modify the SQL Query to Include
delivery_date:
- Update the Orders Table to Display
delivery_date:
- Adjust Status Update Logic if Necessary:
Detailed Implementation:
1. Modify the SQL Query
Ensure that delivery_date is fetched along with other order details.
Updated SQL Query:
SELECT orders.*, customers.name as customer_name, products.name as product_name, products.size as product_size
FROM orders
JOIN customers ON orders.customer_id = customers.id
JOIN products ON orders.product_id = products.id
ORDER BY orders.order_date DESC
Note: delivery_date is already part of orders.*, so no changes are needed unless you want to alias it.
2. Update the Orders Table in HTML
Add a new column for Delivery Date in the table header and corresponding data cells.
Modify Table Headers:
<thead>
<tr>
<th>ID</th>
<th>Customer</th>
<th>Product</th>
<th>Size</th>
<th>Quantity</th>
<th>Packaging</th>
<th>Status</th>
<th>Order Date</th>
<th>Delivery Date</th> <!-- New Column -->
<th>Actions</th>
</tr>
</thead>
Modify Table Body:
Add a new <td> for each row to display delivery_date.
<tbody>
<?php if ($orders_result->num_rows > 0): ?>
<?php while($order = $orders_result->fetch_assoc()): ?>
<tr>
<td><?= htmlspecialchars($order['id']) ?></td>
<td><?= htmlspecialchars($order['customer_name']) ?></td>
<td><?= htmlspecialchars($order['product_name']) ?></td>
<td><?= htmlspecialchars($order['product_size']) ?></td>
<td><?= htmlspecialchars($order['quantity']) ?></td>
<td><?= htmlspecialchars($order['packaging_preferences']) ?></td>
<td>
<?php
switch ($order['status']) {
case 'Pending':
echo '<span class="badge-status-pending">Pending</span>';
break;
case 'In Progress':
echo '<span class="badge-status-in-progress">In Progress</span>';
break;
case 'Completed':
echo '<span class="badge-status-completed">Completed</span>';
break;
case 'Delivered':
echo '<span class="badge-status-delivered">Delivered</span>';
break;
default:
echo '<span class="badge bg-light text-dark">Unknown</span>';
}
?>
</td>
<td><?= date("d M Y, h:i A", strtotime($order['order_date'])) ?></td>
<td><?= $order['delivery_date'] ? date("d M Y", strtotime($order['delivery_date'])) : 'N/A' ?></td> <!-- New Cell -->
<td>
<!-- Existing Actions: Edit and Change Status -->
<a href="edit_order.php?id=<?= $order['id'] ?>" class="btn btn-sm btn-outline-secondary" title="Edit Order">
<i class="bi bi-pencil-fill"></i>
</a>
<!-- Change Status Dropdown -->
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-info dropdown-toggle" data-bs-toggle="dropdown" title="Change Status">
<i class="bi bi-arrow-repeat"></i>
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="?update_status=Pending&order_id=<?= $order['id'] ?>&new_status=Pending">Pending</a></li>
<li><a class="dropdown-item" href="?update_status=In Progress&order_id=<?= $order['id'] ?>&new_status=In Progress">In Progress</a></li>
<li><a class="dropdown-item" href="?update_status=Completed&order_id=<?= $order['id'] ?>&new_status=Completed">Completed</a></li>
<li><a class="dropdown-item" href="?update_status=Delivered&order_id=<?= $order['id'] ?>&new_status=Delivered">Delivered</a></li>
</ul>
</div>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="10" class="text-center">No orders found.</td>
</tr>
<?php endif; ?>
</tbody>
Note: Adjust the colspan in the "No orders found" row to match the new number of columns.
3. Adjust Status Update Logic (If Necessary)
Ensure that when updating the status, the changes reflect appropriately. Since we added delivery_date, you might want to consider business logic such as:
- If status is set to 'Delivered', ensure
delivery_date is set or verified.
- Prevent status updates that conflict with existing
delivery_date values.
Example Enhancement:
// Inside the status update handler
if (isset($_GET['update_status'])) {
$order_id = intval($_GET['order_id']);
$new_status = $conn->real_escape_string($_GET['new_status']);
// Validate new_status
$valid_statuses = ['Pending', 'In Progress', 'Completed', 'Delivered'];
if (in_array($new_status, $valid_statuses)) {
// Optional: If setting to 'Delivered', ensure delivery_date is set
if ($new_status === 'Delivered') {
$check_sql = "SELECT delivery_date FROM orders WHERE id = ?";
$check_stmt = $conn->prepare($check_sql);
$check_stmt->bind_param("i", $order_id);
$check_stmt->execute();
$check_result = $check_stmt->get_result();
if ($check_result->num_rows == 1) {
$order = $check_result->fetch_assoc();
if (empty($order['delivery_date'])) {
header("Location: view_orders.php?error=3"); // Delivery date not set
exit();
}
}
$check_stmt->close();
}
$update_sql = "UPDATE orders SET status=? WHERE id=?";
$stmt = $conn->prepare($update_sql);
$stmt->bind_param("si", $new_status, $order_id);
if ($stmt->execute()) {
$stmt->close();
header("Location: view_orders.php?success=1");
exit();
} else {
$stmt->close();
header("Location: view_orders.php?error=1");
exit();
}
} else {
header("Location: view_orders.php?error=2");
exit();
}
}
Handle New Error Case in the HTML:
<?php if (isset($_GET['error'])): ?>
<?php if ($_GET['error'] == 1): ?>
<div class="alert-error-custom">Failed to update order status.</div>
<?php elseif ($_GET['error'] == 2): ?>
<div class="alert-error-custom">Invalid status selected.</div>
<?php elseif ($_GET['error'] == 3): ?>
<div class="alert-error-custom">Cannot set status to Delivered without a delivery date.</div>
<?php endif; ?>
<?php endif; ?>
Complete Modified view_orders.php:
Here's the updated script with the delivery_date displayed.
<?php
// public/orders/view_orders.php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include authentication and database connection
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
// Handle status update
if (isset($_GET['update_status'])) {
$order_id = intval($_GET['order_id']);
$new_status = $conn->real_escape_string($_GET['new_status']);
// Validate new_status
$valid_statuses = ['Pending', 'In Progress', 'Completed', 'Delivered'];
if (in_array($new_status, $valid_statuses)) {
// Optional: If setting to 'Delivered', ensure delivery_date is set
if ($new_status === 'Delivered') {
$check_sql = "SELECT delivery_date FROM orders WHERE id = ?";
$check_stmt = $conn->prepare($check_sql);
$check_stmt->bind_param("i", $order_id);
$check_stmt->execute();
$check_result = $check_stmt->get_result();
if ($check_result->num_rows == 1) {
$order = $check_result->fetch_assoc();
if (empty($order['delivery_date'])) {
header("Location: view_orders.php?error=3"); // Delivery date not set
exit();
}
}
$check_stmt->close();
}
$update_sql = "UPDATE orders SET status=? WHERE id=?";
$stmt = $conn->prepare($update_sql);
$stmt->bind_param("si", $new_status, $order_id);
if ($stmt->execute()) {
$stmt->close();
header("Location: view_orders.php?success=1");
exit();
} else {
$stmt->close();
header("Location: view_orders.php?error=1");
exit();
}
} else {
header("Location: view_orders.php?error=2");
exit();
}
}
// Fetch orders with customer and product details
$orders_sql = "SELECT orders.*, customers.name as customer_name, products.name as product_name, products.size as product_size
FROM orders
JOIN customers ON orders.customer_id = customers.id
JOIN products ON orders.product_id = products.id
ORDER BY orders.order_date DESC";
$orders_result = $conn->query($orders_sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Orders - Kaak Alia Management System</title>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/kaak_alia_management_system/assets/bootstrap/css/bootstrap.min.css">
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<!-- Embedded Custom Styles -->
<style>
/* Your existing CSS styles here */
/* ... */
</style>
</head>
<body>
<!-- Header -->
<div class="header">
View Orders
</div>
<!-- Display Success or Error Messages -->
<?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
<div class="alert-success-custom">Order status updated successfully!</div>
<?php endif; ?>
<?php if (isset($_GET['error'])): ?>
<?php if ($_GET['error'] == 1): ?>
<div class="alert-error-custom">Failed to update order status.</div>
<?php elseif ($_GET['error'] == 2): ?>
<div class="alert-error-custom">Invalid status selected.</div>
<?php elseif ($_GET['error'] == 3): ?>
<div class="alert-error-custom">Cannot set status to Delivered without a delivery date.</div>
<?php endif; ?>
<?php endif; ?>
<!-- Container -->
<div class="container">
<!-- Recent Orders Table -->
<div class="recent-orders-section">
<h4>All Orders</h4>
<table>
<thead>
<tr>
<th>ID</th>
<th>Customer</th>
<th>Product</th>
<th>Size</th>
<th>Quantity</th>
<th>Packaging</th>
<th>Status</th>
<th>Order Date</th>
<th>Delivery Date</th> <!-- New Column -->
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if ($orders_result->num_rows > 0): ?>
<?php while($order = $orders_result->fetch_assoc()): ?>
<tr>
<td><?= htmlspecialchars($order['id']) ?></td>
<td><?= htmlspecialchars($order['customer_name']) ?></td>
<td><?= htmlspecialchars($order['product_name']) ?></td>
<td><?= htmlspecialchars($order['product_size']) ?></td>
<td><?= htmlspecialchars($order['quantity']) ?></td>
<td><?= htmlspecialchars($order['packaging_preferences']) ?></td>
<td>
<?php
switch ($order['status']) {
case 'Pending':
echo '<span class="badge-status-pending">Pending</span>';
break;
case 'In Progress':
echo '<span class="badge-status-in-progress">In Progress</span>';
break;
case 'Completed':
echo '<span class="badge-status-completed">Completed</span>';
break;
case 'Delivered':
echo '<span class="badge-status-delivered">Delivered</span>';
break;
default:
echo '<span class="badge bg-light text-dark">Unknown</span>';
}
?>
</td>
<td><?= date("d M Y, h:i A", strtotime($order['order_date'])) ?></td>
<td><?= $order['delivery_date'] ? date("d M Y", strtotime($order['delivery_date'])) : 'N/A' ?></td> <!-- New Cell -->
<td>
<!-- Edit Button -->
<a href="edit_order.php?id=<?= $order['id'] ?>" class="btn btn-sm btn-outline-secondary" title="Edit Order">
<i class="bi bi-pencil-fill"></i>
</a>
<!-- Change Status Dropdown -->
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-info dropdown-toggle" data-bs-toggle="dropdown" title="Change Status">
<i class="bi bi-arrow-repeat"></i>
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="?update_status=Pending&order_id=<?= $order['id'] ?>&new_status=Pending">Pending</a></li>
<li><a class="dropdown-item" href="?update_status=In Progress&order_id=<?= $order['id'] ?>&new_status=In Progress">In Progress</a></li>
<li><a class="dropdown-item" href="?update_status=Completed&order_id=<?= $order['id'] ?>&new_status=Completed">Completed</a></li>
<li><a class="dropdown-item" href="?update_status=Delivered&order_id=<?= $order['id'] ?>&new_status=Delivered">Delivered</a></li>
</ul>
</div>
</td>
</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="10" class="text-center">No orders found.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
<a href="#" class="view-all">View All Orders</a>
</div>
</div>
<!-- Footer -->
<div class="footer">
© 2024 Kaak Alia Bakery. All rights reserved.
</div>
<!-- Bootstrap JS Bundle -->
<script src="/kaak_alia_management_system/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Initialize Bootstrap Tooltip (Optional) -->
<script>
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>
</body>
</html>
6. Ensure Proper Display and Validation
A. Consistent Date Formatting
Ensure that all dates are displayed consistently across your application. For example:
- Order Date:
d M Y, h:i A (e.g., 06 Nov 2024, 12:32 PM)
- Delivery Date:
d M Y (e.g., 10 Nov 2024)
Adjust the date() function as needed to match your preferred format.
B. Frontend Enhancements
To improve user experience, consider:
- Using Date Pickers: Enhance date inputs with JavaScript date pickers like Flatpickr or jQuery UI Datepicker.
- Validations: Implement frontend validations in addition to backend validations to provide immediate feedback.
C. Accessibility Considerations
Ensure that all form fields are properly labeled and accessible to users with disabilities.
Final Notes
By following the steps above, you've successfully enhanced your order management system to handle and display delivery dates. Here's a summary of the changes:
-
Database:
- Added a
delivery_date field to the orders table.
-
Add Order (add_order.php):
- Included an input field for
delivery_date.
- Handled
delivery_date in form processing and SQL insertion.
-
Edit Order (edit_order.php):
- Included an input field for
delivery_date.
- Handled
delivery_date in form processing and SQL updating.
-
View Orders (view_orders.php):
- Added a column to display
delivery_date.
- Enhanced status update logic to consider
delivery_date.
-
General Enhancements:
- Ensured consistent date formatting.
- Considered frontend improvements for better user experience.
Additional Recommendations
-
Backup Your Database:
- Before making any changes, always backup your database to prevent data loss.
-
Test Thoroughly:
- After implementing changes, rigorously test all functionalities to ensure everything works as expected.
-
Security Considerations:
- Always use prepared statements to prevent SQL injection.
- Validate and sanitize all user inputs, both on the frontend and backend.
-
User Training:
- Inform and train your staff about the new
delivery_date feature to ensure smooth adoption.
-
Documentation:
- Update your system documentation to reflect the new changes for future reference.
By implementing these changes, your Kaak Alia Management System will be more robust, allowing better tracking and management of orders with specified delivery dates. If you have any further questions or need additional assistance, feel free to ask!