// 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
];
Assistant
// Fetch products for selection
productssql="SELECT∗FROMproductsORDERBYnameASC";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
selected_country = sanitize_input(POST[′country′]??′+965′);contact_input = sanitize_input(POST[′contactdelivery_address = sanitize_input($_POST['delivery_address'] ?? '');
code
// 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
$customer_name = 'Order_' . $contact_digits;
}
$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! Improving the layout and user experience of the contact number section is a great idea. Below is the updated full PHP code with enhancements to the contact number layout. The improvements include:
Bootstrap Input Group: Utilizes Bootstrap's input group to seamlessly integrate the country selector with the contact number input field.
Responsive Design: Ensures that the contact number section adapts well to different screen sizes.
Input Masking: Implements input masking using the Inputmask library to ensure users enter valid phone numbers.
Enhanced Styling: Applies additional CSS to make the contact number section more visually appealing.
To ensure users enter valid phone numbers, the Inputmask library is integrated.
Different masks are applied based on the selected country code. This example includes masks for the Bahamas (+1-242) and Kuwait (+965). You can extend this with additional countries as needed.
javascript
Additional Recommendations
Comprehensive Country Masks:
For a real-world application, consider integrating a more comprehensive library or service that provides accurate phone number formats for all countries.
Libraries like libphonenumber can be integrated for more robust validation.
Flag Icons:
Enhance user experience by displaying flag icons alongside country names in the country selector. Libraries like Flag Icon CSS can be integrated for this purpose.
Accessibility:
Ensure that all form elements are accessible by properly labeling them and ensuring keyboard navigability.
Security Enhancements:
Always validate and sanitize user inputs on both client and server sides to prevent security vulnerabilities like SQL injection and XSS attacks.
By implementing these enhancements, the contact number section will not only look better but also provide a more intuitive and user-friendly experience for your users.
The customer name is automatically generated based on the contact number. This field is now set to readonly to prevent manual edits, ensuring consistency.
html
<label class="form-label" for="customer_name">Customer Name <span class="text-danger">*</span></label>
<input type="text" id="customer_name" name="customer_name" class="form-control"
value="<?= htmlspecialchars($customer_name ?? '') ?>"
required placeholder="Auto-generated based on contact number" readonly>
JavaScript Enhancements:
JavaScript ensures that the input mask updates dynamically when the user selects a different country.
Additionally, the customer name auto-generation function remains intact and works seamlessly with the enhanced contact number section.
javascript
// Apply Input Mask on Country Change
countrySelect.addEventListener('change', applyInputMask);