<?php
session_start();
header('Content-Type: application/json; charset=utf-8');

require_once "../includes/functions.php";

$restaurant_id = (int)($_SESSION['restaurant_id'] ?? 0);
if(!$restaurant_id){
    echo json_encode(['error'=>1]);
    exit;
}

$live_count = (int)fetch_value("
    SELECT COUNT(*) FROM reservations
    WHERE restaurant_id=? AND status IN('pending','confirmed')
", [$restaurant_id]);

// إذا init=1: ثبّت الأساس دائماً (حتى لو كان في جلسة قديمة)
if(isset($_GET['init']) && $_GET['init'] == '1'){
    $_SESSION['last_live_count'] = $live_count;
    echo json_encode([
        'count' => $live_count,
        'play'  => false,
        'init'  => true
    ]);
    exit;
}

// بدون init: قارن مع آخر قيمة
$last = isset($_SESSION['last_live_count']) ? (int)$_SESSION['last_live_count'] : $live_count;
$play = ($live_count > $last);

// حدّث آخر قيمة
$_SESSION['last_live_count'] = $live_count;

echo json_encode([
    'count' => $live_count,
    'play'  => $play,
    'init'  => false
]);
