<?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();
    
    // Close active streams for this user
    $stmt = $pdo->prepare("UPDATE streams SET is_live = FALSE, ended_at = NOW() WHERE user_id = ? AND is_live = TRUE");
    $stmt->execute([$user_id]);
    
    if ($stmt->rowCount() > 0) {
        echo json_encode(['status' => 'stopped', 'message' => 'Stream ended successfully']);
    } else {
        echo json_encode(['status' => 'no_stream', 'message' => 'No active stream found']);
    }

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