<?php

if (!isset($_GET['path'])) {
    http_response_code(400);
    echo "Missing 'path' parameter.";
    exit;
}

$relativePath = ltrim($_GET['path'], '/');

// Validate file extension
if (strtolower(pathinfo($relativePath, PATHINFO_EXTENSION)) !== 'mp4') {
    http_response_code(403);
    echo "Only .mp4 files are allowed.";
    exit;
}

$ftpHost = '192.168.0.1';
$ftpPort = 21;
$ftpUser = 'anonymous';
$ftpPass = ''; // Typically anonymous password can be blank or email

// Connect to FTP
$conn = ftp_connect($ftpHost, $ftpPort, 10);
if (!$conn || !ftp_login($conn, $ftpUser, $ftpPass)) {
    http_response_code(500);
    echo "FTP connection failed.";
    exit;
}

// Get file size
$size = ftp_size($conn, $relativePath);
if ($size === -1) {
    ftp_close($conn);
    http_response_code(404);
    echo "File not found on FTP server.";
    exit;
}

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

if (isset($_SERVER['HTTP_RANGE']) &&
    preg_match('/bytes=(\d+)-(\d*)/', $_SERVER['HTTP_RANGE'], $matches)) {
    
    $start = intval($matches[1]);
    $end = ($matches[2] !== '') ? intval($matches[2]) : $end;

    if ($start > $end || $start >= $size) {
        ftp_close($conn);
        http_response_code(416);
        header("Content-Range: bytes */$size");
        exit;
    }

    $length = $end - $start + 1;
    http_response_code(206);
    header("Content-Range: bytes $start-$end/$size");
} else {
    http_response_code(200);
}

// Set headers
$filename = basename($relativePath);
header("Content-Type: video/mp4");
header("Content-Length: $length");
header("Accept-Ranges: bytes");
header("Content-Disposition: inline; filename=\"$filename\"");

// Open a temp stream
$tempHandle = fopen('php://temp', 'r+');

if (!ftp_fget($conn, $tempHandle, $relativePath, FTP_BINARY, 0)) {
    ftp_close($conn);
    http_response_code(500);
    echo "Failed to download file from FTP.";
    exit;
}
ftp_close($conn);

// Seek to the range offset
rewind($tempHandle);
if ($start > 0) {
    fseek($tempHandle, $start);
}

// Stream the requested range
$remaining = $length;
while (!feof($tempHandle) && $remaining > 0) {
    $chunkSize = min(8192, $remaining);
    $data = fread($tempHandle, $chunkSize);
    echo $data;
    flush();
    $remaining -= strlen($data);
}

fclose($tempHandle);
