<?php
$file = $_GET['file'] ?? '';
$clean = rawurldecode($file);
$path = realpath(__DIR__ . '/' . $clean);

if (!$path || strpos($path, realpath(__DIR__)) !== 0) {
    http_response_code(404);
    die("فایل پیدا نشد");
}

$size = filesize($path);
$fp = fopen($path, 'rb');
$start = 0;
$end = $size - 1;

header("Accept-Ranges: bytes");

if (isset($_SERVER['HTTP_RANGE'])) {
    preg_match('/bytes=(\d+)-(\d*)/', $_SERVER['HTTP_RANGE'], $m);

    $start = intval($m[1]);
    if ($m[2] !== '') $end = intval($m[2]);

    header("HTTP/1.1 206 Partial Content");
}

$length = $end - $start + 1;

header("Content-Type: video/mp4");
header("Content-Length: $length");
header("Content-Range: bytes $start-$end/$size");

fseek($fp, $start);

$buffer = 1024 * 8;
while (!feof($fp) && ftell($fp) <= $end) {
    echo fread($fp, $buffer);
    flush();
}

fclose($fp);
exit;
