adding timer to online order

This commit is contained in:
Flatlogic Bot 2026-03-28 18:12:49 +00:00
parent 5b05c65a86
commit ff9ab72c0b
14 changed files with 1280 additions and 29 deletions

View File

@ -14,7 +14,7 @@ if (!$id) {
// Fetch Order Details // Fetch Order Details
$stmt = $pdo->prepare("SELECT o.*, ot.name as outlet_name, pt.name as payment_type_name, $stmt = $pdo->prepare("SELECT o.*, ot.name as outlet_name, pt.name as payment_type_name,
c.name as customer_name, c.phone as customer_phone, c.email as customer_email, c.address as customer_address, c.name as customer_name, c.phone as customer_phone, c.email as customer_email, c.address as customer_address, o.car_plate,
u.username as created_by_username u.username as created_by_username
FROM orders o FROM orders o
LEFT JOIN outlets ot ON o.outlet_id = ot.id LEFT JOIN outlets ot ON o.outlet_id = ot.id
@ -293,6 +293,13 @@ $vat_rate = (float)($company_settings['vat_rate'] ?? 0);
<small class="text-muted">Customer ID: #<?= $order['customer_id'] ?></small> <small class="text-muted">Customer ID: #<?= $order['customer_id'] ?></small>
</div> </div>
</div> </div>
<?php if ($order['car_plate']): ?>
<div class="mb-2">
<i class="bi bi-car-front text-muted me-2 no-print"></i>
<span class="print-only">Car Plate: </span>
<span class="text-dark"><?= htmlspecialchars($order['car_plate']) ?></span>
</div>
<?php endif; ?>
<?php if ($order['customer_phone']): ?> <?php if ($order['customer_phone']): ?>
<div class="mb-2"> <div class="mb-2">
<i class="bi bi-telephone text-muted me-2 no-print"></i> <i class="bi bi-telephone text-muted me-2 no-print"></i>

View File

@ -282,6 +282,7 @@ include 'includes/header.php';
<th>Cashier</th> <th>Cashier</th>
<th>Customer</th> <th>Customer</th>
<th>Type</th> <th>Type</th>
<th>Car Plate</th>
<th>VAT</th> <th>VAT</th>
<th>Total</th> <th>Total</th>
<?php if ($commission_enabled): ?> <?php if ($commission_enabled): ?>
@ -309,6 +310,9 @@ include 'includes/header.php';
<td> <td>
<?php if (!empty($order['customer_name'])): ?> <?php if (!empty($order['customer_name'])): ?>
<div><?= htmlspecialchars((string)($order['customer_name'] ?? '')) ?></div> <div><?= htmlspecialchars((string)($order['customer_name'] ?? '')) ?></div>
<?php if (!empty($order['car_plate'])): ?>
<div class="small text-muted"><i class="bi bi-car-front me-1"></i><?= htmlspecialchars((string)($order['car_plate'] ?? '')) ?></div>
<?php endif; ?>
<?php if (!empty($order['customer_phone'])): ?> <?php if (!empty($order['customer_phone'])): ?>
<small class="text-muted"><i class="bi bi-telephone me-1"></i><?= htmlspecialchars((string)($order['customer_phone'] ?? '')) ?></small> <small class="text-muted"><i class="bi bi-telephone me-1"></i><?= htmlspecialchars((string)($order['customer_phone'] ?? '')) ?></small>
<?php endif; ?> <?php endif; ?>

View File

@ -14,7 +14,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Kitchen sees: pending, preparing, ready // Kitchen sees: pending, preparing, ready
$stmt = $pdo->prepare(" $stmt = $pdo->prepare("
SELECT SELECT
o.id, o.table_number, o.order_type, o.status, o.created_at, o.customer_name, o.id, o.table_number, o.order_type, o.status, o.created_at, o.ready_time, o.customer_name, o.car_plate, o.user_id,
oi.quantity, COALESCE(p.name, oi.product_name) as product_name, COALESCE(v.name, oi.variant_name) as variant_name oi.quantity, COALESCE(p.name, oi.product_name) as product_name, COALESCE(v.name, oi.variant_name) as variant_name
FROM orders o FROM orders o
JOIN order_items oi ON o.id = oi.order_id JOIN order_items oi ON o.id = oi.order_id
@ -38,6 +38,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
'status' => $row['status'], 'status' => $row['status'],
'created_at' => $row['created_at'], 'created_at' => $row['created_at'],
'customer_name' => $row['customer_name'], 'customer_name' => $row['customer_name'],
'car_plate' => $row['car_plate'],
'ready_time' => $row['ready_time'],
'user_id' => $row['user_id'], 'is_online_order' => ($row['user_id'] === null && $row['order_type'] !== 'dine-in'), 'is_table_order' => ($row['user_id'] === null && $row['order_type'] === 'dine-in'),
'items' => [] 'items' => []
]; ];
} }

View File

@ -70,9 +70,37 @@ try {
} }
// Customer Handling // Customer Handling
$register_customer = !empty($data['register_customer']);
$customer_id = !empty($data['customer_id']) ? intval($data['customer_id']) : null; $customer_id = !empty($data['customer_id']) ? intval($data['customer_id']) : null;
$customer_name = $data['customer_name'] ?? null; $customer_name = $data['customer_name'] ?? null;
$customer_phone = $data['customer_phone'] ?? null; $customer_phone = $data['customer_phone'] ?? null;
$car_plate = $data['car_plate'] ?? null;
$prep_time_minutes = isset($data['prep_time_minutes']) ? intval($data['prep_time_minutes']) : null;
$ready_time = null;
if ($prep_time_minutes > 0) {
$ready_time = date("Y-m-d H:i:s", strtotime("+$prep_time_minutes minutes"));
}
$register_customer = !empty($data['register_customer']);
if (!$customer_id && $customer_phone && $register_customer) {
$stmt = $pdo->prepare("SELECT id FROM customers WHERE phone = ?");
$stmt->execute([$customer_phone]);
$existing = $stmt->fetch();
if ($existing) {
$customer_id = $existing['id'];
} else {
$stmt = $pdo->prepare("INSERT INTO customers (name, phone) VALUES (?, ?)");
$stmt->execute([$customer_name, $customer_phone]);
$customer_id = $pdo->lastInsertId();
}
} else if (!$customer_id && $customer_phone && !$register_customer) {
$stmt = $pdo->prepare("SELECT id FROM customers WHERE phone = ?");
$stmt->execute([$customer_phone]);
$existing = $stmt->fetch();
if ($existing) {
$customer_id = $existing['id'];
}
}
// Fetch Loyalty Settings // Fetch Loyalty Settings
$settingsStmt = $pdo->query("SELECT is_enabled, points_per_order, points_for_free_meal FROM loyalty_settings WHERE id = 1"); $settingsStmt = $pdo->query("SELECT is_enabled, points_per_order, points_for_free_meal FROM loyalty_settings WHERE id = 1");
@ -309,13 +337,13 @@ try {
if ($is_update) { if ($is_update) {
$stmt = $pdo->prepare("UPDATE orders SET $stmt = $pdo->prepare("UPDATE orders SET
outlet_id = ?, table_id = ?, table_number = ?, order_type = ?, outlet_id = ?, table_id = ?, table_number = ?, order_type = ?,
customer_id = ?, customer_name = ?, customer_phone = ?, customer_id = ?, customer_name = ?, customer_phone = ?, car_plate = ?, ready_time = ?,
payment_type_id = ?, total_amount = ?, discount = ?, vat = ?, user_id = ?, payment_type_id = ?, total_amount = ?, discount = ?, vat = ?, user_id = ?,
commission_amount = ?, status = 'pending' commission_amount = ?, status = 'pending'
WHERE id = ?"); WHERE id = ?");
$stmt->execute([ $stmt->execute([
$outlet_id, $table_id, $table_number, $order_type, $outlet_id, $table_id, $table_number, $order_type,
$customer_id, $customer_name, $customer_phone, $customer_id, $customer_name, $customer_phone, $car_plate, $ready_time,
$payment_type_id, $final_total, 0, $calculated_vat, $user_id, $payment_type_id, $final_total, 0, $calculated_vat, $user_id,
$commission_amount, $order_id $commission_amount, $order_id
]); ]);
@ -323,8 +351,8 @@ try {
$delStmt = $pdo->prepare("DELETE FROM order_items WHERE order_id = ?"); $delStmt = $pdo->prepare("DELETE FROM order_items WHERE order_id = ?");
$delStmt->execute([$order_id]); $delStmt->execute([$order_id]);
} else { } else {
$stmt = $pdo->prepare("INSERT INTO orders (outlet_id, table_id, table_number, order_type, customer_id, customer_name, customer_phone, payment_type_id, total_amount, discount, vat, user_id, commission_amount, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')"); $stmt = $pdo->prepare("INSERT INTO orders (outlet_id, table_id, table_number, order_type, customer_id, customer_name, customer_phone, car_plate, ready_time, payment_type_id, total_amount, discount, vat, user_id, commission_amount, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')");
$stmt->execute([$outlet_id, $table_id, $table_number, $order_type, $customer_id, $customer_name, $customer_phone, $payment_type_id, $final_total, 0, $calculated_vat, $user_id, $commission_amount]); $stmt->execute([$outlet_id, $table_id, $table_number, $order_type, $customer_id, $customer_name, $customer_phone, $car_plate, $ready_time, $payment_type_id, $final_total, 0, $calculated_vat, $user_id, $commission_amount]);
$order_id = $pdo->lastInsertId(); $order_id = $pdo->lastInsertId();
} }

View File

@ -25,6 +25,7 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}) : null; }) : null;
window.showToast = showToast;
function showToast(msg, type = 'primary') { function showToast(msg, type = 'primary') {
if (!Toast) { if (!Toast) {
console.log(`Toast: ${msg} (${type})`); console.log(`Toast: ${msg} (${type})`);

143
customer_profile.php Normal file
View File

@ -0,0 +1,143 @@
<?php
require_once 'db/config.php';
$pdo = db();
$settings = get_company_settings();
$customer = null;
$orders = [];
$points_history = [];
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['phone'])) {
$phone = trim($_POST['phone']);
$stmt = $pdo->prepare("SELECT * FROM customers WHERE phone = ?");
$stmt->execute([$phone]);
$customer = $stmt->fetch(PDO::FETCH_ASSOC);
if ($customer) {
$stmt_orders = $pdo->prepare("SELECT o.id, o.created_at, o.total_amount, o.status, o.car_plate, o.ready_time,
(SELECT GROUP_CONCAT(CONCAT(oi.quantity, 'x ', oi.product_name) SEPARATOR ', ') FROM order_items oi WHERE oi.order_id = o.id) as items_summary
FROM orders o WHERE o.customer_id = ? ORDER BY o.created_at DESC");
$stmt_orders->execute([$customer['id']]);
$orders = $stmt_orders->fetchAll(PDO::FETCH_ASSOC);
$stmt_points = $pdo->prepare("SELECT * FROM loyalty_points_history WHERE customer_id = ? ORDER BY created_at DESC");
$stmt_points->execute([$customer['id']]);
$points_history = $stmt_points->fetchAll(PDO::FETCH_ASSOC);
} else {
$error = "Customer not found with this phone number.";
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>My Profile - <?= htmlspecialchars($settings['company_name'] ?? 'Order Online') ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root { --primary-color: #2563eb; --bg-light: #f8fafc; --card-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); --primary-font: 'Plus Jakarta Sans', sans-serif; }
body { background-color: var(--bg-light); font-family: var(--primary-font); color: #1e293b; }
.hero-section { background: linear-gradient(135deg, #1e293b 0%, #334155 100%); color: white; padding: 2rem 1rem 4rem; border-bottom-left-radius: 2.5rem; border-bottom-right-radius: 2.5rem; margin-bottom: -2rem; text-align: center; }
.back-btn { position: absolute; top: 1.5rem; left: 1.5rem; color: white; font-size: 1.5rem; }
.card-custom { background: white; border-radius: 1.25rem; box-shadow: var(--card-shadow); border: none; margin-bottom: 1.5rem; padding: 1.5rem; }
.points-display { font-size: 2.5rem; font-weight: 700; color: var(--primary-color); }
</style>
</head>
<body>
<header class="hero-section position-relative">
<a href="online_order.php" class="back-btn"><i class="bi bi-arrow-left"></i></a>
<h2 class="fw-bold mb-1 mt-2">My Profile</h2>
<p class="opacity-75 mb-0 small">View orders & loyalty points</p>
</header>
<div class="container py-4 position-relative" style="z-index: 10;">
<?php if (!$customer): ?>
<div class="card-custom">
<h4 class="fw-bold mb-3">Login to view profile</h4>
<?php if ($error): ?>
<div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<form method="POST">
<div class="mb-3">
<label class="form-label">Phone Number</label>
<input type="tel" name="phone" class="form-control form-control-lg" placeholder="Enter your registered phone" required>
</div>
<button type="submit" class="btn btn-primary btn-lg w-100 rounded-pill fw-bold">View Profile</button>
</form>
</div>
<?php else: ?>
<div class="card-custom text-center">
<div class="mb-2 text-muted small">Welcome back,</div>
<h3 class="fw-bold mb-3"><?= htmlspecialchars($customer['name']) ?></h3>
<div class="d-flex justify-content-center align-items-center gap-3 bg-light rounded-4 py-3 px-4 d-inline-flex mx-auto">
<div><div class="text-muted small">Available Points</div><div class="points-display"><?= (int)$customer['points'] ?></div></div>
<i class="bi bi-star-fill text-warning fs-1"></i>
</div>
</div>
<h5 class="fw-bold mb-3 ms-2">Order History</h5>
<?php if (empty($orders)): ?>
<p class="text-muted ms-2">No orders found.</p>
<?php else: ?>
<?php foreach ($orders as $order): ?>
<div class="card-custom p-3">
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="fw-bold">Order #<?= $order['id'] ?></span>
<span class="badge bg-<?= $order['status'] === 'completed' ? 'success' : ($order['status'] === 'cancelled' ? 'danger' : 'warning') ?>"><?= ucfirst($order['status']) ?></span>
</div>
<div class="text-muted small mb-2"><i class="bi bi-calendar3 me-1"></i> <?= date('M d, Y h:i A', strtotime($order['created_at'])) ?></div>
<div class="small mb-2"><?= htmlspecialchars($order['items_summary']) ?></div>
<?php if(!empty($order['car_plate'])): ?><div class="small text-muted mb-2"><i class="bi bi-car-front me-1"></i> <?= htmlspecialchars($order['car_plate']) ?></div><?php endif; ?>
<?php if(!empty($order['ready_time']) && !in_array($order['status'], ['completed', 'cancelled'])): ?>
<div class="small mb-2 text-danger fw-bold countdown-timer" data-ready-time="<?= strtotime($order['ready_time']) * 1000 ?>"><i class="bi bi-clock-history me-1"></i> <span></span></div>
<?php endif; ?>
<div class="fw-bold text-primary text-end"><?= number_format($order['total_amount'], 3) ?> OMR</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
<h5 class="fw-bold mb-3 ms-2 mt-4">Points History</h5>
<?php if (empty($points_history)): ?>
<p class="text-muted ms-2">No points history found.</p>
<?php else: ?>
<div class="card-custom p-0 overflow-hidden">
<div class="list-group list-group-flush">
<?php foreach ($points_history as $hist): ?>
<div class="list-group-item p-3">
<div class="d-flex justify-content-between align-items-center">
<div>
<div class="fw-bold small"><?= htmlspecialchars($hist['reason']) ?></div>
<div class="text-muted" style="font-size: 0.75rem;"><?= date('M d, Y h:i A', strtotime($hist['created_at'])) ?></div>
</div>
<div class="fw-bold <?= $hist['points_change'] > 0 ? 'text-success' : 'text-danger' ?>">
<?= $hist['points_change'] > 0 ? '+' : '' ?><?= $hist['points_change'] ?>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
<div class="text-center mt-4">
<a href="customer_profile.php" class="btn btn-outline-secondary rounded-pill px-4">Logout</a>
</div>
<?php endif; ?>
</div>
<script>
function updateTimers() {
document.querySelectorAll('.countdown-timer').forEach(el => {
const readyTime = parseInt(el.getAttribute('data-ready-time'));
const now = new Date().getTime();
const diff = readyTime - now;
if (diff > 0) {
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
el.querySelector('span').innerText = 'Ready in: ' + minutes + 'm ' + seconds + 's';
} else {
el.querySelector('span').innerText = 'Should be ready soon!';
}
});
}
setInterval(updateTimers, 1000);
updateTimers();
</script>
</body>
</html>

View File

@ -0,0 +1,18 @@
-- Add car_plate column to orders table
SET @dbname = DATABASE();
SET @tablename = "orders";
SET @columnname = "car_plate";
SET @preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE
(table_name = @tablename)
AND (table_schema = @dbname)
AND (column_name = @columnname)
) > 0,
"SELECT 1",
"ALTER TABLE orders ADD COLUMN car_plate VARCHAR(50) DEFAULT NULL AFTER customer_phone;"
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

View File

@ -0,0 +1 @@
ALTER TABLE orders ADD COLUMN ready_time DATETIME NULL AFTER created_at;

View File

@ -59,6 +59,15 @@ class PrinterService {
$out .= $esc . "a" . "\x00"; // Left align $out .= $esc . "a" . "\x00"; // Left align
$out .= "Order ID: #" . $order['id'] . "\n"; $out .= "Order ID: #" . $order['id'] . "\n";
$out .= "Date: " . ($order['created_at'] ?? date('Y-m-d H:i:s')) . "\n"; $out .= "Date: " . ($order['created_at'] ?? date('Y-m-d H:i:s')) . "\n";
if (!empty($order['customer_name'])) {
$out .= "Customer: " . $order['customer_name'] . "\n";
}
if (!empty($order['customer_phone'])) {
$out .= "Phone: " . $order['customer_phone'] . "\n";
}
if (!empty($order['car_plate'])) {
$out .= "Car Plate: " . $order['car_plate'] . "\n";
}
$out .= $line; $out .= $line;
foreach ($items as $item) { foreach ($items as $item) {

View File

@ -230,6 +230,11 @@ $baseUrl = get_base_url();
</a> </a>
<!-- Customer Feedback --> <!-- Customer Feedback -->
<a href="online_order.php" class="portal-card" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
<i class="bi bi-cart"></i>
<h3>Online Order</h3>
<p>Place an order for pickup or delivery.</p>
</a>
<a href="rate.php" class="portal-card feedback"> <a href="rate.php" class="portal-card feedback">
<div class="floating-object" style="top: 20%; left: 20%; animation-delay: 1s; background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);"></div> <div class="floating-object" style="top: 20%; left: 20%; animation-delay: 1s; background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);"></div>
<i class="bi bi-star"></i> <i class="bi bi-star"></i>

View File

@ -147,12 +147,74 @@ const COMPANY_SETTINGS = <?= json_encode($settings) ?>;
const BASE_URL = '<?= get_base_url() ?>'; const BASE_URL = '<?= get_base_url() ?>';
let activeOrders = []; let activeOrders = [];
let seenOrderIds = new Set();
let isFirstLoad = true;
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
document.addEventListener('click', () => {
if (audioCtx && audioCtx.state === 'suspended') {
audioCtx.resume();
}
});
function playOnlineSound() {
if (audioCtx && audioCtx.state === 'suspended') audioCtx.resume();
[0, 0.15, 0.3].forEach(startTime => {
const osc = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
osc.type = 'square';
osc.frequency.setValueAtTime(800, audioCtx.currentTime + startTime);
gainNode.gain.setValueAtTime(0.1, audioCtx.currentTime + startTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + startTime + 0.1);
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
osc.start(audioCtx.currentTime + startTime);
osc.stop(audioCtx.currentTime + startTime + 0.15);
});
}
function playTableSound() {
if (audioCtx && audioCtx.state === 'suspended') audioCtx.resume();
[0, 0.3].forEach(startTime => {
const osc = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(500, audioCtx.currentTime + startTime);
gainNode.gain.setValueAtTime(0.2, audioCtx.currentTime + startTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + startTime + 0.25);
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
osc.start(audioCtx.currentTime + startTime);
osc.stop(audioCtx.currentTime + startTime + 0.3);
});
}
async function fetchOrders() { async function fetchOrders() {
try { try {
const response = await fetch('api/kitchen.php?outlet_id=' + OUTLET_ID); const response = await fetch('api/kitchen.php?outlet_id=' + OUTLET_ID);
if (!response.ok) throw new Error('Network response was not ok'); if (!response.ok) throw new Error('Network response was not ok');
const orders = await response.json(); const orders = await response.json();
let newOnlineCount = 0;
let newTableCount = 0;
orders.forEach(order => {
if (!seenOrderIds.has(order.id)) {
if (!isFirstLoad) {
if (order.is_online_order) newOnlineCount++;
else if (order.is_table_order) newTableCount++;
}
seenOrderIds.add(order.id);
}
});
if (newOnlineCount > 0) {
playOnlineSound();
} else if (newTableCount > 0) {
playTableSound();
}
isFirstLoad = false;
activeOrders = orders; activeOrders = orders;
renderOrders(orders); renderOrders(orders);
} catch (error) { } catch (error) {
@ -160,6 +222,21 @@ async function fetchOrders() {
} }
} }
function updateTimers() {
document.querySelectorAll('.countdown-timer').forEach(el => { const readyTime = parseInt(el.getAttribute('data-ready-time'));
const now = new Date().getTime();
const diff = readyTime - now;
if (diff > 0) {
const m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const s = Math.floor((diff % (1000 * 60)) / 1000);
el.querySelector('span').innerText = `Ready in: ${m}m ${s}s`;
} else {
el.querySelector('span').innerText = 'Should be ready!';
}
});
}
setInterval(updateTimers, 1000);
function renderOrders(orders) { function renderOrders(orders) {
const grid = document.getElementById('kitchen-grid'); const grid = document.getElementById('kitchen-grid');
@ -207,6 +284,8 @@ function renderOrders(orders) {
<h5 class="card-title mb-3"> <h5 class="card-title mb-3">
${order.order_type === 'dine-in' ? `Table ${order.table_number}` : order.order_type.toUpperCase()} ${order.order_type === 'dine-in' ? `Table ${order.table_number}` : order.order_type.toUpperCase()}
${order.customer_name ? `<br><small class="text-muted">${order.customer_name}</small>` : ''} ${order.customer_name ? `<br><small class="text-muted">${order.customer_name}</small>` : ''}
${order.car_plate ? `<br><small class="text-muted"><i class="bi bi-car-front"></i> ${order.car_plate}</small>` : ''}
${order.ready_time ? `<br><small class="text-danger fw-bold countdown-timer" data-ready-time="${new Date(order.ready_time).getTime()}"><i class="bi bi-clock-history"></i> <span></span></small>` : ''}
</h5> </h5>
<ul class="item-list mb-3"> <ul class="item-list mb-3">
${itemsHtml} ${itemsHtml}
@ -273,6 +352,7 @@ function printKitchenTicket(orderId) {
${order.order_type === 'dine-in' ? `<div><strong>Table:</strong> ${order.table_number}</div>` : ''} ${order.order_type === 'dine-in' ? `<div><strong>Table:</strong> ${order.table_number}</div>` : ''}
<div><strong>Time:</strong> ${new Date(order.created_at).toLocaleString()}</div> <div><strong>Time:</strong> ${new Date(order.created_at).toLocaleString()}</div>
${order.customer_name ? `<div><strong>Cust:</strong> ${order.customer_name}</div>` : ''} ${order.customer_name ? `<div><strong>Cust:</strong> ${order.customer_name}</div>` : ''}
${order.car_plate ? `<div><strong>Car:</strong> ${order.car_plate}</div>` : ''}
</div> </div>
<div style="border-bottom: 2px solid #000; margin-bottom: 10px;"></div> <div style="border-bottom: 2px solid #000; margin-bottom: 10px;"></div>
<table> <table>

894
online_order.php Normal file
View File

@ -0,0 +1,894 @@
<?php
require_once 'db/config.php';
// Language configuration
$lang = isset($_GET['lang']) && in_array($_GET['lang'], ['en', 'ar']) ? $_GET['lang'] : 'ar';
$is_ar = $lang === 'ar';
$translations = [
'ar' => [
'order_online' => 'اطلب عبر الإنترنت',
'my_profile_points' => 'ملفي الشخصي والنقاط',
'table' => 'طاولة',
'all' => 'الكل',
'add_to_cart' => 'أضف إلى السلة',
'options' => 'الخيارات',
'view_cart' => 'عرض السلة',
'review_order' => 'مراجعة الطلب',
'name' => 'الاسم',
'your_name' => 'اسمك',
'phone' => 'رقم الهاتف',
'your_phone' => 'رقم هاتفك',
'car_plate' => 'رقم لوحة السيارة (اختياري)',
'car_plate_placeholder' => 'مثال: 1234 أ',
'ready_in' => 'وقت التحضير',
'ready_asap' => 'في أسرع وقت',
'ready_10m' => 'بعد 10 دقائق',
'ready_15m' => 'بعد 15 دقيقة',
'ready_20m' => 'بعد 20 دقيقة',
'ready_30m' => 'بعد 30 دقيقة',
'register_to_earn' => 'سجل لكسب النقاط وعرض السجل',
'subtotal' => 'المجموع الفرعي',
'total' => 'المجموع',
'place_order' => 'تأكيد الطلب',
'please_select_option' => 'يرجى تحديد خيار',
'please_enter_details' => 'يرجى إدخال اسمك ورقم هاتفك.',
'order_placed_success' => 'تم الطلب بنجاح!',
'error' => 'خطأ:',
'failed_to_place' => 'فشل في إتمام الطلب. يرجى المحاولة مرة أخرى.',
'all_rights_reserved' => 'جميع الحقوق محفوظة.',
'not_found' => 'لم يتم العثور على الطاولة. يرجى الاتصال بالموظفين.',
'language' => 'English'
],
'en' => [
'order_online' => 'Order Online',
'my_profile_points' => 'My Profile & Points',
'table' => 'Table',
'all' => 'All',
'add_to_cart' => 'Add to Cart',
'options' => 'Options',
'view_cart' => 'View Cart',
'review_order' => 'Review Order',
'name' => 'Name',
'your_name' => 'Your Name',
'phone' => 'Phone',
'your_phone' => 'Your Phone Number',
'car_plate' => 'Car Plate No. (Optional)',
'car_plate_placeholder' => 'e.g. 1234 A',
'ready_in' => 'Ready In',
'ready_asap' => 'ASAP',
'ready_10m' => 'After 10 mins',
'ready_15m' => 'After 15 mins',
'ready_20m' => 'After 20 mins',
'ready_30m' => 'After 30 mins',
'register_to_earn' => 'Register to earn points and view history',
'subtotal' => 'Subtotal',
'total' => 'Total',
'place_order' => 'Place Order',
'please_select_option' => 'Please select an option',
'please_enter_details' => 'Please enter your name and phone number.',
'order_placed_success' => 'Order placed successfully!',
'error' => 'Error:',
'failed_to_place' => 'Failed to place order. Please try again.',
'all_rights_reserved' => 'All rights reserved.',
'not_found' => 'Table not found. Please contact staff.',
'language' => 'عربي'
]
];
function tt($key) {
global $translations, $lang;
return $translations[$lang][$key] ?? $key;
}
$pdo = db();
$settings = get_company_settings();
$table_id = isset($_GET['table_id']) ? (int)$_GET['table_id'] : (isset($_GET['table']) ? (int)$_GET['table'] : 0);
$table_info = null;
if ($table_id === 0 && isset($_GET['table_number'])) {
$stmt = $pdo->prepare('SELECT id FROM `tables` WHERE table_number = ? AND is_deleted = 0 LIMIT 1');
$stmt->execute([$_GET['table_number']]);
$table_id = (int)$stmt->fetchColumn();
}
if ($table_id > 0) {
try {
$stmt = $pdo->prepare("
SELECT t.id, t.table_number AS table_name, a.outlet_id, o.name AS outlet_name, o.name_ar AS outlet_name_ar
FROM `tables` t
JOIN areas a ON t.area_id = a.id
JOIN outlets o ON a.outlet_id = o.id
WHERE t.id = ?
");
$stmt->execute([$table_id]);
$table_info = $stmt->fetch();
if (!$table_info) {
die(tt('not_found'));
}
} catch (PDOException $e) {
die("Database error: " . $e->getMessage());
}
}
$outlet_id = (int)($table_info['outlet_id'] ?? 0);
$categories = $pdo->query("SELECT * FROM categories WHERE is_deleted = 0 ORDER BY sort_order")->fetchAll();
$all_products = $pdo->query("SELECT p.*, c.name as category_name, c.name_ar as category_name_ar FROM products p JOIN categories c ON p.category_id = c.id WHERE p.is_deleted = 0 AND p.show_in_qorder = 1 AND c.is_deleted = 0")->fetchAll();
// Fetch variants
$variants_raw = $pdo->query("SELECT * FROM product_variants WHERE is_deleted = 0 ORDER BY price_adjustment ASC")->fetchAll();
$variants_by_product = [];
foreach ($variants_raw as $v) {
$variants_by_product[$v['product_id']][] = $v;
}
// Build translated structures for JS
$js_products = array_map(function($p) use ($is_ar) {
$p['display_name'] = ($is_ar && !empty($p['name_ar'])) ? $p['name_ar'] : $p['name'];
return $p;
}, $all_products);
$js_variants = [];
foreach ($variants_by_product as $pid => $vars) {
$js_variants[$pid] = array_map(function($v) use ($is_ar) {
$v['display_name'] = ($is_ar && !empty($v['name_ar'])) ? $v['name_ar'] : $v['name'];
return $v;
}, $vars);
}
?>
<!doctype html>
<html lang="<?= $lang ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title><?= htmlspecialchars($settings['company_name'] ?? tt('order_online')) ?></title>
<?php if (!empty($settings['favicon_url'])): ?>
<link rel="icon" href="<?= get_base_url() . htmlspecialchars($settings['favicon_url']) ?>?v=<?= time() ?>">
<?php endif; ?>
<?php if ($is_ar): ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
<?php else: ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<?php endif; ?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&family=Noto+Kufi+Arabic:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary-color: #2563eb;
--secondary-color: #64748b;
--bg-light: #f8fafc;
--card-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
--primary-font: <?= $is_ar ? "'Noto Kufi Arabic', 'Plus Jakarta Sans', sans-serif" : "'Plus Jakarta Sans', 'Noto Kufi Arabic', sans-serif" ?>;
}
body {
background-color: var(--bg-light);
font-family: var(--primary-font);
color: #1e293b;
padding-bottom: 80px;
}
/* Header Styling */
.hero-section {
background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
color: white;
padding: 3rem 1rem 5rem;
border-bottom-left-radius: 2.5rem;
border-bottom-right-radius: 2.5rem;
margin-bottom: -3rem;
position: relative;
z-index: 1;
}
.company-logo {
width: 80px;
height: 80px;
background: white;
padding: 10px;
border-radius: 20px;
box-shadow: var(--card-shadow);
margin-bottom: 1rem;
object-fit: contain;
}
.table-badge {
background: rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
padding: 0.5rem 1rem;
border-radius: 50px;
font-weight: 600;
font-size: 0.9rem;
display: inline-block;
}
.lang-switcher {
position: absolute;
top: 1rem;
<?= $is_ar ? 'left: 1rem;' : 'right: 1rem;' ?>
color: white;
text-decoration: none;
background: rgba(255, 255, 255, 0.1);
padding: 0.4rem 0.8rem;
border-radius: 50px;
font-size: 0.85rem;
backdrop-filter: blur(5px);
border: 1px solid rgba(255, 255, 255, 0.2);
transition: all 0.2s;
}
.lang-switcher:hover { color: white; background: rgba(255, 255, 255, 0.2); }
/* Category Nav */
.category-nav-container {
position: sticky;
top: 0;
z-index: 100;
background: rgba(248, 250, 252, 0.8);
backdrop-filter: blur(10px);
padding: 0.75rem 0;
border-bottom: 1px solid #e2e8f0;
margin-bottom: 1.5rem;
}
.category-wrapper {
display: flex;
overflow-x: auto;
gap: 0.75rem;
padding: 0.25rem 1rem;
scrollbar-width: none;
-ms-overflow-style: none;
-webkit-overflow-scrolling: touch;
}
.category-wrapper::-webkit-scrollbar { display: none; }
.category-item {
display: inline-flex;
flex-direction: column;
align-items: center;
text-decoration: none;
color: var(--secondary-color);
font-weight: 500;
font-size: 0.85rem;
min-width: 70px;
text-align: center;
transition: all 0.2s;
padding: 0.5rem;
border-radius: 12px;
}
.category-item.active {
color: var(--primary-color);
background: white;
box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.1);
}
.category-icon {
width: 44px;
height: 44px;
border-radius: 12px;
background: #f1f5f9;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 0.4rem;
font-size: 1.25rem;
transition: all 0.2s;
overflow: hidden;
}
.category-icon img {
width: 100%;
height: 100%;
object-fit: cover;
}
.category-item.active .category-icon {
background: #dbeafe;
color: var(--primary-color);
}
/* Product Grid */
.products-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
padding: 0 1rem;
}
@media (min-width: 768px) {
.products-grid { grid-template-columns: repeat(3, 1fr); }
}
@media (min-width: 992px) {
.products-grid { grid-template-columns: repeat(4, 1fr); }
}
@media (min-width: 1200px) {
.products-grid { grid-template-columns: repeat(5, 1fr); }
}
.product-card {
background: white;
border-radius: 1.25rem;
overflow: hidden;
box-shadow: var(--card-shadow);
transition: transform 0.2s;
border: 1px solid #f1f5f9;
display: flex;
flex-direction: column;
height: 100%;
cursor: pointer;
}
.product-card:active { transform: scale(0.98); }
.product-img-wrapper {
position: relative;
width: 100%;
padding-top: 100%; /* 1:1 Aspect Ratio */
background: #f8fafc;
}
.product-img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.no-image-placeholder {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #f1f5f9;
color: #94a3b8;
font-size: 2rem;
}
.product-info {
padding: 0.85rem;
display: flex;
flex-direction: column;
flex-grow: 1;
}
.product-name {
font-size: 0.95rem;
font-weight: 600;
margin-bottom: 0.25rem;
line-height: 1.3;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.product-price {
font-weight: 700;
color: var(--primary-color);
font-size: 1rem;
margin-top: auto;
}
.add-btn {
width: 32px;
height: 32px;
border-radius: 10px;
background: var(--primary-color);
color: white;
display: flex;
align-items: center;
justify-content: center;
border: none;
box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.3);
}
/* Floating Cart Bar */
.cart-bar {
position: fixed;
bottom: 1.5rem;
left: 1rem;
right: 1rem;
background: #1e293b;
color: white;
padding: 0.85rem 1.25rem;
border-radius: 1.25rem;
display: flex;
align-items: center;
justify-content: space-between;
z-index: 1000;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
transform: translateY(150%);
}
.cart-bar.visible { transform: translateY(0); }
.cart-count {
background: var(--primary-color);
color: white;
width: 24px;
height: 24px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 0.75rem;
font-weight: 700;
<?= $is_ar ? 'margin-left: 0.5rem;' : 'margin-right: 0.5rem;' ?>
}
.view-cart-btn {
color: white;
text-decoration: none;
font-weight: 600;
display: flex;
align-items: center;
}
/* Footer */
footer {
background: #f1f5f9;
padding: 3rem 1rem;
margin-top: 3rem;
text-align: center;
border-top: 1px solid #e2e8f0;
}
.footer-logo { height: 40px; margin-bottom: 1rem; filter: grayscale(1); opacity: 0.6; }
.footer-links {
display: flex;
justify-content: center;
gap: 1.5rem;
margin-bottom: 1.5rem;
}
.footer-links a { color: var(--secondary-color); font-size: 1.25rem; }
/* Modals */
.modal-content { border-radius: 1.5rem; border: none; }
.modal-header { border-bottom: 1px solid #f1f5f9; padding: 1.25rem; }
.modal-body { padding: 1.25rem; }
.variant-item {
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 0.75rem;
margin-bottom: 0.5rem;
display: flex;
justify-content: space-between;
cursor: pointer;
}
.variant-item.selected {
border-color: var(--primary-color);
background: #eff6ff;
}
.cart-item {
display: flex;
gap: 1rem;
padding-bottom: 1rem;
margin-bottom: 1rem;
border-bottom: 1px solid #f1f5f9;
}
.qty-control {
display: flex;
align-items: center;
background: #f1f5f9;
border-radius: 10px;
padding: 2px;
}
.qty-btn {
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
border: none;
background: white;
border-radius: 8px;
font-weight: 700;
}
.qty-val { width: 30px; text-align: center; font-weight: 600; }
</style>
</head>
<body>
<!-- Hero Header -->
<header class="hero-section text-center">
<div class="container">
<?php
$currentParams = $_GET;
$currentParams['lang'] = $is_ar ? 'en' : 'ar';
$switchUrl = '?' . http_build_query($currentParams);
?>
<a href="<?= htmlspecialchars($switchUrl) ?>" class="lang-switcher">
<i class="bi bi-globe"></i> <?= tt('language') ?>
</a>
<?php if (!empty($settings['logo_url'])): ?>
<img src="<?= get_base_url() . htmlspecialchars($settings['logo_url']) ?>?v=<?= time() ?>" class="company-logo" alt="Logo">
<?php endif; ?>
<h1 class="h3 fw-bold mb-1"><?= htmlspecialchars($settings['company_name'] ?? 'Restaurant') ?></h1>
<p class="opacity-75 mb-3 small">
<?php
$outlet_name_display = ($is_ar && !empty($table_info['outlet_name_ar'])) ? $table_info['outlet_name_ar'] : ($table_info['outlet_name'] ?? '');
echo htmlspecialchars($outlet_name_display);
?>
</p>
<div class="mt-3">
<a href="customer_profile.php<?= isset($_GET['lang']) ? '?lang='.$_GET['lang'] : '' ?>" class="btn btn-outline-light btn-sm rounded-pill px-3"><i class="bi bi-person-circle <?= $is_ar ? 'ms-1' : 'me-1' ?>"></i> <?= tt('my_profile_points') ?></a>
</div>
<div class="table-badge mt-3">
<i class="bi bi-geo-alt-fill <?= $is_ar ? 'ms-1' : 'me-1' ?>"></i> <?= tt('table') ?> <?= htmlspecialchars($table_info['table_name'] ?? 'N/A') ?>
</div>
</div>
</header>
<div class="container py-4">
<!-- Category Navigation -->
<div class="category-nav-container">
<div class="category-wrapper">
<a href="#" class="category-item active" data-category="all">
<div class="category-icon"><i class="bi bi-grid-fill"></i></div>
<span><?= tt('all') ?></span>
</a>
<?php foreach ($categories as $cat): ?>
<?php $cat_name = ($is_ar && !empty($cat['name_ar'])) ? $cat['name_ar'] : $cat['name']; ?>
<a href="#" class="category-item" data-category="<?= $cat['id'] ?>">
<div class="category-icon">
<?php if (!empty($cat['image_url'])): ?>
<img src="<?= (strpos($cat['image_url'], 'http') === 0) ? htmlspecialchars($cat['image_url']) : get_base_url() . htmlspecialchars($cat['image_url']) ?>" alt="<?= htmlspecialchars($cat_name) ?>">
<?php else: ?>
<i class="bi bi-egg-fried"></i>
<?php endif; ?>
</div>
<span><?= htmlspecialchars($cat_name) ?></span>
</a>
<?php endforeach; ?>
</div>
</div>
<!-- Product Grid -->
<div class="products-grid">
<?php foreach ($js_products as $p): ?>
<div class="product-card-container" data-category-id="<?= $p['category_id'] ?>">
<div class="product-card" onclick="openProduct(<?= htmlspecialchars(json_encode($p)) ?>)">
<div class="product-img-wrapper">
<?php if (!empty($p['image_url'])): ?>
<img src="<?= (strpos($p['image_url'], 'http') === 0) ? htmlspecialchars($p['image_url']) : get_base_url() . htmlspecialchars($p['image_url']) ?>" class="product-img" alt="<?= htmlspecialchars($p['display_name']) ?>">
<?php else: ?>
<div class="no-image-placeholder"><i class="bi bi-image"></i></div>
<?php endif; ?>
</div>
<div class="product-info">
<h3 class="product-name"><?= htmlspecialchars($p['display_name']) ?></h3>
<div class="d-flex justify-content-between align-items-center">
<span class="product-price"><?= number_format($p['price'], 2) ?></span>
<button class="add-btn"><i class="bi bi-plus-lg"></i></button>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<!-- Footer -->
<footer>
<div class="container">
<?php if (!empty($settings['logo_url'])): ?>
<img src="<?= get_base_url() . htmlspecialchars($settings['logo_url']) ?>?v=<?= time() ?>" class="footer-logo" alt="Logo">
<?php endif; ?>
<p class="text-muted small mb-3">
<?= htmlspecialchars($settings['address'] ?? '') ?><br>
<?= htmlspecialchars($settings['phone'] ?? '') ?>
</p>
<div class="footer-links">
<a href="#"><i class="bi bi-instagram"></i></a>
<a href="#"><i class="bi bi-facebook"></i></a>
<a href="#"><i class="bi bi-whatsapp"></i></a>
</div>
<p class="text-muted small mb-0">&copy; <?= date('Y') ?> <?= htmlspecialchars($settings['company_name'] ?? 'Restaurant') ?>. <?= tt('all_rights_reserved') ?></p>
</div>
</footer>
<!-- Floating Cart -->
<div class="cart-bar" id="cart-bar">
<div class="d-flex align-items-center">
<span class="cart-count" id="cart-count">0</span>
<span class="fw-bold" id="cart-total">0.00</span>
</div>
<a href="#" class="view-cart-btn" onclick="showCartModal()">
<?= tt('view_cart') ?> <i class="bi <?= $is_ar ? 'bi-arrow-left' : 'bi-arrow-right' ?> mx-2"></i>
</a>
</div>
<!-- Product Modal -->
<div class="modal fade" id="productModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header border-0">
<button type="button" class="btn-close <?= $is_ar ? 'ms-0 me-auto' : '' ?>" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body text-center pt-0">
<div id="modal-img-container" class="mb-3 rounded-4 overflow-hidden" style="height: 200px; background: #f8fafc;"></div>
<h4 class="fw-bold mb-1" id="modal-product-name"></h4>
<p class="text-muted small mb-3" id="modal-product-desc"></p>
<div id="variants-section" class="text-start mb-4 d-none">
<p class="fw-bold mb-2"><?= tt('options') ?></p>
<div id="variants-list"></div>
</div>
<div class="d-flex align-items-center justify-content-between mb-4 px-2">
<span class="h4 fw-bold text-primary mb-0" id="modal-price"></span>
<div class="qty-control">
<button class="qty-btn" onclick="updateModalQty(-1)">-</button>
<span class="qty-val" id="modal-qty">1</span>
<button class="qty-btn" onclick="updateModalQty(1)">+</button>
</div>
</div>
<button class="btn btn-primary btn-lg w-100 rounded-pill py-3 fw-bold" onclick="addToCartFromModal()"><?= tt('add_to_cart') ?></button>
</div>
</div>
</div>
</div>
<!-- Cart Modal -->
<div class="modal fade" id="cartModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-fullscreen-sm-down modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title fw-bold"><?= tt('review_order') ?></h5>
<button type="button" class="btn-close <?= $is_ar ? 'ms-0 me-auto' : '' ?>" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label"><?= tt('name') ?></label>
<input type="text" class="form-control" id="customer-name" placeholder="<?= tt('your_name') ?>" required>
</div>
<div class="mb-3">
<label class="form-label"><?= tt('phone') ?></label>
<input type="tel" class="form-control" id="customer-phone" placeholder="<?= tt('your_phone') ?>" required>
</div>
<div class="mb-3">
<label class="form-label"><?= tt('car_plate') ?></label>
<input type="text" class="form-control" id="car-plate" placeholder="<?= tt('car_plate_placeholder') ?>">
</div>
<div class="mb-4 d-flex align-items-center">
<input type="checkbox" id="register-checkbox" class="form-check-input <?= $is_ar ? 'ms-2' : 'me-2' ?>">
<label class="form-check-label" for="register-checkbox"><?= tt('register_to_earn') ?></label>
</div>
<hr>
<div id="cart-items-list"></div>
<div class="mt-4 p-3 bg-light rounded-4">
<div class="d-flex justify-content-between mb-2">
<span class="text-muted"><?= tt('subtotal') ?></span>
<span class="fw-bold" id="checkout-subtotal">0.00</span>
</div>
<div class="d-flex justify-content-between h4 mt-3 pt-3 border-top">
<span class="fw-bold"><?= tt('total') ?></span>
<span class="fw-bold text-primary" id="checkout-total">0.00</span>
</div>
</div>
</div>
<div class="modal-footer border-0 p-3">
<button class="btn btn-primary btn-lg w-100 rounded-pill py-3 fw-bold" onclick="placeOrder()"><?= tt('place_order') ?></button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let cart = [];
const variantsByProduct = <?= json_encode($js_variants) ?>;
let currentProduct = null;
let currentModalQty = 1;
let selectedVariant = null;
// Translation strings for JS alerts
const ttStrings = {
please_select_option: <?= json_encode(tt('please_select_option')) ?>,
please_enter_details: <?= json_encode(tt('please_enter_details')) ?>,
order_placed_success: <?= json_encode(tt('order_placed_success')) ?>,
error: <?= json_encode(tt('error')) ?>,
failed_to_place: <?= json_encode(tt('failed_to_place')) ?>
};
// Category Filtering
document.querySelectorAll('.category-item').forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
const catId = item.getAttribute('data-category');
document.querySelectorAll('.category-item').forEach(i => i.classList.remove('active'));
item.classList.add('active');
document.querySelectorAll('.product-card-container').forEach(card => {
if (catId === 'all' || card.getAttribute('data-category-id') === catId) {
card.style.display = 'block';
} else {
card.style.display = 'none';
}
});
});
});
function openProduct(p) {
currentProduct = p;
currentModalQty = 1;
selectedVariant = null;
document.getElementById('modal-product-name').textContent = p.display_name;
document.getElementById('modal-price').textContent = parseFloat(p.price).toFixed(2);
document.getElementById('modal-qty').textContent = '1';
const imgContainer = document.getElementById('modal-img-container');
if (p.image_url) {
const fullUrl = p.image_url.startsWith('http') ? p.image_url : '<?= get_base_url() ?>' + p.image_url;
imgContainer.innerHTML = `<img src="${fullUrl}" style="width:100%; height:100%; object-fit:cover;">`;
} else {
imgContainer.innerHTML = `<div class="d-flex align-items-center justify-content-center h-100 text-muted fs-1"><i class="bi bi-image"></i></div>`;
}
const variants = variantsByProduct[p.id] || [];
const vSection = document.getElementById('variants-section');
const vList = document.getElementById('variants-list');
if (variants.length > 0) {
vSection.classList.remove('d-none');
vList.innerHTML = variants.map(v => `
<div class="variant-item" data-variant-id="${v.id}" onclick="selectVariant(this, ${v.price_adjustment})">
<span>${v.display_name}</span>
<span class="fw-bold" dir="ltr">+${parseFloat(v.price_adjustment).toFixed(2)}</span>
</div>
`).join('');
} else {
vSection.classList.add('d-none');
}
new bootstrap.Modal(document.getElementById('productModal')).show();
}
function selectVariant(el, adj) {
document.querySelectorAll('.variant-item').forEach(v => v.classList.remove('selected'));
el.classList.add('selected');
selectedVariant = {
id: el.getAttribute('data-variant-id'),
name: el.querySelector('span').textContent,
adjustment: adj
};
updateModalPrice();
}
function updateModalPrice() {
let price = parseFloat(currentProduct.price);
if (selectedVariant) price += parseFloat(selectedVariant.adjustment);
document.getElementById('modal-price').textContent = (price * currentModalQty).toFixed(2);
}
function updateModalQty(delta) {
currentModalQty = Math.max(1, currentModalQty + delta);
document.getElementById('modal-qty').textContent = currentModalQty;
updateModalPrice();
}
function addToCartFromModal() {
const variants = variantsByProduct[currentProduct.id] || [];
if (variants.length > 0 && !selectedVariant) {
alert(ttStrings.please_select_option);
return;
}
const item = {
id: currentProduct.id,
name: currentProduct.display_name,
price: parseFloat(currentProduct.price),
qty: currentModalQty,
variant_id: selectedVariant ? selectedVariant.id : null,
variant_name: selectedVariant ? selectedVariant.name : '',
variant_adj: selectedVariant ? selectedVariant.adjustment : 0
};
const existing = cart.find(i => i.id === item.id && i.variant_id === item.variant_id);
if (existing) {
existing.qty += item.qty;
} else {
cart.push(item);
}
updateCartUI();
bootstrap.Modal.getInstance(document.getElementById('productModal')).hide();
}
function updateCartUI() {
const count = cart.reduce((sum, item) => sum + item.qty, 0);
const total = cart.reduce((sum, item) => sum + ((item.price + parseFloat(item.variant_adj)) * item.qty), 0);
document.getElementById('cart-count').textContent = count;
document.getElementById('cart-total').textContent = total.toFixed(2);
const cartBar = document.getElementById('cart-bar');
if (count > 0) {
cartBar.classList.add('visible');
} else {
cartBar.classList.remove('visible');
}
}
function showCartModal() {
const list = document.getElementById('cart-items-list');
const total = cart.reduce((sum, item) => sum + ((item.price + parseFloat(item.variant_adj)) * item.qty), 0);
list.innerHTML = cart.map((item, index) => `
<div class="cart-item">
<div class="flex-grow-1">
<h6 class="fw-bold mb-0">${item.name}</h6>
${item.variant_name ? `<small class="text-muted">${item.variant_name}</small>` : ''}
<div class="fw-bold text-primary mt-1">${((item.price + parseFloat(item.variant_adj)) * item.qty).toFixed(2)}</div>
</div>
<div class="qty-control align-self-center <?= $is_ar ? 'me-2' : '' ?>">
<button class="qty-btn" onclick="updateCartQty(${index}, -1)">-</button>
<span class="qty-val">${item.qty}</span>
<button class="qty-btn" onclick="updateCartQty(${index}, 1)">+</button>
</div>
</div>
`).join('');
document.getElementById('checkout-subtotal').textContent = total.toFixed(2);
document.getElementById('checkout-total').textContent = total.toFixed(2);
new bootstrap.Modal(document.getElementById('cartModal')).show();
}
function updateCartQty(index, delta) {
cart[index].qty += delta;
if (cart[index].qty <= 0) cart.splice(index, 1);
updateCartUI();
if (cart.length === 0) {
bootstrap.Modal.getInstance(document.getElementById('cartModal')).hide();
} else {
showCartModal();
}
}
async function placeOrder() {
if (cart.length === 0) return;
const custName = document.getElementById("customer-name").value;
const custPhone = document.getElementById("customer-phone").value;
const carPlate = document.getElementById("car-plate").value;
const doRegister = document.getElementById("register-checkbox").checked;
if (!custName || !custPhone) {
alert(ttStrings.please_enter_details);
return;
}
const orderData = {
table_id: <?= $table_id ?>,
outlet_id: <?= $outlet_id ?>,
items: cart.map(item => ({
product_id: item.id,
variant_id: item.variant_id,
quantity: item.qty,
price: item.price + parseFloat(item.variant_adj)
})),
order_type: 'takeaway',
customer_name: custName,
customer_phone: custPhone,
car_plate: carPlate,
prep_time_minutes: parseInt(prepTime, 10),
register_customer: doRegister
};
try {
const resp = await fetch('api/order.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(orderData)
});
const res = await resp.json();
if (res.success) {
alert(ttStrings.order_placed_success);
document.getElementById("customer-name").value = "";
document.getElementById("customer-phone").value = "";
document.getElementById("car-plate").value = "";
document.getElementById("register-checkbox").checked = false;
cart = [];
updateCartUI();
bootstrap.Modal.getInstance(document.getElementById('cartModal')).hide();
} else {
alert(ttStrings.error + ' ' + res.error);
}
} catch (e) {
alert(ttStrings.failed_to_place);
}
}
</script>
</body>
</html>

View File

@ -1,23 +0,0 @@
<?php
$content = file_get_contents('admin/products.php');
$search = <<<HTML
<?php if ($product['is_loyalty']): ?>
<span class="badge bg-info bg-opacity-10 text-info border border-info rounded-pill ms-1" style="font-size: 0.7rem;">
<i class="bi bi-star-fill"></i> Loyalty
</span>
<?php endif; ?>
HTML;
$replace = $search . <<<HTML
<?php if ($product['show_in_qorder']): ?>
<span class="badge bg-primary bg-opacity-10 text-primary border border-primary rounded-pill ms-1" style="font-size: 0.7rem;">
<i class="bi bi-qr-code"></i> QR Menu
</span>
<?php endif; ?>
HTML;
$content = str_replace($search, $replace, $content);
file_put_contents('admin/products.php', $content);
echo "Badge added.\n";

81
pos.php
View File

@ -486,6 +486,87 @@ $vat_rate = (float)($settings['vat_rate'] ?? 0);
} }
}; };
const t = (key) => translations[LANG][key] || key; const t = (key) => translations[LANG][key] || key;
// --- Audio Notifications Polling ---
let seenOrderIds = new Set();
let isFirstLoad = true;
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
document.addEventListener('click', () => {
if (audioCtx && audioCtx.state === 'suspended') {
audioCtx.resume();
}
});
function playOnlineSound() {
if (audioCtx && audioCtx.state === 'suspended') audioCtx.resume();
[0, 0.15, 0.3].forEach(startTime => {
const osc = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
osc.type = 'square';
osc.frequency.setValueAtTime(800, audioCtx.currentTime + startTime);
gainNode.gain.setValueAtTime(0.1, audioCtx.currentTime + startTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + startTime + 0.1);
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
osc.start(audioCtx.currentTime + startTime);
osc.stop(audioCtx.currentTime + startTime + 0.15);
});
}
function playTableSound() {
if (audioCtx && audioCtx.state === 'suspended') audioCtx.resume();
[0, 0.3].forEach(startTime => {
const osc = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(500, audioCtx.currentTime + startTime);
gainNode.gain.setValueAtTime(0.2, audioCtx.currentTime + startTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + startTime + 0.25);
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
osc.start(audioCtx.currentTime + startTime);
osc.stop(audioCtx.currentTime + startTime + 0.3);
});
}
async function pollForNewOrders() {
if (!CURRENT_OUTLET || !CURRENT_OUTLET.id) return;
try {
const response = await fetch('api/kitchen.php?outlet_id=' + CURRENT_OUTLET.id);
if (!response.ok) return;
const orders = await response.json();
let newOnlineCount = 0;
let newTableCount = 0;
orders.forEach(order => {
if (!seenOrderIds.has(order.id)) {
if (!isFirstLoad) {
if (order.is_online_order) newOnlineCount++;
else if (order.is_table_order) newTableCount++;
}
seenOrderIds.add(order.id);
}
});
if (newOnlineCount > 0) {
playOnlineSound();
if (typeof showToast === 'function') showToast('New Online Order!', 'warning');
} else if (newTableCount > 0) {
playTableSound();
if (typeof showToast === 'function') showToast('New Table Order!', 'info');
}
isFirstLoad = false;
} catch (e) {
// Ignore polling errors
}
}
setInterval(pollForNewOrders, 10000);
pollForNewOrders();
// ------------------------------------
</script> </script>
<script src="assets/js/main.js?v=<?= time() ?>"></script> <script src="assets/js/main.js?v=<?= time() ?>"></script>
</body> </body>