<?php
require_once '../../config/db.php';
require_once '../../core/Auth.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    $user_id = Auth::check();
    $data = json_decode(file_get_contents("php://input"));
    
    // Optional: Update viewers count if sent from client (or source of truth could be RTMP stats)
    // For now we assume client sends estimated viewers or we just keep "alive"
    
    $viewers = isset($data->viewers) ? (int)$data->viewers : null;
    
    if ($viewers !== null) {
        $stmt = $pdo->prepare("UPDATE streams SET viewers = ? WHERE user_id = ? AND is_live = TRUE");
        $stmt->execute([$viewers, $user_id]);
    } else {
        // Just check if live
    }
    
    echo json_encode(['status' => 'alive']);

} catch (Exception $e) {
    http_response_code(401);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
