// 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",
"Kuwait" => "+965",
// Continue adding countries up to the desired list
];
// Fetch products for selection
products_result = products_sql);
Assistant
productssql="SELECT∗FROMproductsORDERBYnameASC";
conn−>query(
if (!products_result) {
die("Error fetching products: " . conn->error);
}
// Handle form submission
if (_SERVER['REQUEST_METHOD'] == 'POST') {
// Sanitize and validate input
selected_country = sanitize_input(POST[′country′]??′+965′);contact_input = sanitize_input(POST[′contactdelivery_address = sanitize_input($_POST['delivery_address'] ?? '');
code
// Validate contact number: allow digits, spaces, hyphens, parentheses, and plus signs
if (empty($contact_input) || !preg_match('/^[\d\+\-\s\(\)]+$/', $contact_input)) {
$error = "A valid contact number is required. Please enter only numbers, spaces, hyphens, parentheses, or plus signs.";
} else {
// Full contact number with country code
$full_contact = $selected_country . ' ' . $contact_input;
// Generate customer name
// Optionally, you can format the customer name differently if needed
$customer_name = 'Order_' . preg_replace('/\D/', '', $full_contact);
}
$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';
?>
Certainly! Below is the updated PHP code for your add_order.php file with the following enhancements:
Reordered Form Fields: The Contact Number field is now placed above the Customer Name field.
Editable Customer Name: The Customer Name field is now editable, allowing you to input the customer's actual name instead of auto-generating it.
Enhanced Contact Number UX:
Improved form layout for better usability.
Enhanced validation to ensure flexibility while maintaining data integrity.
Removed the auto-generation script for the customer name, as it's no longer needed.
Optionally, you can integrate a more advanced phone input library like intl-tel-input for a better user experience (this is not included here but can be considered for future improvements).
Contact Number is now placed above the Customer Name.
Customer Name is now an editable field instead of being auto-generated and read-only.
Removed Auto-Generation of Customer Name:
The JavaScript function autoGenerateCustomerName has been removed because the customer name is now manually inputted.
The customer_name input field is now a standard text input without the readonly attribute.
Updated Server-Side Validation:
Added validation to ensure that the customer_name field is not empty.
Removed the logic related to generating the customer_name based on the contact number.
Enhanced Contact Number UX:
The contact number input now consists of a country selector and a flexible text input for the number.
Validation remains strict to ensure that only valid characters are entered, but it allows for greater flexibility in formatting.
For even better UX, you might consider integrating a library like intl-tel-input in the future.
Improved Code Comments and Structure:
Added comments to highlight major sections and changes for easier maintenance.
Minor UI Enhancements:
Kept the existing styling and layout for a consistent look and feel.
Ensured that dynamic elements like adding/removing product rows work seamlessly with the new form structure.
Optional Enhancements:
Integrate a Better Phone Input Library:
If you'd like to further enhance the contact number UX, consider using a library like intl-tel-input. This library provides a more user-friendly interface for entering international telephone numbers, automatically handling country codes, formatting, and validation.
<script>
const phoneInputField = document.querySelector("#contact");
const phoneInput = window.intlTelInput(phoneInputField, {
separateDialCode: true,
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js", // just for formatting/placeholders etc
});
// Update the country selector when the user selects a country from the dropdown
const countrySelect = document.getElementById('country');
countrySelect.addEventListener('change', function() {
const selectedCode = this.value.replace(/\D/g, '');
phoneInput.setCountry(selectedCode);
});
// Optional: Validate the phone number on form submission
const form = document.querySelector("form");
form.addEventListener('submit', function(e) {
if (!phoneInput.isValidNumber()) {
e.preventDefault();
alert("Please enter a valid phone number.");
}
});
</script>
Final Notes:
Security:
Ensure that all user inputs are properly sanitized and validated to prevent SQL injection and other security vulnerabilities.
Consider using more robust validation libraries or frameworks for enhanced security and usability.
User Experience:
Always aim for a balance between flexibility and validation to provide a smooth user experience without compromising data integrity.
Consider providing real-time feedback for form validations to guide users as they fill out the form.
Code Maintenance:
Keep your code modular and well-commented to facilitate easier maintenance and future enhancements.
Regularly update libraries and dependencies to leverage new features and security patches.
Feel free to further customize the styles and functionalities as per your specific requirements. Let me know if you need any more assistance!
Adjust the HTML Structure:
Modify the country selector to work in tandem with intl-tel-input, possibly removing the manual country dropdown if using the library's built-in country selection.