<?php
declare(strict_types=1);

require __DIR__ . '/auth.php';
require __DIR__ . '/db.php';

$fileId = (int)($_GET['file_id'] ?? 0);
if ($fileId <= 0) {
    http_response_code(400);
    exit;
}

$stmt = $pdo->prepare("SELECT path, type FROM files WHERE id = :id AND is_active = 1");
$stmt->execute([':id' => $fileId]);
$file = $stmt->fetch();

if (!$file) {
    http_response_code(404);
    exit;
}

$path = $file['path'];
if (!is_file($path)) {
    http_response_code(404);
    exit;
}

$size = filesize($path);
$mime = ($file['type'] === 'mp4') ? 'video/mp4' : 'application/pdf';

header("Content-Type: {$mime}");
header("Accept-Ranges: bytes");

$start = 0;
$end = $size - 1;

if (isset($_SERVER['HTTP_RANGE'])) {
    // Example: bytes=0-1023
    if (preg_match('/bytes=(\\d+)-(\\d*)/', $_SERVER['HTTP_RANGE'], $matches)) {
        $start = (int)$matches[1];
        if ($matches[2] !== '') {
            $end = (int)$matches[2];
        }
        http_response_code(206);
    }
}

$length = $end - $start + 1;

header("Content-Length: {$length}");
header("Content-Range: bytes {$start}-{$end}/{$size}");

$fp = fopen($path, 'rb');
fseek($fp, $start);

$buffer = 8192;
while (!feof($fp) && ($pos = ftell($fp)) <= $end) {
    if ($pos + $buffer > $end) {
        $buffer = $end - $pos + 1;
    }
    echo fread($fp, $buffer);
    flush();
}
fclose($fp);
exit;
