<?php
session_start();
include("../config/db.php");
header('Content-Type: application/json');

$allowed = ['restaurant_admin','staff','waiter'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role']??'', $allowed)) {
    echo json_encode(["error"=>"unauthorized"]); exit;
}

$uid = (int)$_SESSION['user_id'];
$u = $conn->prepare("SELECT restaurant_id FROM users WHERE id=?");
$u->bind_param("i",$uid); $u->execute();
$row = $u->get_result()->fetch_assoc();
$rid = (int)($row['restaurant_id'] ?? 0);

if (!$rid) { echo json_encode(["error"=>"no restaurant"]); exit; }

$pending = $conn->prepare("SELECT COUNT(*) FROM orders WHERE restaurant_id=? AND order_status='pending'");
$pending->bind_param("i",$rid); $pending->execute();
$pending_count = $pending->get_result()->fetch_row()[0];

$notifs = $conn->prepare("SELECT COUNT(*) FROM notifications WHERE restaurant_id=? AND is_read=0");
$notifs->bind_param("i",$rid); $notifs->execute();
$notif_count = $notifs->get_result()->fetch_row()[0];

$scans = $conn->prepare("SELECT COUNT(*) FROM qr_scans WHERE restaurant_id=? AND scanned_at >= NOW() - INTERVAL 5 MINUTE");
$scans->bind_param("i",$rid); $scans->execute();
$recent_scans = $scans->get_result()->fetch_row()[0];

echo json_encode([
    "pending_orders" => (int)$pending_count,
    "unread_notifs"  => (int)$notif_count,
    "recent_scans"   => (int)$recent_scans,
    "timestamp"      => date('Y-m-d H:i:s')
]);
