-- 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,
is_star tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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;
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);
// Include authentication, database connection, and functions
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
require_once DIR . '/../../includes/functions.php'; // Include the functions.php for sanitize_input()
// Initialize variables
success=′′;error = '';
// Fetch products for selection
productssql="SELECT∗FROMproductsORDERBYnameASC";products_result = conn−>query(products_sql);
if (!products_result) {
die("Error fetching products: " . conn->error);
}
// 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();
}
userid=_SESSION['user_id'];
$last_order_id = 0;
// Fetch the last pending order ID to initialize polling
initialpendingsql="SELECTo.idFROMordersoWHEREo.status=′Pending′ORDERBYo.idDESCLIMIT1";initial_result = conn−>query(initial_pending_sql);
if (initial_result && initial_result->num_rows > 0) {
row=initial_result->fetch_assoc();
lastorderid=intval(row['id']);
}
// Fetch the logged-in user's profile information
username=′User′;//Defaultusernameprofile_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", userid);stmt->execute();
resultuser=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']);
profileimage=′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.");
}
?>
// 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
lastorderid=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";
// 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 implement real-time audio notifications for new orders in your Kaak Alia Management System, we'll enhance your existing setup by ensuring that:
All users (admins and staff) receive real-time notifications when a new order is added.
An audio alert plays reliably across different browsers, adhering to their autoplay policies.
We'll achieve this by refining your header.php and get_new_orders.php files and ensuring that the audio element is correctly configured and omnipresent across all relevant pages.
Below are the complete and revised code snippets for each file, along with detailed explanations to ensure seamless integration and functionality.
1. includes/header.php
This file is crucial as it manages user authentication, fetches user data, initializes the last known order ID, and handles real-time notifications with audio alerts.
Complete Code:
<?php
// includes/header.php
// 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);
// Start the 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';
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
$user_id = $_SESSION['user_id'];
$last_order_id = 0;
// Fetch the maximum order ID to initialize polling
$initial_order_sql = "SELECT MAX(o.id) AS max_id FROM orders o";
$initial_result = $conn->query($initial_order_sql);
if ($initial_result && $initial_result->num_rows > 0) {
$row = $initial_result->fetch_assoc();
$last_order_id = intval($row['max_id']);
} else {
$last_order_id = 0; // No orders yet
}
// Fetch the logged-in user's profile information
$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>Admin Dashboard</title>
<!-- 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>
</head>
<body class="bg-gray-100">
<!-- 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
// Fetch count of new pending orders beyond last_order_id
$pending_new_sql = "SELECT COUNT(*) AS count FROM orders WHERE status = 'Pending' AND id > ?";
$stmt_pending = $conn->prepare($pending_new_sql);
$pending_count = 0;
if ($stmt_pending) {
$stmt_pending->bind_param("i", $last_order_id);
$stmt_pending->execute();
$result_pending = $stmt_pending->get_result();
if ($result_pending && $result_pending->num_rows === 1) {
$row_pending = $result_pending->fetch_assoc();
$pending_count = intval($row_pending['count']);
}
$stmt_pending->close();
}
if ($pending_count > 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 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 DESC
LIMIT 5
";
$stmt_notif = $conn->prepare($notifications_sql);
if ($stmt_notif) {
$stmt_notif->bind_param("i", $last_order_id);
$stmt_notif->execute();
$result_notif = $stmt_notif->get_result();
if ($result_notif && $result_notif->num_rows > 0):
while($notification = $result_notif->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;
$stmt_notif->close();
}
?>
</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');
// Attempt to unlock audio via user interaction
function unlockAudio() {
audio.play().catch(function(error) {
console.log('Audio unlock failed:', error);
});
document.removeEventListener('click', unlockAudio);
document.removeEventListener('keydown', unlockAudio);
}
document.addEventListener('click', unlockAudio);
document.addEventListener('keydown', unlockAudio);
// Function to fetch new orders
function fetchNewOrders() {
fetch(`/includes/get_new_orders.php?last_order_id=${lastOrderId}`)
.then(response => response.json())
.then(data => {
let newOrdersDetected = false;
if (data.orders && data.orders.length > 0) {
const notificationsList = document.getElementById('notificationsList');
data.orders.forEach(order => {
// Update lastOrderId to the highest order id
if (order.id > lastOrderId) {
lastOrderId = order.id;
newOrdersDetected = true;
}
// Create a new notification item
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);
});
if (newOrdersDetected && audio) {
audio.currentTime = 0; // Reset to start
audio.play().catch(function(error) {
console.log('Audio playback failed:', error);
});
// 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>
</body>
</html>
Explanation & Key Enhancements:
User Authentication & Data Retrieval:
Ensures that only authenticated users can access the dashboard.
Retrieves and securely displays user information, including the profile image with cache-busting.
Initialization of last_order_id:
Sets last_order_id to the highest existing order ID upon page load to track new orders accurately.
Notifications Badge:
Displays a red dot on the bell icon if there are any new pending orders beyond the last_order_id.
Real-Time Notification Handling:
Polling Mechanism:
Uses fetch to call get_new_orders.php every 10 seconds to check for new orders.
Audio Alert:
Plays the you_have_a_new_order.mp3 audio whenever new orders are detected.
Ensures that audio playback is initiated by a user interaction (click or keydown) to comply with modern browser autoplay restrictions.
Dynamic Notification List:
Updates the notifications dropdown in real-time by inserting new notifications at the top of the list.
Mobile Responsiveness:
Implements a mobile menu that toggles visibility on smaller screens for better user experience.
Security Considerations:
Sanitizes all dynamic content to prevent Cross-Site Scripting (XSS) attacks using the sanitizeHTML function.
User Interaction for Audio Playback:
Adds event listeners for click and keydown to unlock audio playback, adhering to browser policies that restrict autoplaying audio without user interaction.
2. includes/get_new_orders.php
This script fetches new pending orders that have been added after the user's last known order ID. It returns the data in JSON format for the frontend to process.
Complete 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 the 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' => date("d M Y, h:i A", strtotime($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]);
?>
Explanation & Key Enhancements:
User Authentication:
Ensures that only authenticated users can access the script, returning a 401 Unauthorized error for unauthenticated requests.
Fetching New Orders:
Queries the database for new orders with a status of 'Pending' and an id greater than the provided last_order_id.
Orders are sorted in ascending order to ensure proper sequence.
Data Sanitization:
Escapes the customer_name using htmlspecialchars to prevent XSS attacks.
Formats the order_date into a human-readable format.
Error Handling:
Returns a 500 Internal Server Error with a JSON-encoded error message if the database query fails.
JSON Response:
Returns the fetched data in a structured JSON format, making it easy for the frontend to process and display notifications.
3. add_order.php
While your existing add_order.php script handles order creation, ensure that orders are correctly inserted with a status of 'Pending' so that the polling mechanism can detect them. Here's a brief checklist to verify:
Checklist:
Order Status:
Ensure that every new order inserted has the status set to 'Pending'.
Proper Commit of Transactions:
Ensure that all database transactions related to order creation are properly committed to allow immediate detection by the polling mechanism.
Sanitization and Validation:
Continue using sanitize_input() and proper validation as shown in your existing script to maintain security and data integrity.
No Changes Needed:
Given your existing add_order.php script handles these aspects correctly, no modifications are required. However, always test the order creation process to ensure that new orders are being inserted with the correct status and that related entries (like order_items) are properly linked.
4. Ensuring Audio Playback Compliance
Modern browsers have stringent autoplay policies that prevent audio from playing without explicit user interaction. To ensure that the audio alerts function correctly:
User Interaction Initialization:
The provided header.php includes JavaScript that attempts to play the audio once the user interacts with the page (via click or keydown). This unlocks the audio for subsequent playback.
Audio File Verification:
Ensure that the audio file you_have_a_new_order.mp3 exists in the /assets/audio/ directory and is accessible.
Verify the path by directly navigating to https://yourdomain.com/assets/audio/you_have_a_new_order.mp3 in your browser.
Browser Console Checks:
Use the browser's developer tools (F12) to monitor the console for any errors related to audio playback.
Testing Audio Playback:
Manually add a new order and observe if the audio plays for other users.
Initially, reduce the polling interval (e.g., to every 5 seconds) for testing purposes. Remember to set it back to a reasonable interval (like 10 seconds) to avoid unnecessary server load.
5. Additional Recommendations
Use Web Workers or Service Workers for Enhanced Performance:
For more efficient real-time notifications, consider implementing Web Workers or Service Workers, which can handle background tasks without blocking the main thread.
Implement Server-Sent Events (SSE) or WebSockets for Real-Time Communication:
While polling is straightforward, technologies like SSE or WebSockets offer more efficient and real-time communication channels, reducing latency and server load.
Handle Multiple Notifications Gracefully:
If multiple orders are added in quick succession, ensure that the audio alert doesn't overlap or become disruptive. You might consider aggregating notifications or limiting the number of alerts.
Accessibility Considerations:
Provide users with the option to mute or disable audio notifications, enhancing accessibility and user control.
By meticulously implementing and testing the above code and recommendations, your Kaak Alia Management System will effectively play audio notifications across all user roles when new orders are added, ensuring timely awareness and efficient order management.