<?php
declare(strict_types=1);

/**
 * file_serve.php
 * Secure streaming endpoint (requires login).
 * Streams the file from server path stored in DB.
 */

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

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

$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("Not found"); }

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

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

header("Content-Type: {$mime}");
header("X-Content-Type-Options: nosniff");
header('Content-Disposition: inline; filename="' . basename($fullPath) . '"');
header('Content-Length: ' . filesize($fullPath));

$fp = fopen($fullPath, 'rb');
fpassthru($fp);
exit;
