<?php
error_reporting(0);
$file = $_GET['file'] ?? '';
$ip = $_SERVER['REMOTE_ADDR'];

$base_dir = realpath(_DIR_ . '/../streams/');
$real_path = realpath($base_dir . '/' . $file);

if ($real_path && strpos($real_path, $base_dir) === 0 && file_exists($real_path)) {
    require_once '../includes/db.php';
    if (session_status() === PHP_SESSION_ACTIVE) { session_write_close(); }

    if (preg_match('/canal_([0-9]+)/', $file, $matches)) {
        $channel_id = $matches[1];
        try {
            $pdo->prepare("UPDATE active_connections SET start_time = ? WHERE user_ip = ? AND content_id = ? AND stream_type = 'live'")->execute([time(), $ip, $channel_id]);
        } catch (Exception $e) {}
    }
    
    $pdo = null;

    header('Content-Type: video/mp2t');
    header('Content-Length: ' . filesize($real_path));
    header('Cache-Control: no-cache, no-store, must-revalidate');
    
    if (ob_get_level()) { ob_end_clean(); }
    flush();
    
    readfile($real_path);
    exit;
}
http_response_code(404);
?>
