<?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"));
    
    $title = isset($data->title) ? trim($data->title) : "Live Stream";
    
    // Generate Stream Key (Simple hash for now)
    $stream_key = 'live_' . $user_id . '_' . bin2hex(random_bytes(8));
    
    // Check if checks active stream exists? Maybe reuse or close old ones?
    $pdo->prepare("UPDATE streams SET is_live = FALSE, ended_at = NOW() WHERE user_id = ? AND is_live = TRUE")->execute([$user_id]);

    $stmt = $pdo->prepare("INSERT INTO streams (user_id, title, stream_key, is_live, started_at) VALUES (?, ?, ?, TRUE, NOW())");
    $stmt->execute([$user_id, $title, $stream_key]);
    
    $stream_id = $pdo->lastInsertId();
    
    // Construct RTMP URL (Mock)
    // In real app, this comes from config
    $rtmp_url = "rtmp://localhost/live";

    echo json_encode([
        'status' => 'live',
        'stream_id' => $stream_id,
        'stream_key' => $stream_key,
        'rtmp_url' => $rtmp_url,
        'playback_url' => "http://localhost/hls/$stream_key.m3u8"
    ]);

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