<?php
/**
 * Returns the current OPEN service ("Call Server") requests for the signed-in
 * staff member's restaurant, as JSON. Polled by the waiter dashboard to raise
 * a live alert/notification without a full refresh.
 */
require_once(__DIR__ . "/../includes/auth.php");
header('Content-Type: application/json');

$calls = []; $maxId = 0;
if ($q = $conn->prepare("SELECT * FROM service_calls WHERE restaurant_id=? AND status='open' ORDER BY created_at ASC")) {
    $q->bind_param("i", $__rest_id); $q->execute();
    foreach ($q->get_result()->fetch_all(MYSQLI_ASSOC) as $c) {
        [$src, $sec] = order_source_label(['table_number' => $c['table_number'], 'loc_label' => $c['table_label']]);
        $mins = max(0, (int)floor((time() - strtotime($c['created_at'])) / 60));
        $calls[] = [
            'id'   => (int)$c['id'],
            'src'  => $src,
            'sec'  => $sec,
            'name' => $c['customer_name'] ?: 'A customer',
            'mins' => $mins,
        ];
        $maxId = max($maxId, (int)$c['id']);
    }
}
echo json_encode(['calls' => $calls, 'maxId' => $maxId]);
