-- 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;
Assistant
--
-- 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;
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 */;) i want to update this codes add order (<?php
// public/orders/add_order.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// 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()
// Initialize variables
success=′′;error = '';
// Define an array of countries with their dialing codes
$countries = [
"Afghanistan" => "+93",
"Albania" => "+355",
"Algeria" => "+213",
"Andorra" => "+376",
"Angola" => "+244",
"Antigua and Barbuda" => "+1-268",
"Argentina" => "+54",
"Armenia" => "+374",
"Australia" => "+61",
"Austria" => "+43",
"Azerbaijan" => "+994",
"Bahamas" => "+1-242",
"Bahrain" => "+973",
"Bangladesh" => "+880",
"Barbados" => "+1-246",
"Belarus" => "+375",
"Belgium" => "+32",
"Belize" => "+501",
"Benin" => "+229",
"Bhutan" => "+975",
"Bolivia" => "+591",
"Bosnia and Herzegovina" => "+387",
"Botswana" => "+267",
"Brazil" => "+55",
"Brunei" => "+673",
"Bulgaria" => "+359",
"Burkina Faso" => "+226",
"Burundi" => "+257",
// ... (Add all other countries as needed)
"Kuwait" => "+965",
// Continue adding countries up to the desired list
];
// Fetch products for selection
productssql="SELECT∗FROMproductsORDERBYnameASC";products_result = conn−>query(products_sql);
if (!products_result) {
die("Error fetching products: " . conn->error);
}
// Initialize priority with default value
$priority = 'Normal';
// Set selectedcountrytoPOSTvalueordefaultto′+965′selected_country = sanitize_input($_POST['country'] ?? '+965');
// Handle form submission
if (_SERVER['REQUEST_METHOD'] == 'POST') {
// Sanitize and validate input
contact_input = sanitize_input(POST[′contact′]??′′);delivery_address = sanitize_input(POST[′deliverycustomer_name_input = sanitize_input($_POST['customer_name'] ?? '');
// Ensure contact number contains only digits
$contact_digits = preg_replace('/\D/', '', $contact_input);
if (empty($contact_digits)) {
$error = "A valid contact number is required.";
} else {
// Full contact number with country code
$full_contact = $selected_country . $contact_digits;
// Generate customer name or use provided name
if (!empty($customer_name_input)) {
$customer_name = $customer_name_input;
} else {
$customer_name = 'Order_' . $contact_digits;
}
}
// Set priority
$priority = sanitize_input($_POST['priority'] ?? 'Normal');
$free_shipping = isset($_POST['free_shipping']) ? 1 : 0;
$delivery_fee = $free_shipping ? 0.00 : (isset($_POST['delivery_fee']) ? floatval($_POST['delivery_fee']) : 0.00);
// Validate priority
$valid_priorities = ['Normal', 'Important', 'Quick'];
if (!in_array($priority, $valid_priorities)) {
$priority = 'Normal';
}
// Handle multiple products
$product_ids = $_POST['product_id'] ?? [];
$quantities = $_POST['quantity'] ?? [];
$packaging_preferences = $_POST['packaging_preferences'] ?? [];
$apply_discount = $_POST['apply_discount'] ?? [];
$discount_percentages = $_POST['discount_percentage'] ?? [];
$discount_reasons = $_POST['discount_reason'] ?? [];
// Basic validation
if (empty($customer_name)) {
$error = "Customer name generation failed.";
} elseif (empty($contact_input)) {
$error = "Contact number is required.";
} elseif (empty($product_ids) || !is_array($product_ids) || count($product_ids) == 0) {
$error = "At least one product must be selected.";
} else {
// Validate each product entry
foreach ($product_ids as $index => $pid) {
if (empty($pid)) {
$error = "Product selection is required for all items.";
break;
}
if (!isset($quantities[$index]) || intval($quantities[$index]) <= 0) {
$error = "Quantity must be at least 1 for all items.";
break;
}
// If discount is applied, validate discount fields
if (isset($apply_discount[$index])) {
$discount = trim($discount_percentages[$index]);
$reason = trim($discount_reasons[$index]);
if ($discount === '') {
$error = "Discount percentage is required if discount is applied.";
break;
}
if (!is_numeric($discount) || floatval($discount) < 0 || floatval($discount) > 100) {
$error = "Invalid discount percentage for product. It should be between 0 and 100.";
break;
}
if (empty($reason)) {
$error = "Discount reason is required if discount is applied.";
break;
}
}
}
// Validate delivery_datetime
$delivery_datetime_input = $_POST['delivery_datetime'] ?? '';
if (!empty($delivery_datetime_input)) {
// Convert from 'Y-m-d\TH:i' to 'Y-m-d H:i:s'
$delivery_datetime = sanitize_input(str_replace('T', ' ', $delivery_datetime_input) . ':00');
if (!preg_match("/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/", $delivery_datetime)) {
$error = "Invalid delivery date and time format.";
} elseif (strtotime($delivery_datetime) < strtotime(date('Y-m-d H:i:s'))) {
$error = "Delivery date and time cannot be in the past.";
}
} else {
$delivery_datetime = null;
}
// Validate delivery_fee if not free shipping
if (!$free_shipping) {
if (!isset($_POST['delivery_fee']) || !is_numeric($_POST['delivery_fee']) || floatval($_POST['delivery_fee']) < 0) {
$error = "Valid delivery fee is required.";
}
}
}
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, $full_contact, $delivery_address);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$customer_id = $stmt->insert_id;
$stmt->close();
// Insert into orders table using prepared statement
$status = 'Pending'; // Default status
$stmt = $conn->prepare("INSERT INTO orders (customer_id, status, priority, delivery_datetime, delivery_fee, free_shipping) VALUES (?, ?, ?, ?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("isssdi", $customer_id, $status, $priority, $delivery_datetime, $delivery_fee, $free_shipping);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
$order_id = $stmt->insert_id;
$stmt->close();
// Insert products into order_items table
$stmt = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, packaging_preferences, discount_percentage, discount_reason) VALUES (?, ?, ?, ?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
// Loop through each product
foreach ($product_ids as $index => $pid) {
$pid = intval($pid);
$qty = intval($quantities[$index]);
$pack_pref = sanitize_input($packaging_preferences[$index] ?? '');
// Handle discount
$discount_percent = 0.00;
$discount_rs = null;
if (isset($apply_discount[$index])) {
$discount_percent = floatval(trim($discount_percentages[$index]));
$discount_rs = sanitize_input($discount_reasons[$index]);
}
$stmt->bind_param("iiisds", $order_id, $pid, $qty, $pack_pref, $discount_percent, $discount_rs);
if (!$stmt->execute()) {
throw new Exception("Execute failed: " . $stmt->error);
}
}
$stmt->close();
// Commit transaction
$conn->commit();
// Redirect to view_orders.php after successful addition
header("Location: view_orders.php?success=1");
exit();
} catch (Exception $e) {
// Rollback transaction
$conn->rollback();
$error = "Error adding order: " . $e->getMessage();
}
}
}
// Now include the header AFTER form handling
require_once '../../includes/header.php';
?>
<!-- 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;
}
}
/* Tooltip styles */
.tooltip {
position: relative;
display: inline-block;
cursor: pointer;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 250px;
background-color: #6B7280; /* Tailwind's gray-500 */
color: #fff;
text-align: left;
border-radius: 4px;
padding: 8px;
position: absolute;
z-index: 10;
bottom: 125%; /* Position above the icon */
left: 50%;
margin-left: -125px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
</style>
<!-- Additional JavaScript for dynamic product addition, discount handling, and delivery fee toggle -->
<script>
let productCount = <?= isset($product_ids) ? count($product_ids) : 1; ?>;
function addProductRow() {
const productContainer = document.getElementById('products-container');
const productRow = document.createElement('div');
productRow.className = 'product-row bg-gray-50 p-4 rounded-lg shadow-md mb-4';
productRow.innerHTML = `
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700" for="product_id_${productCount}">
Product <span class="text-red-500">*</span>
<span class="tooltip">
<i class="bi bi-question-circle text-gray-400 text-sm"></i>
<span class="tooltiptext">
Select the product from the dropdown menu. This list includes available items that can be added to the customer's order.
</span>
</span>
</label>
<select name="product_id[]" id="product_id_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" required>
<option value="">Select Product</option>
<?php
// 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="quantity_${productCount}">
Quantity <span class="text-red-500">*</span>
<span class="tooltip">
<i class="bi bi-question-circle text-gray-400 text-sm"></i>
<span class="tooltiptext">
Enter the number of units required for each selected product. Quantities must be in whole numbers and are defaulted to one (1) if not specified.
</span>
</span>
</label>
<input type="number" name="quantity[]" id="quantity_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="1" value="1" required>
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="packaging_preferences_${productCount}">
Packaging Preferences
<span class="tooltip">
<i class="bi bi-question-circle text-gray-400 text-sm"></i>
<span class="tooltiptext">
Specify any particular packaging requests, such as 'Gift Wrap' or 'Fragile - Handle with Care,' to ensure customer satisfaction and safe delivery.
</span>
</span>
</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" placeholder="e.g., Gift Wrap">
</div>
<div>
<label class="block text-sm font-medium text-gray-700" for="discount_${productCount}">
Apply Discount
<span class="tooltip">
<i class="bi bi-question-circle text-gray-400 text-sm"></i>
<span class="tooltiptext">
Check this box if the customer is eligible for a discount. Discounts will be applied to the total product cost at checkout.
</span>
</span>
</label>
<div class="flex items-center mt-1">
<input type="checkbox" name="apply_discount[]" id="discount_checkbox_${productCount}" class="h-4 w-4 text-teal-600 border-gray-300 rounded" onchange="toggleDiscountFields(this, ${productCount})">
<label for="discount_checkbox_${productCount}" class="ml-2 block text-sm text-gray-700">
Yes
</label>
</div>
<div id="discount_fields_${productCount}" class="discount-fields mt-2" style="display: none;">
<label class="block text-sm font-medium text-gray-700" for="discount_percentage_${productCount}">
Discount Percentage (%) <span class="text-red-500">*</span>
<span class="tooltip">
<i class="bi bi-question-circle text-gray-400 text-sm"></i>
<span class="tooltiptext">
Enter the discount percentage to be applied to this product. It should be between 0 and 100.
</span>
</span>
</label>
<input type="number" name="discount_percentage[]" id="discount_percentage_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
<label class="block text-sm font-medium text-gray-700 mt-2" for="discount_reason_${productCount}">
Discount Reason <span class="text-red-500">*</span>
<span class="tooltip">
<i class="bi bi-question-circle text-gray-400 text-sm"></i>
<span class="tooltiptext">
Provide a reason for the discount applied to this product.
</span>
</span>
</label>
<input type="text" name="discount_reason[]" id="discount_reason_${productCount}" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2 focus:ring-teal-500 focus:border-teal-500" 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="removeProductRow(this)">
<i class="bi bi-trash-fill"></i> Remove Product
</button>
</div>
`;
productContainer.appendChild(productRow);
productCount++;
}
function removeProductRow(button) {
const productRow = button.closest('.product-row');
productRow.remove();
}
// Toggle discount fields based on checkbox
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 deliveryFeeField = document.getElementById('delivery_fee_field');
const deliveryFeeInput = document.getElementById('delivery_fee');
if (freeShippingCheckbox.checked) {
deliveryFeeField.style.display = 'none';
deliveryFeeInput.value = '0.00';
deliveryFeeInput.disabled = true;
} else {
deliveryFeeField.style.display = 'block';
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() {
// Add initial product row if none exist
if (document.getElementById('products-container').children.length === 0) {
addProductRow();
}
// Initialize delivery fee toggle
toggleDeliveryFee();
document.getElementById('free_shipping').addEventListener('change', toggleDeliveryFee);
// Initialize Customer Name auto-generation
document.getElementById('contact').addEventListener('input', autoGenerateCustomerName);
});
</script>
To add a "Customer Pickup" option to your order management system, you'll need to update both your database schema and the PHP code handling the order form. Below are the detailed steps and complete code changes required to implement this feature.
1. Update the Database Schema
You need to add a new column pickup to the orders table to indicate whether an order is for delivery or pickup.
SQL Code:
-- Add 'pickup' column to 'orders' table
ALTER TABLE `orders`
ADD COLUMN `pickup` TINYINT(1) NOT NULL DEFAULT 0 AFTER `is_paid`;
Explanation:
pickup: A TINYINT(1) that serves as a boolean flag.
0: Order is for delivery.
1: Order is for customer pickup.
2. Update the PHP Code
Modify the add_order.php script to include the "Customer Pickup" checkbox and handle its logic appropriately.
pickup Field: Captures whether the customer opts to pick up the order (1) or have it delivered (0).
Form Modifications:
Customer Pickup Checkbox:
Added a checkbox labeled "Customer Pickup" within the Delivery Details section.
When checked, this option indicates that the customer will collect the order directly from your kitchen.
JavaScript Enhancements:
togglePickup() Function:
Manages the visibility of the Delivery Details section based on the state of the "Customer Pickup" checkbox.
If "Customer Pickup" is checked:
Hides the Delivery Details section.
Unchecks "Free Shipping" if it was previously selected.
Sets the Delivery Fee to 0.00 and disables the input.
If unchecked:
Reveals the Delivery Details section and re-enables delivery-related inputs.
Event Listeners:
Initialized event listeners for the "Customer Pickup" checkbox to trigger togglePickup() on change.
Ensures that the form dynamically responds to user interactions.
Backend Validation and Processing:
Pickup Logic:
When processing the form submission, the script checks if the pickup checkbox was selected.
If pickup is 1:
Skips validation for delivery-related fields.
Inserts customer information without delivery_address.
Sets delivery-related fields (delivery_datetime, delivery_fee, free_shipping) to NULL or 0 accordingly.
If pickup is 0:
Proceeds with normal delivery validations and processing.
Error Handling:
Ensures that mandatory fields are validated appropriately based on whether the order is for pickup or delivery.
Summary
By following the above steps, you've successfully integrated a "Customer Pickup" option into your order management system. This enhancement allows customers to choose between having their orders delivered or picking them up directly from your kitchen. The form dynamically adjusts to user selections, ensuring a seamless and intuitive experience.
Note: Always backup your database before making structural changes and thoroughly test the new feature in a development environment before deploying it to production.