Explore / Programming based on this info database (-- phpMyAdmin SQL Dump -- version 5.2.1 --… Save Share Download ▾ Reportbased on this info database (-- phpMyAdmin SQL Dump
-- version 5.2.1
-- https://www.phpmyadmin.net/
-- Host: 127.0.0.1:3306
-- Generation Time: Nov 12, 2024 at 05:40 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,
tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Show full message · 1,849 lines Assistant2024-11-12 18:41 UTC Copy response
Copy first prompt
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Nov 12, 2024
Added to archive Nov 17, 2026
ID 01m7h427xw5aryhhzy0cwkcv43Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 802a5593f1e12992235ab588c2e6ec2b
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
is_star
--
-- 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
) 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 */;) when i add new 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);
// 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()
// Initialize variables
s u c c e s s = ′ ′ ; success = '';
s u ccess = ′′ ; error = '';
// 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);
if (!products_result) {
die("Error fetching products: " . conn->error);
}
// Handle form submission
if (_SERVER['REQUEST_METHOD'] == 'POST') {
// Sanitize and validate input
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 delivery_datetime = isset(_POST['delivery_datetime']) && !empty( _POST['delivery_datetime']) ? sanitize_input(P O S T [ ′ d e l i v e r y d a t e t i m e ′ ] ) : n u l l ; _POST['delivery_datetime']) : null;
P O S T [ ′ d e l i v er y priority = isset(P O S T [ ′ p r i o r i t y ′ ] ) ? s a n i t i z e i n p u t ( _POST['priority']) ? sanitize_input( P O S T [ ′ p r i or i t y _POST['priority']) : 'Normal';
code Copy code
// Validate priority
$valid_priorities = ['Normal', 'Important', 'Quick'];
if (!in_array($priority, $valid_priorities)) {
$priority = 'Normal';
}
// Handle multiple products
$product_ids = isset($_POST['product_id']) ? $_POST['product_id'] : [];
$quantities = isset($_POST['quantity']) ? $_POST['quantity'] : [];
$packaging_preferences = isset($_POST['packaging_preferences']) ? $_POST['packaging_preferences'] : [];
$apply_discount = isset($_POST['apply_discount']) ? $_POST['apply_discount'] : [];
$discount_percentages = isset($_POST['discount_percentage']) ? $_POST['discount_percentage'] : [];
$discount_reasons = isset($_POST['discount_reason']) ? $_POST['discount_reason'] : [];
// Basic validation
if (empty($customer_name)) {
$error = "Customer name 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
if ($delivery_datetime && !preg_match("/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/", $delivery_datetime)) {
$error = "Invalid delivery date and time format.";
} elseif ($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 (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
$status = 'Pending'; // Default status
$stmt = $conn->prepare("INSERT INTO orders (customer_id, status, priority, delivery_datetime) VALUES (?, ?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("isss", $customer_id, $status, $priority, $delivery_datetime);
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]);
}
// Corrected bind_param types: "iiisds"
$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';
?>
code Copy code
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&family=Roboto:wght@400;500;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">
<!-- Flatpickr CSS for Date Picker -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<!-- Custom Styles -->
<style>
/* ---------------------------------------------------
1. CSS Variables for Consistent Design
---------------------------------------------------- */
:root {
/* Primary Colors */
--background-color: #FFFFFF; /* Crisp White */
--light-grey: #F5F5F5;
--medium-grey: #E0E0E0;
--dark-grey: #333333;
--charcoal: #4A4A4A;
/* Accent Colors */
--accent-purple: #8A65FF;
--accent-yellow: #FFD166;
--accent-blue: #4A90E2;
--accent-green: #50C878;
--accent-red: #FF6B6B;
/* Text Colors */
--primary-text: var(--dark-grey);
--secondary-text: #666666;
/* UI Elements */
--input-border: var(--medium-grey);
--input-focus-border: var(--accent-blue);
--box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
--box-border-radius: 12px;
--hover-shadow: rgba(0, 0, 0, 0.1);
/* Button Colors */
--button-primary: var(--accent-purple);
--button-secondary: var(--accent-blue);
--button-danger: var(--accent-red);
/* Status Badge Colors */
--badge-pending: #FFD166; /* Yellow */
--badge-in-progress: #8A65FF; /* Purple */
--badge-completed: #50C878; /* Green */
--badge-delivered: #4A90E2; /* Blue */
}
/* Custom scrollbar for better UX */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f5f9; /* Tailwind's gray-100 */
}
::-webkit-scrollbar-thumb {
background: #4b6584; /* Teal-500 */
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #0d9488; /* Teal-600 */
}
/* ---------------------------------------------------
2. Global Styles
---------------------------------------------------- */
body {
font-family: 'Roboto', sans-serif;
background-color: var(--light-grey);
margin: 0;
padding: 0;
color: var(--primary-text);
}
.container-body {
max-width: 1200px;
margin: 40px auto;
padding: 40px 20px;
box-sizing: border-box;
background-color: var(--background-color);
box-shadow: var(--box-shadow);
border-radius: var(--box-border-radius);
font-family: 'Roboto', sans-serif;
transition: all 0.3s ease;
}
/* ---------------------------------------------------
3. Header Styles
---------------------------------------------------- */
.header {
padding: 20px 30px;
background-color: var(--background-color);
display: flex;
align-items: center;
justify-content: center; /* Center the content */
margin-bottom: 30px;
border-bottom: 1px solid var(--light-grey);
}
.header h1 {
color: var(--charcoal);
font-size: 32px;
font-weight: 700;
font-family: 'Poppins', sans-serif;
display: flex;
align-items: center;
justify-content: center;
}
.header h1 i {
margin-right: 10px;
font-size: 28px;
color: var(--accent-purple);
}
/* ---------------------------------------------------
4. Welcome Section
---------------------------------------------------- */
.welcome-section {
background-color: var(--background-color);
box-shadow: var(--box-shadow);
border-radius: var(--box-border-radius);
padding: 30px;
text-align: center;
margin-bottom: 30px;
font-family: 'Poppins', sans-serif;
}
.welcome-section h3 {
font-size: 28px;
color: var(--primary-text);
margin-bottom: 10px;
font-weight: 700;
display: none; /* Removed "Add New Order" from welcome section */
}
.welcome-section p {
font-size: 16px;
color: var(--secondary-text);
margin: 0;
}
/* Decorative Line Under Welcome Section */
.welcome-section::after {
content: "";
display: block;
width: 80px;
height: 4px;
background: linear-gradient(90deg, var(--accent-blue), var(--accent-purple));
margin: 15px auto 0;
border-radius: 2px;
}
/* ---------------------------------------------------
5. Form Container Styles
---------------------------------------------------- */
.form-container {
background-color: var(--background-color);
box-shadow: var(--box-shadow);
border-radius: var(--box-border-radius);
padding: 30px;
max-width: 900px;
margin: auto;
font-family: 'Roboto', sans-serif;
}
.form-container h3 {
text-align: center;
margin-bottom: 30px;
color: var(--accent-blue);
font-family: 'Poppins', sans-serif;
font-size: 28px;
font-weight: 700;
}
/* ---------------------------------------------------
6. Form Styles
---------------------------------------------------- */
.form-control {
border-radius: var(--box-border-radius);
border: 1px solid var(--input-border);
background-color: #ffffff;
padding: 12px;
box-shadow: var(--box-shadow);
transition: border-color 0.3s, box-shadow 0.3s;
width: 100%;
margin-bottom: 20px;
font-family: 'Roboto', sans-serif;
color: var(--primary-text);
font-size: 16px;
}
.form-control::placeholder {
color: #AAAAAA;
font-style: italic;
}
.form-control:focus {
border-color: var(--accent-blue);
box-shadow: 0 0 5px var(--accent-blue);
outline: none;
}
.form-label {
margin-bottom: 5px;
font-size: 14px;
text-align: left;
font-family: 'Poppins', sans-serif;
font-weight: 600;
color: var(--secondary-text);
}
/* ---------------------------------------------------
7. Order Priority Styles
---------------------------------------------------- */
.order-priority {
display: flex;
gap: 25px;
margin-bottom: 25px;
flex-wrap: wrap;
}
.order-priority label {
cursor: pointer;
position: relative;
padding-left: 35px;
user-select: none;
font-weight: 600;
transition: color 0.3s;
font-family: 'Poppins', sans-serif;
color: var(--secondary-text);
}
.order-priority input[type="radio"] {
position: absolute;
opacity: 0;
cursor: pointer;
}
.order-priority .custom-radio {
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
height: 20px;
width: 20px;
background-color: #fff;
border: 2px solid var(--input-border);
border-radius: 50%;
transition: background-color 0.3s, border-color 0.3s;
}
.order-priority label:hover input ~ .custom-radio {
border-color: var(--accent-blue);
}
.order-priority input:checked ~ .custom-radio {
background-color: var(--accent-blue);
border-color: var(--accent-blue);
}
.order-priority .custom-radio::after {
content: "";
position: absolute;
display: none;
}
.order-priority input:checked ~ .custom-radio::after {
display: block;
}
.order-priority .custom-radio::after {
top: 6px;
left: 6px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
}
/* ---------------------------------------------------
8. Buttons Section
---------------------------------------------------- */
.add-product-button,
.remove-product-button,
.submit-button {
border: none;
border-radius: 50px; /* Pill-shaped */
padding: 10px 20px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s, transform 0.3s, box-shadow 0.3s;
font-family: 'Poppins', sans-serif;
display: flex;
align-items: center;
gap: 8px;
}
.add-product-button {
background-color: var(--accent-purple);
color: #ffffff;
margin-top: 10px;
}
.add-product-button:hover {
background-color: #7e5aff;
transform: scale(1.05);
box-shadow: 0 4px 12px var(--hover-shadow);
}
.remove-product-button {
background-color: var(--button-danger);
color: #ffffff;
}
.remove-product-button:hover {
background-color: #e63946;
transform: scale(1.05);
box-shadow: 0 4px 12px var(--hover-shadow);
}
.submit-button {
width: 100%;
height: 50px;
font-weight: bold;
background-color: var(--accent-blue);
color: #ffffff;
justify-content: center;
font-family: 'Poppins', sans-serif;
box-shadow: var(--box-shadow);
gap: 10px;
}
.submit-button:hover {
background-color: #357ABD;
transform: scale(1.02);
box-shadow: 0 4px 12px var(--hover-shadow);
}
/* ---------------------------------------------------
9. Alert Styles
---------------------------------------------------- */
.alert-success,
.alert-danger {
border-radius: var(--box-border-radius);
padding: 15px 20px;
margin-bottom: 20px;
text-align: center;
width: 100%;
margin: 20px auto;
font-family: 'Poppins', sans-serif;
font-size: 16px;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
}
.alert-success {
background-color: var(--badge-completed);
color: #ffffff;
}
.alert-danger {
background-color: var(--badge-delivered);
color: #ffffff;
}
/* ---------------------------------------------------
10. Footer Styles
---------------------------------------------------- */
.footer {
background-color: var(--background-color);
color: var(--secondary-text);
padding: 20px;
text-align: center;
border-radius: var(--box-border-radius);
font-size: 14px;
line-height: 22px;
margin-top: 40px;
font-family: 'Roboto', sans-serif;
box-shadow: var(--box-shadow);
}
/* ---------------------------------------------------
11. Responsive Design Enhancements
---------------------------------------------------- */
@media (max-width: 768px) {
.header h1 {
font-size: 24px;
}
.welcome-section h3 {
font-size: 24px;
}
.form-container h3 {
font-size: 24px;
}
.action-button {
flex: 1 1 100%;
height: 50px;
font-size: 14px;
}
.form-control {
font-size: 14px;
}
.form-label {
font-size: 13px;
}
.submit-button {
height: 50px;
font-size: 16px;
}
}
@media (max-width: 480px) {
.container-body {
padding: 20px 10px;
}
.header h1 {
font-size: 20px;
}
.welcome-section h3 {
font-size: 20px;
}
.form-container h3 {
font-size: 20px;
}
.form-control {
font-size: 13px;
}
.form-label {
font-size: 12px;
}
.submit-button {
height: 45px;
font-size: 14px;
}
.order-priority {
flex-direction: column;
}
}
/* ---------------------------------------------------
12. Additional Styles for Enhanced UI
---------------------------------------------------- */
/* Card Styles for Product Rows */
.product-row {
background-color: var(--light-grey);
border: 1px solid var(--input-border);
border-radius: var(--box-border-radius);
padding: 20px;
position: relative;
transition: transform 0.3s, box-shadow 0.3s;
}
.product-row:hover {
transform: translateY(-5px);
box-shadow: 0 4px 16px var(--hover-shadow);
}
/* Icon Styles */
.icon-primary {
color: var(--accent-purple);
font-size: 20px;
}
/* Transition for discount fields */
.discount-fields {
transition: all 0.3s ease-in-out;
}
</style>
<!-- Additional JavaScript for dynamic product addition and discount handling -->
<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 mb-3';
productRow.innerHTML = `
<div class="row">
<div class="col-md-4">
<label class="form-label" for="product_id_${productCount}">Product <span class="text-danger">*</span></label>
<select name="product_id[]" id="product_id_${productCount}" class="form-control" 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 class="col-md-2">
<label class="form-label" for="quantity_${productCount}">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity[]" id="quantity_${productCount}" class="form-control" min="1" value="1" required>
</div>
<div class="col-md-3">
<label class="form-label" for="packaging_preferences_${productCount}">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_${productCount}" class="form-control" placeholder="e.g., Gift Wrap">
</div>
<div class="col-md-3">
<label class="form-label" for="discount_${productCount}">Apply Discount</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_${productCount}" name="apply_discount[]">
<label class="form-check-label" for="discount_checkbox_${productCount}">
Yes
</label>
</div>
<div id="discount_fields_${productCount}" class="discount-fields" style="display: none; margin-top: 10px;">
<label class="form-label" for="discount_percentage_${productCount}">Discount Percentage (%) <span class="text-danger">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_${productCount}" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
<label class="form-label mt-2" for="discount_reason_${productCount}">Discount Reason <span class="text-danger">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_${productCount}" class="form-control" placeholder="Enter reason for discount">
</div>
</div>
<div class="col-md-12 d-flex justify-content-end mt-3">
<button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
</div>
</div>
`;
productContainer.appendChild(productRow);
// Initialize discount toggle for the new row
const newCheckbox = productRow.querySelector(`input[name="apply_discount[]"]`);
newCheckbox.addEventListener('change', function() {
toggleDiscountFields(this, productCount);
});
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 = '');
}
}
// Add event listeners to existing discount checkboxes on page load
function initializeDiscountToggle() {
const discountCheckboxes = document.querySelectorAll('input[name="apply_discount[]"]');
discountCheckboxes.forEach((checkbox, index) => {
checkbox.addEventListener('change', function() {
toggleDiscountFields(this, index);
});
});
}
// 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 discount toggles
initializeDiscountToggle();
});
</script>
code Copy code
<main class='container-body'>
<!-- Header -->
<div class="header">
<h1><i class="bi bi-cart-plus"></i>Add New Order</h1>
<!-- You can add navigation or user info here -->
</div>
<!-- Welcome Section -->
<div class="welcome-section">
<p>Fill out the form below to add a new customer order.</p>
</div>
<!-- Form Container -->
<div class="form-container">
<?php if (!empty($error)): ?>
<div class="alert-danger d-flex align-items-center">
<i class="bi bi-exclamation-triangle-fill"></i> <?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>
<?php if (!empty($success)): ?>
<div class="alert-success d-flex align-items-center">
<i class="bi bi-check-circle-fill"></i> <?= htmlspecialchars($success) ?>
</div>
<?php endif; ?>
<form method="POST" action="add_order.php">
<!-- Customer Details -->
<div class="form-section">
<h5 class="mb-3">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" rows="3"><?= isset($_POST['delivery_address']) ? htmlspecialchars($_POST['delivery_address']) : '' ?></textarea>
</div>
<hr>
<!-- Order Details -->
<div class="form-section">
<h5 class="mb-3">Order Details</h5>
<!-- Priority Selection -->
<label class="form-label">Order Priority</label>
<div class="order-priority">
<label>
<input type="radio" name="priority" value="Normal" <?= (isset($_POST['priority']) && $_POST['priority'] === 'Normal') || !isset($_POST['priority']) ? 'checked' : '' ?>>
<span class="custom-radio"></span>
Normal (Default)
</label>
<label>
<input type="radio" name="priority" value="Important" <?= isset($_POST['priority']) && $_POST['priority'] === 'Important' ? 'checked' : '' ?>>
<span class="custom-radio"></span>
Important
</label>
<label>
<input type="radio" name="priority" value="Quick" <?= isset($_POST['priority']) && $_POST['priority'] === 'Quick' ? 'checked' : '' ?>>
<span class="custom-radio"></span>
Quick
</label>
</div>
<!-- Products Selection -->
<div id="products-container">
<!-- Product Rows will be added here -->
<?php
// If form was submitted with errors, repopulate the product rows
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($error) && !empty($product_ids) && is_array($product_ids)) {
foreach ($product_ids as $i => $pid) {
?>
<div class="product-row mb-3">
<div class="row">
<div class="col-md-4">
<label class="form-label" for="product_id_<?= $i ?>">Product <span class="text-danger">*</span></label>
<select name="product_id[]" id="product_id_<?= $i ?>" class="form-control" required>
<option value="">Select Product</option>
<?php
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()):
$selected = ($product['id'] == $pid) ? 'selected' : '';
?>
<option value="<?= htmlspecialchars($product['id']) ?>" <?= $selected ?>>
<?= htmlspecialchars($product['name'] . " - " . $product['size'] . " (" . number_format($product['price'], 2) . " KD)") ?>
</option>
<?php endwhile; ?>
</select>
</div>
<div class="col-md-2">
<label class="form-label" for="quantity_<?= $i ?>">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity[]" id="quantity_<?= $i ?>" class="form-control" min="1" value="<?= isset($quantities[$i]) ? intval($quantities[$i]) : '1' ?>" required>
</div>
<div class="col-md-3">
<label class="form-label" for="packaging_preferences_<?= $i ?>">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_<?= $i ?>" class="form-control" placeholder="e.g., Gift Wrap" value="<?= isset($packaging_preferences[$i]) ? htmlspecialchars($packaging_preferences[$i]) : '' ?>">
</div>
<div class="col-md-3">
<label class="form-label" for="discount_<?= $i ?>">Apply Discount</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_<?= $i ?>" name="apply_discount[]" <?= isset($apply_discount[$i]) ? 'checked' : '' ?>>
<label class="form-check-label" for="discount_checkbox_<?= $i ?>">
Yes
</label>
</div>
<div id="discount_fields_<?= $i ?>" class="discount-fields" style="display: <?= isset($apply_discount[$i]) ? 'block' : 'none' ?>; margin-top: 10px;">
<label class="form-label" for="discount_percentage_<?= $i ?>">Discount Percentage (%) <span class="text-danger">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_<?= $i ?>" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage" value="<?= isset($discount_percentages[$i]) ? htmlspecialchars($discount_percentages[$i]) : '' ?>">
<label class="form-label mt-2" for="discount_reason_<?= $i ?>">Discount Reason <span class="text-danger">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_<?= $i ?>" class="form-control" placeholder="Enter reason for discount" value="<?= isset($discount_reasons[$i]) ? htmlspecialchars($discount_reasons[$i]) : '' ?>">
</div>
</div>
<div class="col-md-12 d-flex justify-content-end mt-3">
<button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
</div>
</div>
</div>
<?php
}
} else {
// Add one default product row
?>
<div class="product-row mb-3">
<div class="row">
<div class="col-md-4">
<label class="form-label" for="product_id_0">Product <span class="text-danger">*</span></label>
<select name="product_id[]" id="product_id_0" class="form-control" required>
<option value="">Select Product</option>
<?php
$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 class="col-md-2">
<label class="form-label" for="quantity_0">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity[]" id="quantity_0" class="form-control" min="1" value="1" required>
</div>
<div class="col-md-3">
<label class="form-label" for="packaging_preferences_0">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_0" class="form-control" placeholder="e.g., Gift Wrap">
</div>
<div class="col-md-3">
<label class="form-label" for="discount_0">Apply Discount</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="discount_checkbox_0" name="apply_discount[]">
<label class="form-check-label" for="discount_checkbox_0">
Yes
</label>
</div>
<div id="discount_fields_0" class="discount-fields" style="display: none; margin-top: 10px;">
<label class="form-label" for="discount_percentage_0">Discount Percentage (%) <span class="text-danger">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_0" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
<label class="form-label mt-2" for="discount_reason_0">Discount Reason <span class="text-danger">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_0" class="form-control" placeholder="Enter reason for discount">
</div>
</div>
<div class="col-md-12 d-flex justify-content-end mt-3">
<button type="button" class="remove-product-button btn btn-danger btn-sm" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
</div>
</div>
</div>
<?php
}
?>
</div>
<button type="button" class="add-product-button btn btn-secondary" onclick="addProductRow()"><i class="bi bi-plus-circle-fill"></i> Add Another Product</button>
<!-- Delivery DateTime Field -->
<hr>
<div class="form-section">
<h5 class="mb-3">Delivery Details</h5>
<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="<?= isset($_POST['delivery_datetime']) ? htmlspecialchars($_POST['delivery_datetime']) : '' ?>">
</div>
</div>
<!-- Submit Button -->
<button type="submit" class="submit-button btn btn-primary"><i class="bi bi-plus-lg"></i> Add Order</button>
</form>
</div>
<!-- Footer -->
<div class="footer">
© 2024 Kaak Alia Bakery. All rights reserved.
</div>
</main>
<!-- Bootstrap JS Bundle -->
<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"
});
</script>
<!-- Bootstrap Tooltip Initialization -->
<script>
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>
// Enable error reporting for debugging (Remove or comment out in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include authentication and database connection
require_once DIR . '/auth.php';
require_once DIR . '/db_connect.php';
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
u s e r i d = user_id = u se r i d = _SESSION['user_id'];
$last_order_id = 0;
// Fetch the last pending order ID to initialize polling
i n i t i a l p e n d i n g s q l = " S E L E C T o . i d F R O M o r d e r s o W H E R E o . s t a t u s = ′ P e n d i n g ′ O R D E R B Y o . i d D E S C L I M I T 1 " ; initial_pending_sql = "
SELECT o.id
FROM orders o
WHERE o.status = 'Pending'
ORDER BY o.id DESC
LIMIT 1
";
ini t ia l p e n d in g s q l = " S E L E C T o . i d F R O M or d er so W H E R E o . s t a t u s = ′ P e n d in g ′ O R D E R B Y o . i d D E S C L I M I T 1" ; initial_result = c o n n − > q u e r y ( conn->query( co nn − > q u er y ( initial_pending_sql);
if (initial_result && initial_result->num_rows > 0) {
r o w = row = r o w = initial_result->fetch_assoc();
l a s t o r d e r i d = i n t v a l ( last_order_id = intval( l a s t o r d e r i d = in t v a l ( row['id']);
}
// Fetch the logged-in user's profile information
u s e r n a m e = ′ U s e r ′ ; / / D e f a u l t u s e r n a m e username = 'User'; // Default username
u ser nam e = ′ U se r ′ ; // D e f a u l t u ser nam e profile_image = '/assets/images/user-placeholder.png'; // Default profile image
s t m t = stmt = s t m t = conn->prepare("SELECT username, profile_image FROM users WHERE id = ?");
if (stmt) {
stmt->bind_param("i", u s e r i d ) ; user_id);
u se r i d ) ; stmt->execute();
r e s u l t u s e r = result_user = r es u l t u ser = stmt->get_result();
if (result_user && result_user->num_rows === 1) {
u s e r = user = u ser = result_user->fetch_assoc();
u s e r n a m e = h t m l s p e c i a l c h a r s ( username = htmlspecialchars( u ser nam e = h t m l s p ec ia l c ha r s ( user['username'], ENT_QUOTES, 'UTF-8');
if (!empty(user['profile_image']) && file_exists(__DIR__ . '/../' . user['profile_image'])) {
// Append file modification time to prevent caching
mod_time = filemtime(__DIR__ . '/../' . user['profile_image']);
p r o f i l e i m a g e = ′ / ′ . h t m l s p e c i a l c h a r s ( profile_image = '/' . htmlspecialchars( p r o f i l e i ma g e = ′ user['profile_image'], ENT_QUOTES, 'UTF-8') . '?v=' . mod_time;
}
}
stmt->close();
} else {
// Log error or handle accordingly
error_log("Failed to prepare statement for fetching user data.");
}
?>
code Copy code
<!-- Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<!-- Bootstrap JS Bundle with Popper (Loaded Defer for Performance) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" defer></script>
<!-- Alpine.js for Interactivity -->
<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.10.3/dist/cdn.min.js" defer></script>
<!-- Custom Styles for Notification Links -->
<style>
.notification-link {
display: block;
color: inherit;
text-decoration: none;
}
.notification-link:hover {
background-color: #4a5568; /* Tailwind's gray-700 */
}
.notification-badge {
position: absolute;
top: 0;
right: 0;
width: 0.75rem;
height: 0.75rem;
background-color: #f56565; /* Tailwind's red-500 */
border-radius: 9999px;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { transform: scale(0.75); opacity: 1; }
50% { transform: scale(1.25); opacity: 0.5; }
}
</style>
code Copy code
<!-- Audio Element for New Order Alert -->
<audio id="newOrderAudio" src="/assets/audio/you_have_a_new_order.mp3" preload="auto"></audio>
<!-- Header -->
<header class="bg-gray-800 text-white py-4 border-b-4 border-yellow-400 shadow-lg top-0 left-0 right-0 z-50">
<div class="container mx-auto px-4 flex justify-between items-center">
<!-- Logo -->
<div class="flex items-center">
<a href="/public/dashboard.php" class="flex items-center">
<img src="/assets/img/logo.png" alt="Kaak Alia Logo" class="h-12 w-auto mr-2">
<span class="text-xl font-bold">Admin Panel</span>
</a>
</div>
<!-- Navigation Links (Desktop) -->
<nav class="hidden md:flex space-x-4">
<a href="/public/orders/add_order.php" class="flex items-center bg-yellow-400 text-gray-800 px-4 py-2 rounded-lg hover:bg-yellow-300 shadow transition-all duration-300">
<i class="bi bi-plus-circle-fill mr-2"></i> Add Order
</a>
<a href="/public/orders/view_orders.php" class="flex items-center bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-400 shadow transition-all duration-300">
<i class="bi bi-eye-fill mr-2"></i> View Orders
</a>
<a href="/public/products/manage_products.php" class="flex items-center bg-green-400 text-white px-4 py-2 rounded-lg hover:bg-green-300 shadow transition-all duration-300">
<i class="bi bi-box-seam-fill mr-2"></i> Manage Products
</a>
<a href="/public/users/manage_users.php" class="flex items-center bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-400 shadow transition-all duration-300">
<i class="bi bi-people-fill mr-2"></i> Manage Users
</a>
<a href="/public/reports/generate_reports.php" class="flex items-center bg-pink-500 text-white px-4 py-2 rounded-lg hover:bg-pink-400 shadow transition-all duration-300">
<i class="bi bi-bar-chart-fill mr-2"></i> Reports
</a>
</nav>
<!-- Right Side Icons -->
<div class="flex items-center space-x-4">
<!-- Notifications Dropdown -->
<div class="relative" x-data="{ open: false }">
<button @click="open = !open" class="relative text-white hover:text-yellow-400 focus:outline-none" aria-haspopup="true" aria-expanded="false" aria-controls="notification-menu" aria-label="Notifications">
<i class="bi bi-bell-fill text-2xl"></i>
<?php if ($last_order_id > 0): ?>
<!-- Notification Badge -->
<span class="absolute top-0 right-0 inline-block w-3 h-3 bg-red-500 rounded-full"></span>
<?php endif; ?>
</button>
<!-- Dropdown Menu -->
<div x-show="open" @click.away="open = false" id="notification-menu" class="absolute right-0 mt-2 w-80 bg-gray-800 text-white rounded-lg shadow-lg z-50">
<div class="py-2 px-4 border-b border-yellow-400">
<h3 class="text-lg font-semibold">Notifications</h3>
</div>
<ul class="max-h-64 overflow-y-auto" id="notificationsList">
<?php
// Fetch the latest 5 pending orders with their items
$notifications_sql = "
SELECT DISTINCT o.id, o.order_date, c.name AS customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'Pending'
ORDER BY o.id DESC
LIMIT 5
";
$notifications_result = $conn->query($notifications_sql);
if ($notifications_result && $notifications_result->num_rows > 0):
while($notification = $notifications_result->fetch_assoc()):
?>
<li class="px-4 py-2 hover:bg-gray-700 cursor-pointer">
<a href="/public/orders/view_order_customer.php?order_id=<?= htmlspecialchars($notification['id'], ENT_QUOTES, 'UTF-8') ?>" class="notification-link flex items-center">
<span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
New Order: <?= htmlspecialchars($notification['customer_name'], ENT_QUOTES, 'UTF-8'); ?> placed on <?= date("d M Y, h:i A", strtotime($notification['order_date'])) ?>
</a>
</li>
<?php
endwhile;
else:
?>
<li class="px-4 py-2 text-gray-400">No new notifications</li>
<?php endif; ?>
</ul>
<div class="py-2 px-4 border-t border-yellow-400 text-center">
<a href="/public/notifications.php" class="text-yellow-400 hover:underline">View All</a>
</div>
</div>
</div>
<!-- User Profile Dropdown -->
<div class="relative" x-data="{ open: false }">
<button @click="open = !open" class="flex items-center focus:outline-none" aria-haspopup="true" aria-expanded="false" aria-controls="profile-menu">
<img src="<?= $profile_image ?>" alt="User Avatar" class="h-10 w-10 rounded-full border-2 border-white hover:border-yellow-400 transition-colors duration-300">
<span class="ml-2 hidden lg:inline-block">
<?= $username ?>
</span>
<i class="bi bi-caret-down-fill ml-1 hidden lg:inline-block"></i>
</button>
<!-- Dropdown Menu -->
<div x-show="open" @click.away="open = false" id="profile-menu" class="absolute right-0 mt-2 w-48 bg-gray-800 text-white rounded-lg shadow-lg z-50">
<a href="/public/workspace/index.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-laptop mr-2"></i> WorkSpace
</a>
<a href="/public/drivers/drivers_list.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-car-front mr-2"></i> Drivers
</a>
<a href="/includes/user_settings.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-gear-fill mr-2"></i> Settings
</a>
<a href="/public/about_kaakalia/index_en.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-info-circle mr-2"></i> About Kaak Alia
</a>
<a href="/public/logout.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-box-arrow-right mr-2"></i> Logout
</a>
</div>
</div>
<!-- Mobile Menu Button -->
<div class="md:hidden">
<button id="mobile-menu-button" class="text-white focus:outline-none" aria-label="Toggle Mobile Menu">
<i class="bi bi-list text-2xl"></i>
</button>
</div>
</div>
</div>
<!-- Mobile Navigation Menu -->
<nav id="mobile-menu" class="hidden md:hidden mt-4">
<ul class="flex flex-col space-y-2">
<li>
<a href="/public/orders/add_order.php" class="flex items-center bg-yellow-400 text-gray-800 px-4 py-2 rounded-lg hover:bg-yellow-300 transition-all duration-300">
<i class="bi bi-plus-circle-fill mr-2"></i> Add Order
</a>
</li>
<li>
<a href="/public/orders/view_orders.php" class="flex items-center bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-400 transition-all duration-300">
<i class="bi bi-eye-fill mr-2"></i> View Orders
</a>
</li>
<li>
<a href="/public/products/manage_products.php" class="flex items-center bg-green-400 text-white px-4 py-2 rounded-lg hover:bg-green-300 transition-all duration-300">
<i class="bi bi-box-seam-fill mr-2"></i> Manage Products
</a>
</li>
<li>
<a href="/public/users/manage_users.php" class="flex items-center bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-400 transition-all duration-300">
<i class="bi bi-people-fill mr-2"></i> Manage Users
</a>
</li>
<li>
<a href="/public/reports/generate_reports.php" class="flex items-center bg-pink-500 text-white px-4 py-2 rounded-lg hover:bg-pink-400 transition-all duration-300">
<i class="bi bi-bar-chart-fill mr-2"></i> Reports
</a>
</li>
<!-- Additional Mobile Links -->
<li>
<a href="/public/notifications.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
<i class="bi bi-bell-fill mr-2"></i> Notifications
</a>
</li>
<li>
<a href="/includes/user_settings.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
<i class="bi bi-gear-fill mr-2"></i> Settings
</a>
</li>
<li>
<a href="/public/about_kaakalia/index.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
<i class="bi bi-info-circle mr-2"></i> About Kaak Alia
</a>
</li>
</ul>
</nav>
</header>
<!-- JavaScript for Real-Time Notifications and Mobile Menu Toggle -->
<script>
document.addEventListener('DOMContentLoaded', function() {
const mobileMenuButton = document.getElementById('mobile-menu-button');
const mobileMenu = document.getElementById('mobile-menu');
// Toggle mobile menu on button click
mobileMenuButton.addEventListener('click', function() {
mobileMenu.classList.toggle('hidden');
});
let lastOrderId = <?= $last_order_id ?>;
const audio = document.getElementById('newOrderAudio');
// Function to fetch new orders
function fetchNewOrders() {
fetch(`/includes/get_new_orders.php?last_order_id=${lastOrderId}`)
.then(response => response.json())
.then(data => {
if (data.orders && data.orders.length > 0) {
data.orders.forEach(order => {
// Update lastOrderId if needed
if (order.id > lastOrderId) {
lastOrderId = order.id;
}
// Create a new notification item
const notificationsList = document.getElementById('notificationsList');
const li = document.createElement('li');
li.className = 'px-4 py-2 hover:bg-gray-700 cursor-pointer';
// Create a link to the order details page
const a = document.createElement('a');
a.href = `/public/orders/view_order_customer.php?order_id=${encodeURIComponent(order.id)}`;
a.className = 'notification-link flex items-center';
a.innerHTML = `
<span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
New Order: ${sanitizeHTML(order.customer_name)} placed on ${sanitizeHTML(order.order_date)}
`;
li.appendChild(a);
// Insert the new notification at the top
notificationsList.insertBefore(li, notificationsList.firstChild);
// Play the audio alert
if (audio) {
audio.play().catch(function(error) {
console.log('Audio playback failed:', error);
});
}
// Optionally, update the notification badge
const bellIcon = document.querySelector('header .bi-bell-fill');
const existingBadge = bellIcon.parentNode.querySelector('.notification-badge');
if (!existingBadge) {
const badge = document.createElement('span');
badge.className = 'notification-badge';
bellIcon.parentNode.appendChild(badge);
}
});
}
})
.catch(error => {
console.error('Error fetching new orders:', error);
});
}
// Function to sanitize HTML to prevent XSS
function sanitizeHTML(str) {
var temp = document.createElement('div');
temp.textContent = str;
return temp.innerHTML;
}
// Poll every 10 seconds for new orders
setInterval(fetchNewOrders, 10000); // 10000 ms = 10 seconds
// Fetch immediately on page load
fetchNewOrders();
});
</script>
// 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 'auth.php';
require_once 'db_connect.php';
// Get the last known order ID from the client
l a s t o r d e r i d = i s s e t ( last_order_id = isset( l a s t o r d e r i d = i sse t ( _GET['last_order_id']) ? intval($_GET['last_order_id']) : 0;
// Prepare the SQL to fetch new pending orders
$sql = "SELECT o.id, o.order_date, c.name AS customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'Pending' AND o.id > ?
ORDER BY o.id ASC";
s t m t = stmt = s t m t = conn->prepare(s q l ) ; i f ( ! sql);
if (! s q l ) ; i f ( ! stmt) {
http_response_code(500);
echo json_encode(['error' => 'Database error: ' . $conn->error]);
exit();
}
s t m t − > b i n d p a r a m ( " i " , stmt->bind_param("i", s t m t − > bin d p a r am ( " i " , last_order_id);
s t m t − > e x e c u t e ( ) ; stmt->execute();
s t m t − > e x ec u t e ( ) ; result = $stmt->get_result();
n e w o r d e r s = [ ] ; w h i l e ( new_orders = [];
while ( n e w o r d er s = [ ] ; w hi l e ( row = result->fetch_assoc()) {
new_orders[] = [
'id' => r o w [ ′ i d ′ ] , ′ o r d e r d a t e ′ = > row['id'],
'order_date' => r o w [ ′ i d ′ ] , ′ or d e r d a t e row['order_date'],
'customer_name' => htmlspecialchars($row['customer_name'], ENT_QUOTES, 'UTF-8')
];
}
// Return the new orders as JSON
header('Content-Type: application/json');
echo json_encode(['orders' => $new_orders]);
?>) so make it the audio is owkring well, and all users, when i add order, it plays the audio and other users (staff and admins) listen to this notifcaitoin, type full codes plz
To ensure that the notification audio plays correctly for all users (both staff and admins ) when a new order is added, it's essential to structure your PHP includes properly and ensure that the JavaScript responsible for playing the audio is correctly implemented. Below is a comprehensive guide with complete code snippets to achieve this functionality.
1. Project Structure Overview
Before diving into the code, it's crucial to have a clear understanding of your project structure to manage includes effectively. Here's a recommended structure:
code Copy code
/kaak_alia_management_system/
├── /public/
│ ├── /orders/
│ │ ├── add_order.php
│ │ └── view_orders.php
│ ├── dashboard.php
│ ├── login.php
│ └── logout.php
├── /includes/
│ ├── auth.php
│ ├── db_connect.php
│ ├── head.php
│ ├── header.php
│ ├── footer.php
│ └── get_new_orders.php
├── /assets/
│ ├── /audio/
│ │ └── you_have_a_new_order.mp3
│ ├── /bootstrap/
│ │ ├── css/
│ │ │ └── bootstrap.min.css
│ │ └── js/
│ │ └── bootstrap.bundle.min.js
│ └── /images/
│ └── user-placeholder.png
└── /assets/img/logo.png
2. includes/head.php
This file contains the opening HTML tags and links to CSS and JS resources. It should be included at the beginning of each page.
php Copy code
<?php
// includes/head.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Include authentication and database connection
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_connect.php';
// Redirect to login if user is not authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
// Fetch user information for header
$user_id = $_SESSION['user_id'];
$username = 'User'; // Default username
$profile_image = '/assets/images/user-placeholder.png'; // Default profile image
$stmt = $conn->prepare("SELECT username, profile_image FROM users WHERE id = ?");
if ($stmt) {
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result_user = $stmt->get_result();
if ($result_user && $result_user->num_rows === 1) {
$user = $result_user->fetch_assoc();
$username = htmlspecialchars($user['username'], ENT_QUOTES, 'UTF-8');
if (!empty($user['profile_image']) && file_exists(__DIR__ . '/../' . $user['profile_image'])) {
// Append file modification time to prevent caching
$mod_time = filemtime(__DIR__ . '/../' . $user['profile_image']);
$profile_image = '/' . htmlspecialchars($user['profile_image'], ENT_QUOTES, 'UTF-8') . '?v=' . $mod_time;
}
}
$stmt->close();
} else {
// Log error or handle accordingly
error_log("Failed to prepare statement for fetching user data.");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta Tags for Responsiveness and Accessibility -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kaak Alia Management System</title>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/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">
<!-- Flatpickr CSS for Date Picker -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<!-- Custom Styles -->
<link rel="stylesheet" href="/assets/css/custom.css">
<!-- Additional Custom Styles can be included here -->
</head>
<body class="bg-gray-100">
3. includes/header.php
This file contains the navigation bar and notification/audio elements. It should be included after head.php within the <body> tag of each page.
4. includes/footer.php
This file contains the footer content and includes necessary JavaScript files. It should be included at the end of each page.
php Copy code
<?php
// includes/footer.php
?>
<!-- Footer -->
<footer class="bg-gray-800 text-white py-4 border-t-4 border-yellow-400 shadow-lg mt-10">
<div class="container mx-auto text-center">
© 2024 Kaak Alia Bakery. All rights reserved.
</div>
</footer>
<!-- Bootstrap JS Bundle -->
<script src="/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"
});
</script>
<!-- Bootstrap Tooltip Initialization -->
<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>
5. includes/get_new_orders.php
This script fetches new pending orders and returns them as JSON. Ensure that this file is secure and only accessible to authenticated users.
php Copy code
<?php
// includes/get_new_orders.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Include authentication and database connection
require_once 'auth.php';
require_once 'db_connect.php';
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
exit();
}
// Get the last known order ID from the client
$last_order_id = isset($_GET['last_order_id']) ? intval($_GET['last_order_id']) : 0;
// Prepare the SQL to fetch new pending orders
$sql = "SELECT o.id, o.order_date, c.name AS customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'Pending' AND o.id > ?
ORDER BY o.id ASC";
$stmt = $conn->prepare($sql);
if (!$stmt) {
http_response_code(500);
echo json_encode(['error' => 'Database error: ' . $conn->error]);
exit();
}
$stmt->bind_param("i", $last_order_id);
$stmt->execute();
$result = $stmt->get_result();
$new_orders = [];
while ($row = $result->fetch_assoc()) {
$new_orders[] = [
'id' => $row['id'],
'order_date' => $row['order_date'],
'customer_name' => htmlspecialchars($row['customer_name'], ENT_QUOTES, 'UTF-8')
];
}
$stmt->close();
// Return the new orders as JSON
header('Content-Type: application/json');
echo json_encode(['orders' => $new_orders]);
exit();
?>
6. public/orders/add_order.php
Ensure that this file correctly includes the head.php, header.php, and footer.php files without duplicating HTML structures.
7. includes/get_new_orders.php
Ensure that this script correctly identifies and returns new orders. This file is already correctly implemented, but here's a refined version with additional security measures.
php Copy code
<?php
// includes/get_new_orders.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Include authentication and database connection
require_once 'auth.php';
require_once 'db_connect.php';
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
exit();
}
// Get the last known order ID from the client
$last_order_id = isset($_GET['last_order_id']) ? intval($_GET['last_order_id']) : 0;
// Prepare the SQL to fetch new pending orders
$sql = "SELECT o.id, o.order_date, c.name AS customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'Pending' AND o.id > ?
ORDER BY o.id ASC";
$stmt = $conn->prepare($sql);
if (!$stmt) {
http_response_code(500);
echo json_encode(['error' => 'Database error: ' . $conn->error]);
exit();
}
$stmt->bind_param("i", $last_order_id);
$stmt->execute();
$result = $stmt->get_result();
$new_orders = [];
while ($row = $result->fetch_assoc()) {
$new_orders[] = [
'id' => $row['id'],
'order_date' => $row['order_date'],
'customer_name' => htmlspecialchars($row['customer_name'], ENT_QUOTES, 'UTF-8')
];
}
$stmt->close();
// Return the new orders as JSON
header('Content-Type: application/json');
echo json_encode(['orders' => $new_orders]);
exit();
?>
8. JavaScript Enhancements
To ensure the audio notification works seamlessly across all modern browsers, it's vital to handle potential autoplay restrictions. Here's an enhanced version of the JavaScript in header.php to address these concerns:
Explanation of Enhancements:
Reset Audio Playback: Before playing the audio, audio.currentTime = 0; ensures that the audio plays from the start each time a new order is detected.
Handle Autoplay Restrictions:
Modern browsers often block autoplay of audio unless it's muted or has been initiated by user interaction.
The initializeAudio function attempts to play the audio muted on the first user interaction (click or keydown). This action typically unlocks the ability to play audio without restrictions.
Event listeners are added to the body to detect the first user interaction and initialize the audio.
9. Ensure Audio File Accessibility
Make sure that the audio file you_have_a_new_order.mp3 is placed in the correct directory with the appropriate permissions.
10. Testing the Notification System
After implementing the above changes, follow these steps to test the notification system:
Open Two Browser Windows:
Window 1: Log in as an admin or staff member.
Window 2: Log in as another admin or staff member.
Add a New Order:
In Window 1 , navigate to add_order.php and submit a new order.
Observe Notifications:
In Window 2 , within 10 seconds, you should see the new order appear in the notifications dropdown, and the audio notification should play automatically.
Audio Playback:
Ensure that the audio plays without requiring additional user interaction.
If audio doesn’t play, check the browser console for errors and verify that the audio file path is correct.
11. Additional Recommendations
12. Conclusion
By restructuring your PHP includes and ensuring that the audio file is correctly referenced and accessible, you can achieve a functional notification system where all users are alerted audibly when a new order is placed. The provided code snippets and explanations should help you implement this feature seamlessly in your Kaak Alia Management System.
If you encounter any issues during implementation, consider checking browser console logs for JavaScript errors, verifying file paths, and ensuring that all files have the correct permissions on your server.
Show full message · 1,081 lines Copy first response
Not yet included in a published release.
a
dd
r
es
s ′
])
;
d
a
t
e
t
im
e ′
])
:
n u l l ;
′
])?
s
ani
t
i
z
e i
n
p
u
t
(
/ ′
.
h
t
m
l
s
p
ec
ia
l
c
ha
r
s
(
′
=>
<?php
// includes/header.php
?>
<!-- Audio Element for New Order Alert -->
<audio id="newOrderAudio" src="/assets/audio/you_have_a_new_order.mp3" preload="auto"></audio>
<!-- Header -->
<header class="bg-gray-800 text-white py-4 border-b-4 border-yellow-400 shadow-lg fixed top-0 left-0 right-0 z-50">
<div class="container mx-auto px-4 flex justify-between items-center">
<!-- Logo -->
<div class="flex items-center">
<a href="/public/dashboard.php" class="flex items-center">
<img src="/assets/img/logo.png" alt="Kaak Alia Logo" class="h-12 w-auto mr-2">
<span class="text-xl font-bold">Admin Panel</span>
</a>
</div>
<!-- Navigation Links (Desktop) -->
<nav class="hidden md:flex space-x-4">
<a href="/public/orders/add_order.php" class="flex items-center bg-yellow-400 text-gray-800 px-4 py-2 rounded-lg hover:bg-yellow-300 shadow transition-all duration-300">
<i class="bi bi-plus-circle-fill mr-2"></i> Add Order
</a>
<a href="/public/orders/view_orders.php" class="flex items-center bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-400 shadow transition-all duration-300">
<i class="bi bi-eye-fill mr-2"></i> View Orders
</a>
<a href="/public/products/manage_products.php" class="flex items-center bg-green-400 text-white px-4 py-2 rounded-lg hover:bg-green-300 shadow transition-all duration-300">
<i class="bi bi-box-seam-fill mr-2"></i> Manage Products
</a>
<a href="/public/users/manage_users.php" class="flex items-center bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-400 shadow transition-all duration-300">
<i class="bi bi-people-fill mr-2"></i> Manage Users
</a>
<a href="/public/reports/generate_reports.php" class="flex items-center bg-pink-500 text-white px-4 py-2 rounded-lg hover:bg-pink-400 shadow transition-all duration-300">
<i class="bi bi-bar-chart-fill mr-2"></i> Reports
</a>
</nav>
<!-- Right Side Icons -->
<div class="flex items-center space-x-4">
<!-- Notifications Dropdown -->
<div class="relative" x-data="{ open: false }">
<button @click="open = !open" class="relative text-white hover:text-yellow-400 focus:outline-none" aria-haspopup="true" aria-expanded="false" aria-controls="notification-menu" aria-label="Notifications">
<i class="bi bi-bell-fill text-2xl"></i>
<!-- Notification Badge -->
<span class="absolute top-0 right-0 inline-block w-3 h-3 bg-red-500 rounded-full"></span>
</button>
<!-- Dropdown Menu -->
<div x-show="open" @click.away="open = false" id="notification-menu" class="absolute right-0 mt-2 w-80 bg-gray-800 text-white rounded-lg shadow-lg z-50 hidden">
<div class="py-2 px-4 border-b border-yellow-400">
<h3 class="text-lg font-semibold">Notifications</h3>
</div>
<ul class="max-h-64 overflow-y-auto" id="notificationsList">
<?php
// Fetch the latest 5 pending orders with their items
$notifications_sql = "
SELECT DISTINCT o.id, o.order_date, c.name AS customer_name
FROM orders o
JOIN customers c ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'Pending'
ORDER BY o.id DESC
LIMIT 5
";
$notifications_result = $conn->query($notifications_sql);
if ($notifications_result && $notifications_result->num_rows > 0):
while($notification = $notifications_result->fetch_assoc()):
?>
<li class="px-4 py-2 hover:bg-gray-700 cursor-pointer relative">
<a href="/public/orders/view_order_customer.php?order_id=<?= htmlspecialchars($notification['id'], ENT_QUOTES, 'UTF-8') ?>" class="notification-link flex items-center">
<span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
New Order: <?= htmlspecialchars($notification['customer_name'], ENT_QUOTES, 'UTF-8'); ?> placed on <?= date("d M Y, h:i A", strtotime($notification['order_date'])) ?>
</a>
</li>
<?php
endwhile;
else:
?>
<li class="px-4 py-2 text-gray-400">No new notifications</li>
<?php endif; ?>
</ul>
<div class="py-2 px-4 border-t border-yellow-400 text-center">
<a href="/public/notifications.php" class="text-yellow-400 hover:underline">View All</a>
</div>
</div>
</div>
<!-- User Profile Dropdown -->
<div class="relative" x-data="{ open: false }">
<button @click="open = !open" class="flex items-center focus:outline-none" aria-haspopup="true" aria-expanded="false" aria-controls="profile-menu">
<img src="<?= $profile_image ?>" alt="User Avatar" class="h-10 w-10 rounded-full border-2 border-white hover:border-yellow-400 transition-colors duration-300">
<span class="ml-2 hidden lg:inline-block">
<?= $username ?>
</span>
<i class="bi bi-caret-down-fill ml-1 hidden lg:inline-block"></i>
</button>
<!-- Dropdown Menu -->
<div x-show="open" @click.away="open = false" id="profile-menu" class="absolute right-0 mt-2 w-48 bg-gray-800 text-white rounded-lg shadow-lg z-50 hidden">
<a href="/public/workspace/index.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-laptop mr-2"></i> WorkSpace
</a>
<a href="/public/drivers/drivers_list.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-car-front mr-2"></i> Drivers
</a>
<a href="/includes/user_settings.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-gear-fill mr-2"></i> Settings
</a>
<a href="/public/about_kaakalia/index_en.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-info-circle mr-2"></i> About Kaak Alia
</a>
<a href="/public/logout.php" class="block px-4 py-2 hover:bg-yellow-400 hover:text-gray-800 flex items-center">
<i class="bi bi-box-arrow-right mr-2"></i> Logout
</a>
</div>
</div>
<!-- Mobile Menu Button -->
<div class="md:hidden">
<button id="mobile-menu-button" class="text-white focus:outline-none" aria-label="Toggle Mobile Menu">
<i class="bi bi-list text-2xl"></i>
</button>
</div>
</div>
</div>
<!-- Mobile Navigation Menu -->
<nav id="mobile-menu" class="hidden md:hidden mt-4 bg-gray-800 text-white">
<ul class="flex flex-col space-y-2">
<li>
<a href="/public/orders/add_order.php" class="flex items-center bg-yellow-400 text-gray-800 px-4 py-2 rounded-lg hover:bg-yellow-300 transition-all duration-300">
<i class="bi bi-plus-circle-fill mr-2"></i> Add Order
</a>
</li>
<li>
<a href="/public/orders/view_orders.php" class="flex items-center bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-400 transition-all duration-300">
<i class="bi bi-eye-fill mr-2"></i> View Orders
</a>
</li>
<li>
<a href="/public/products/manage_products.php" class="flex items-center bg-green-400 text-white px-4 py-2 rounded-lg hover:bg-green-300 transition-all duration-300">
<i class="bi bi-box-seam-fill mr-2"></i> Manage Products
</a>
</li>
<li>
<a href="/public/users/manage_users.php" class="flex items-center bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-400 transition-all duration-300">
<i class="bi bi-people-fill mr-2"></i> Manage Users
</a>
</li>
<li>
<a href="/public/reports/generate_reports.php" class="flex items-center bg-pink-500 text-white px-4 py-2 rounded-lg hover:bg-pink-400 transition-all duration-300">
<i class="bi bi-bar-chart-fill mr-2"></i> Reports
</a>
</li>
<!-- Additional Mobile Links -->
<li>
<a href="/public/notifications.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
<i class="bi bi-bell-fill mr-2"></i> Notifications
</a>
</li>
<li>
<a href="/includes/user_settings.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
<i class="bi bi-gear-fill mr-2"></i> Settings
</a>
</li>
<li>
<a href="/public/about_kaakalia/index.php" class="flex items-center bg-gray-700 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition-all duration-300">
<i class="bi bi-info-circle mr-2"></i> About Kaak Alia
</a>
</li>
</ul>
</nav>
<!-- JavaScript for Real-Time Notifications and Mobile Menu Toggle -->
<script>
document.addEventListener('DOMContentLoaded', function() {
const mobileMenuButton = document.getElementById('mobile-menu-button');
const mobileMenu = document.getElementById('mobile-menu');
// Toggle mobile menu on button click
mobileMenuButton.addEventListener('click', function() {
mobileMenu.classList.toggle('hidden');
});
let lastOrderId = <?= $last_order_id ?>;
const audio = document.getElementById('newOrderAudio');
// Function to fetch new orders
function fetchNewOrders() {
fetch(`/includes/get_new_orders.php?last_order_id=${lastOrderId}`)
.then(response => response.json())
.then(data => {
if (data.orders && data.orders.length > 0) {
data.orders.forEach(order => {
// Update lastOrderId if needed
if (order.id > lastOrderId) {
lastOrderId = order.id;
}
// Create a new notification item
const notificationsList = document.getElementById('notificationsList');
const li = document.createElement('li');
li.className = 'px-4 py-2 hover:bg-gray-700 cursor-pointer relative';
// Create a link to the order details page
const a = document.createElement('a');
a.href = `/public/orders/view_order_customer.php?order_id=${encodeURIComponent(order.id)}`;
a.className = 'notification-link flex items-center';
a.innerHTML = `
<span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
New Order: ${sanitizeHTML(order.customer_name)} placed on ${sanitizeHTML(formatDate(order.order_date))}
`;
li.appendChild(a);
// Insert the new notification at the top
notificationsList.insertBefore(li, notificationsList.firstChild);
// Play the audio alert
if (audio) {
audio.play().catch(function(error) {
console.log('Audio playback failed:', error);
});
}
// Optionally, update the notification badge
const bellIcon = document.querySelector('header .bi-bell-fill');
const existingBadge = bellIcon.parentNode.querySelector('.notification-badge');
if (!existingBadge) {
const badge = document.createElement('span');
badge.className = 'notification-badge';
bellIcon.parentNode.appendChild(badge);
}
});
}
})
.catch(error => {
console.error('Error fetching new orders:', error);
});
}
// Function to sanitize HTML to prevent XSS
function sanitizeHTML(str) {
var temp = document.createElement('div');
temp.textContent = str;
return temp.innerHTML;
}
// Function to format date
function formatDate(dateString) {
const options = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' };
return new Date(dateString).toLocaleDateString(undefined, options);
}
// Poll every 10 seconds for new orders
setInterval(fetchNewOrders, 10000); // 10000 ms = 10 seconds
// Fetch immediately on page load
fetchNewOrders();
});
</script>
</header>
<?php
// public/orders/add_order.php
// Start output buffering to prevent "headers already sent" errors
ob_start();
// Include head and header
require_once __DIR__ . '/../../includes/head.php';
require_once __DIR__ . '/../../includes/header.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 = sanitize_input($_POST['customer_name']);
$contact = sanitize_input($_POST['contact']);
$delivery_address = sanitize_input($_POST['delivery_address']);
$delivery_datetime = isset($_POST['delivery_datetime']) && !empty($_POST['delivery_datetime']) ? sanitize_input($_POST['delivery_datetime']) : null;
$priority = isset($_POST['priority']) ? sanitize_input($_POST['priority']) : 'Normal';
// Validate priority
$valid_priorities = ['Normal', 'Important', 'Quick'];
if (!in_array($priority, $valid_priorities)) {
$priority = 'Normal';
}
// Handle multiple products
$product_ids = isset($_POST['product_id']) ? $_POST['product_id'] : [];
$quantities = isset($_POST['quantity']) ? $_POST['quantity'] : [];
$packaging_preferences = isset($_POST['packaging_preferences']) ? $_POST['packaging_preferences'] : [];
$apply_discount = isset($_POST['apply_discount']) ? $_POST['apply_discount'] : [];
$discount_percentages = isset($_POST['discount_percentage']) ? $_POST['discount_percentage'] : [];
$discount_reasons = isset($_POST['discount_reason']) ? $_POST['discount_reason'] : [];
// Basic validation
if (empty($customer_name)) {
$error = "Customer name 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
if ($delivery_datetime && !preg_match("/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/", $delivery_datetime)) {
$error = "Invalid delivery date and time format.";
} elseif ($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 (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
$status = 'Pending'; // Default status
$stmt = $conn->prepare("INSERT INTO orders (customer_id, status, priority, delivery_datetime) VALUES (?, ?, ?, ?)");
if (!$stmt) {
throw new Exception("Prepare statement failed: " . $conn->error);
}
$stmt->bind_param("isss", $customer_id, $status, $priority, $delivery_datetime);
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]);
}
// Corrected bind_param types: "iiisds"
$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();
}
}
}
?>
<!-- Page Content -->
<main class='mt-20 container mx-auto px-4'>
<!-- Welcome Section -->
<div class="welcome-section bg-white shadow-lg rounded-lg p-6 mb-6">
<p>Fill out the form below to add a new customer order.</p>
</div>
<!-- Form Container -->
<div class="form-container bg-white shadow-lg rounded-lg p-6">
<?php if (!empty($error)): ?>
<div class="alert alert-danger d-flex align-items-center">
<i class="bi bi-exclamation-triangle-fill"></i> <?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>
<?php if (!empty($success)): ?>
<div class="alert alert-success d-flex align-items-center">
<i class="bi bi-check-circle-fill"></i> <?= htmlspecialchars($success) ?>
</div>
<?php endif; ?>
<form method="POST" action="add_order.php">
<!-- Customer Details -->
<div class="form-section mb-4">
<h5 class="mb-3">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" rows="3"><?= isset($_POST['delivery_address']) ? htmlspecialchars($_POST['delivery_address']) : '' ?></textarea>
</div>
<hr>
<!-- Order Details -->
<div class="form-section mb-4">
<h5 class="mb-3">Order Details</h5>
<!-- Priority Selection -->
<label class="form-label">Order Priority</label>
<div class="order-priority flex space-x-4">
<label class="inline-flex items-center">
<input type="radio" name="priority" value="Normal" <?= (isset($_POST['priority']) && $_POST['priority'] === 'Normal') || !isset($_POST['priority']) ? 'checked' : '' ?>>
<span class="ml-2">Normal (Default)</span>
</label>
<label class="inline-flex items-center">
<input type="radio" name="priority" value="Important" <?= isset($_POST['priority']) && $_POST['priority'] === 'Important' ? 'checked' : '' ?>>
<span class="ml-2">Important</span>
</label>
<label class="inline-flex items-center">
<input type="radio" name="priority" value="Quick" <?= isset($_POST['priority']) && $_POST['priority'] === 'Quick' ? 'checked' : '' ?>>
<span class="ml-2">Quick</span>
</label>
</div>
<!-- Products Selection -->
<div id="products-container" class="mt-4">
<!-- Product Rows will be added here -->
<?php
// If form was submitted with errors, repopulate the product rows
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($error) && !empty($product_ids) && is_array($product_ids)) {
foreach ($product_ids as $i => $pid) {
?>
<div class="product-row bg-gray-100 p-4 rounded-lg mb-4">
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div>
<label class="form-label" for="product_id_<?= $i ?>">Product <span class="text-danger">*</span></label>
<select name="product_id[]" id="product_id_<?= $i ?>" class="form-control" required>
<option value="">Select Product</option>
<?php
$products_result->data_seek(0);
while($product = $products_result->fetch_assoc()):
$selected = ($product['id'] == $pid) ? 'selected' : '';
?>
<option value="<?= htmlspecialchars($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_<?= $i ?>">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity[]" id="quantity_<?= $i ?>" class="form-control" min="1" value="<?= isset($quantities[$i]) ? intval($quantities[$i]) : '1' ?>" required>
</div>
<div>
<label class="form-label" for="packaging_preferences_<?= $i ?>">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_<?= $i ?>" class="form-control" placeholder="e.g., Gift Wrap" value="<?= isset($packaging_preferences[$i]) ? htmlspecialchars($packaging_preferences[$i]) : '' ?>">
</div>
<div>
<label class="form-label" for="discount_<?= $i ?>">Apply Discount</label>
<div class="flex items-center">
<input type="checkbox" class="form-checkbox" id="discount_checkbox_<?= $i ?>" name="apply_discount[]"
<?= isset($apply_discount[$i]) ? 'checked' : '' ?>>
<label for="discount_checkbox_<?= $i ?>" class="ml-2">Yes</label>
</div>
<div id="discount_fields_<?= $i ?>" class="discount-fields mt-2" style="display: <?= isset($apply_discount[$i]) ? 'block' : 'none' ?>;">
<label class="form-label" for="discount_percentage_<?= $i ?>">Discount Percentage (%) <span class="text-danger">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_<?= $i ?>" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage" value="<?= isset($discount_percentages[$i]) ? htmlspecialchars($discount_percentages[$i]) : '' ?>">
<label class="form-label mt-2" for="discount_reason_<?= $i ?>">Discount Reason <span class="text-danger">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_<?= $i ?>" class="form-control" placeholder="Enter reason for discount" value="<?= isset($discount_reasons[$i]) ? htmlspecialchars($discount_reasons[$i]) : '' ?>">
</div>
</div>
</div>
<button type="button" class="remove-product-button btn btn-danger btn-sm mt-4" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
</div>
<?php
}
} else {
// Add one default product row if not repopulating
?>
<div class="product-row bg-gray-100 p-4 rounded-lg mb-4">
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div>
<label class="form-label" for="product_id_0">Product <span class="text-danger">*</span></label>
<select name="product_id[]" id="product_id_0" class="form-control" required>
<option value="">Select Product</option>
<?php
$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="form-label" for="quantity_0">Quantity <span class="text-danger">*</span></label>
<input type="number" name="quantity[]" id="quantity_0" class="form-control" min="1" value="1" required>
</div>
<div>
<label class="form-label" for="packaging_preferences_0">Packaging Preferences</label>
<input type="text" name="packaging_preferences[]" id="packaging_preferences_0" class="form-control" placeholder="e.g., Gift Wrap">
</div>
<div>
<label class="form-label" for="discount_0">Apply Discount</label>
<div class="flex items-center">
<input type="checkbox" class="form-checkbox" id="discount_checkbox_0" name="apply_discount[]">
<label for="discount_checkbox_0" class="ml-2">Yes</label>
</div>
<div id="discount_fields_0" class="discount-fields mt-2" style="display: none;">
<label class="form-label" for="discount_percentage_0">Discount Percentage (%) <span class="text-danger">*</span></label>
<input type="number" name="discount_percentage[]" id="discount_percentage_0" class="form-control" min="0" max="100" step="0.01" placeholder="Enter discount percentage">
<label class="form-label mt-2" for="discount_reason_0">Discount Reason <span class="text-danger">*</span></label>
<input type="text" name="discount_reason[]" id="discount_reason_0" class="form-control" placeholder="Enter reason for discount">
</div>
</div>
</div>
<button type="button" class="remove-product-button btn btn-danger btn-sm mt-4" onclick="removeProductRow(this)"><i class="bi bi-trash-fill"></i> Remove</button>
</div>
<?php
}
?>
</div>
<button type="button" class="add-product-button btn btn-secondary mt-2" onclick="addProductRow()"><i class="bi bi-plus-circle-fill"></i> Add Another Product</button>
<!-- Delivery DateTime Field -->
<hr class="my-4">
<div class="form-section">
<h5 class="mb-3">Delivery Details</h5>
<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="<?= isset($_POST['delivery_datetime']) ? htmlspecialchars($_POST['delivery_datetime']) : '' ?>">
</div>
</div>
<!-- Submit Button -->
<button type="submit" class="submit-button btn btn-primary mt-4"><i class="bi bi-plus-lg"></i> Add Order</button>
</form>
</div>
</main>
<!-- Footer -->
<?php
require_once __DIR__ . '/../../includes/footer.php';
?>
<!-- JavaScript within includes/header.php -->
<script>
document.addEventListener('DOMContentLoaded', function() {
const mobileMenuButton = document.getElementById('mobile-menu-button');
const mobileMenu = document.getElementById('mobile-menu');
// Toggle mobile menu on button click
mobileMenuButton.addEventListener('click', function() {
mobileMenu.classList.toggle('hidden');
});
let lastOrderId = <?= $last_order_id ?>;
const audio = document.getElementById('newOrderAudio');
// Function to fetch new orders
function fetchNewOrders() {
fetch(`/includes/get_new_orders.php?last_order_id=${lastOrderId}`)
.then(response => response.json())
.then(data => {
if (data.orders && data.orders.length > 0) {
data.orders.forEach(order => {
// Update lastOrderId if needed
if (order.id > lastOrderId) {
lastOrderId = order.id;
}
// Create a new notification item
const notificationsList = document.getElementById('notificationsList');
const li = document.createElement('li');
li.className = 'px-4 py-2 hover:bg-gray-700 cursor-pointer relative';
// Create a link to the order details page
const a = document.createElement('a');
a.href = `/public/orders/view_order_customer.php?order_id=${encodeURIComponent(order.id)}`;
a.className = 'notification-link flex items-center';
a.innerHTML = `
<span class="inline-block w-2 h-2 bg-red-500 rounded-full mr-2"></span>
New Order: ${sanitizeHTML(order.customer_name)} placed on ${sanitizeHTML(formatDate(order.order_date))}
`;
li.appendChild(a);
// Insert the new notification at the top
notificationsList.insertBefore(li, notificationsList.firstChild);
// Play the audio alert
if (audio) {
audio.currentTime = 0; // Reset to start
audio.play().catch(function(error) {
console.log('Audio playback failed:', error);
});
}
// Optionally, update the notification badge
const bellIcon = document.querySelector('header .bi-bell-fill');
const existingBadge = bellIcon.parentNode.querySelector('.notification-badge');
if (!existingBadge) {
const badge = document.createElement('span');
badge.className = 'notification-badge';
bellIcon.parentNode.appendChild(badge);
}
});
}
})
.catch(error => {
console.error('Error fetching new orders:', error);
});
}
// Function to sanitize HTML to prevent XSS
function sanitizeHTML(str) {
var temp = document.createElement('div');
temp.textContent = str;
return temp.innerHTML;
}
// Function to format date
function formatDate(dateString) {
const options = { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' };
return new Date(dateString).toLocaleDateString(undefined, options);
}
// Function to initialize audio after user interaction
function initializeAudio() {
// Play audio muted first to unlock play functionality
audio.muted = true;
audio.play().then(() => {
audio.muted = false;
}).catch(error => {
console.log('Audio initialization failed:', error);
});
}
// Listen for first user interaction to initialize audio
document.body.addEventListener('click', initializeAudio, { once: true });
document.body.addEventListener('keydown', initializeAudio, { once: true });
// Poll every 10 seconds for new orders
setInterval(fetchNewOrders, 10000); // 10000 ms = 10 seconds
// Fetch immediately on page load
fetchNewOrders();
});
</script>