<?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 LIMIT 1");
$stmt->execute([':id' => $fileId]);
$file = $stmt->fetch();
if (!$file) { http_response_code(404); exit; }

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

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

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

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

if (!empty($_SERVER['HTTP_RANGE']) && preg_match('/bytes=(\d+)-(\d*)/', $_SERVER['HTTP_RANGE'], $m)) {
  $start = (int)$m[1];
  if ($m[2] !== '') $end = (int)$m[2];
  if ($start > $end || $end >= $size) { http_response_code(416); exit; }

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

$length = $end - $start + 1;
header("Content-Length: {$length}");

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

$chunk = 8192;
while (!feof($fp) && ftell($fp) <= $end) {
  $remaining = $end - ftell($fp) + 1;
  echo fread($fp, ($remaining < $chunk) ? $remaining : $chunk);
  flush();
}
fclose($fp);
exit;
