<?php
/**
 * heartbeat.php — Heartbeat des Jetsons SmartEye
 *
 * Appelé toutes les 5 minutes par chaque Jetson déployé.
 * Met à jour le statut du site et le timestamp du dernier contact.
 *
 * POST /heartbeat.php
 * Content-Type: application/json
 * {"client_id": "Demo_01", "token": "secret123", "uptime": 86400, "cameras_active": 3}
 */
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(["success" => false, "message" => "POST uniquement"]));
}

$input = json_decode(file_get_contents("php://input"), true);
$client_id = $input['client_id'] ?? '';
$token = $input['token'] ?? '';

if (empty($client_id) || empty($token)) {
    http_response_code(400);
    die(json_encode(["success" => false, "message" => "client_id et token requis"]));
}

$DB_FILE = "database.json";
$db = json_decode(file_get_contents($DB_FILE), true);

// Authentification
$found_key = null;
foreach ($db['clients'] as $key => $c) {
    if (strcasecmp($c['name'] ?? '', $client_id) === 0 && $c['token'] === $token) {
        $found_key = $key;
        break;
    }
}

if ($found_key === null) {
    http_response_code(403);
    die(json_encode(["success" => false, "message" => "Authentification échouée"]));
}

// Mise à jour heartbeat
$db['clients'][$found_key]['last_heartbeat'] = date("Y-m-d H:i:s");
$db['clients'][$found_key]['site_status'] = "active";
$db['clients'][$found_key]['uptime'] = $input['uptime'] ?? 0;
$db['clients'][$found_key]['cameras_active'] = $input['cameras_active'] ?? 0;

file_put_contents($DB_FILE, json_encode($db, JSON_PRETTY_PRINT));

echo json_encode([
    "success" => true,
    "message" => "Heartbeat reçu",
    "server_time" => date("Y-m-d H:i:s")
]);
?>