<?php
declare(strict_types=1);
require_once __DIR__ . '/../db.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

function rs_out(array $d, int $s = 200): void {
    http_response_code($s);
    echo json_encode($d, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$raw  = (string)file_get_contents('php://input');
$body = [];
if ($raw !== '') { $dec = json_decode($raw, true); if (is_array($dec)) $body = $dec; }
if (empty($body)) $body = $_POST;

$apiKey     = trim((string)($body['api_key'] ?? ''));
$apiSecret  = trim((string)($body['api_secret'] ?? ''));
$instanceId = trim((string)($body['instance_id'] ?? ''));
$newStatus  = trim((string)($body['status'] ?? ''));

if ($apiKey === '' || $apiSecret === '') rs_out(['ok'=>false,'error'=>'Missing credentials'], 401);
if ($instanceId === '') rs_out(['ok'=>false,'error'=>'instance_id required'], 400);
if (!in_array($newStatus, ['waiting','assigned','started','closed'], true)) rs_out(['ok'=>false,'error'=>'Invalid status'], 400);

$pdo = lk_pdo();
try {
    $st = $pdo->prepare("SELECT id, api_secret_hash FROM users WHERE api_key=? AND is_active=1 LIMIT 1");
    $st->execute([$apiKey]);
    $user = $st->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) { rs_out(['ok'=>false,'error'=>'DB: '.$e->getMessage()], 500); }

if (!$user || !hash_equals((string)$user['api_secret_hash'], $apiSecret)) rs_out(['ok'=>false,'error'=>'Invalid credentials'], 401);

try {
    $extraSql = match($newStatus) {
        'started' => ', started_at=NOW()',
        'closed'  => ', closed_at=NOW()',
        'waiting' => ', is_assigned=0, assigned_at=NULL, expires_at=NULL, assigned_to=NULL, instance_id=NULL',
        default   => ''
    };
    $up = $pdo->prepare("UPDATE rooms SET status=? $extraSql WHERE instance_id=?");
    $up->execute([$newStatus, $instanceId]);
    rs_out(['ok'=>true,'updated'=>$up->rowCount(),'status'=>$newStatus]);
} catch (Throwable $e) {
    rs_out(['ok'=>false,'error'=>$e->getMessage()], 500);
}
