<?php
// restaurantadmin/ajax/poll.php
// Polled every 20s by includes/header.php to detect new orders & notifications.
// Returns active order counts per status + new pending indicator.
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=? LIMIT 1");
$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; }

// ── Per-status counts (active statuses only) ──────────────────────────────
$active_statuses = ['pending','accepted','preparing','ready','served'];
$counts = array_fill_keys($active_statuses, 0);

$sc = $conn->prepare(
    "SELECT order_status, COUNT(*) AS cnt
     FROM orders
     WHERE restaurant_id=? AND order_status IN('pending','accepted','preparing','ready','served')
     GROUP BY order_status"
);
$sc->bind_param("i",$rid); $sc->execute();
$scr = $sc->get_result();
while ($r = $scr->fetch_assoc()) {
    $counts[$r['order_status']] = (int)$r['cnt'];
}

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

// ── Recent QR scans (last 5 min) — table may not exist on all installs ───
$recent_scans = 0;
$tables_res = $conn->query("SHOW TABLES LIKE 'qr_scans'");
if ($tables_res && $tables_res->num_rows > 0) {
    $qs = $conn->prepare("SELECT COUNT(*) FROM qr_scans WHERE restaurant_id=? AND scanned_at >= NOW() - INTERVAL 5 MINUTE");
    $qs->bind_param("i",$rid); $qs->execute();
    $recent_scans = (int)$qs->get_result()->fetch_row()[0];
}

// ── Most recent order ID (used to detect brand-new orders client-side) ───
$lo = $conn->prepare("SELECT id FROM orders WHERE restaurant_id=? ORDER BY id DESC LIMIT 1");
$lo->bind_param("i",$rid); $lo->execute();
$last_order_id = (int)($lo->get_result()->fetch_row()[0] ?? 0);

// ── Most recent pending order details for the alert toast ────────────────
$latest_pending = null;
if ($counts['pending'] > 0) {
    $lp = $conn->prepare(
        "SELECT o.id, o.total_amount, o.table_number, o.table_label, u.name AS customer_name,
                (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) AS item_count
         FROM orders o
         LEFT JOIN users u ON o.user_id = u.id
         WHERE o.restaurant_id=? AND o.order_status='pending'
         ORDER BY o.created_at DESC LIMIT 1"
    );
    $lp->bind_param("i",$rid); $lp->execute();
    $latest_pending = $lp->get_result()->fetch_assoc();
    if ($latest_pending) {
        $latest_pending['total_amount'] = (float)$latest_pending['total_amount'];
        $latest_pending['item_count']   = (int)$latest_pending['item_count'];
        $latest_pending['id']           = (int)$latest_pending['id'];
    }
}

echo json_encode([
    // Summary counts
    "pending_orders"  => $counts['pending'],
    "accepted_orders" => $counts['accepted'],
    "preparing_orders"=> $counts['preparing'],
    "ready_orders"    => $counts['ready'],
    "served_orders"   => $counts['served'],
    "active_total"    => array_sum($counts),

    // Misc
    "unread_notifs"   => $notif_count,
    "recent_scans"    => $recent_scans,
    "last_order_id"   => $last_order_id,
    "latest_pending"  => $latest_pending,
    "timestamp"       => date('Y-m-d H:i:s'),
]);
