<?php
ob_end_clean();

if (!isset($_GET['url'])) {
    http_response_code(400);
    exit('No URL');
}

$url = $_GET['url'];

if (!filter_var($url, FILTER_VALIDATE_URL)) {
    http_response_code(400);
    exit('Invalid URL');
}

// ambil range dari browser (WAJIB untuk mobile)
$headers = [];

if (isset($_SERVER['HTTP_RANGE'])) {
    $headers[] = "Range: " . $_SERVER['HTTP_RANGE'];
}

$headers[] = "User-Agent: Mozilla/5.0";
$headers[] = "Referer: https://dramaboxdb.com/";
$headers[] = "Origin: https://dramaboxdb.com";

$ch = curl_init($url);

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => false, // 🔥 langsung stream
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_BUFFERSIZE => 8192,
    CURLOPT_HTTPHEADER => $headers,

    // 🔥 kirim langsung ke browser
    CURLOPT_WRITEFUNCTION => function($ch, $data) {
        echo $data;
        flush();
        return strlen($data);
    },

    // 🔥 handle header dari server video
    CURLOPT_HEADERFUNCTION => function($ch, $header) {
        $len = strlen($header);

        if (stripos($header, 'Content-Type:') === 0 ||
            stripos($header, 'Content-Length:') === 0 ||
            stripos($header, 'Accept-Ranges:') === 0 ||
            stripos($header, 'Content-Range:') === 0) {
            header(trim($header));
        }

        return $len;
    }
]);

http_response_code(206); // penting untuk streaming

curl_exec($ch);

if (curl_errno($ch)) {
    http_response_code(500);
    echo 'Stream Error';
}

curl_close($ch);