<?php
// ===============================
// tmpdownload.php LIVE STREAM + CACHE
// ===============================
ignore_user_abort(true);
set_time_limit(0);
while (ob_get_level()) ob_end_flush();
ob_implicit_flush(true);

/* ===============================
   INPUT
================================ */
if (!isset($_GET['id'], $_GET['p'])) {
    http_response_code(400);
    exit('Invalid request');
}

$msg_id = (int) $_GET['id'];
$short  = $_GET['code'] ?? '';

/* ===============================
   UNPACK PAYLOAD
================================ */
$data = json_decode(
    base64_decode(strtr($_GET['p'], '-_', '+/')),
    true
);

if (!$data || empty($data['channel'])) {
    http_response_code(403);
    exit('Invalid payload');
}

$mime   = $data['mime'] ?? 'application/octet-stream';
$expire = (int) ($data['expire'] ?? 0);

if ($expire && time() > $expire) {
    header("Location: https://inddrive.com/{$short}");
    exit;
}

/* ===============================
   SAFE FILENAME
================================ */
$filename = urldecode($data['name'] ?? '');
$filename = basename($filename);
$filename = preg_replace('/[^\w\-. \[\]]/u', '', $filename);

if ($filename === '') {
    $filename = 'ZukuPlay_File_' . $msg_id;
}

/* ===============================
   CACHE PATH 
================================ */
$baseCache = __DIR__ . '/tmp_cache';
$msgDir    = $baseCache . '/' . $msg_id;
$cacheFile = $msgDir . '/' . $filename;
$tmpFile   = $cacheFile . '.tmp';
$lockFile  = $cacheFile . '.lock';

if (!is_dir($msgDir)) {
    mkdir($msgDir, 0777, true);
}

/* ===============================
   CACHE PATH
================================ */
if (is_file($cacheFile)) {

    touch($cacheFile);
    $directUrl =
        'https://dl.inddrive.com/tmp_cache/' . $msg_id . '/' . $filename;

    header("Location: $directUrl", true, 302);
    exit;
}

/* ===============================
   TRY LOCK (NO WAIT)
================================ */
$lockFp = fopen($lockFile, 'c');
$gotLock = flock($lockFp, LOCK_EX | LOCK_NB);

/* ===============================
   LOCK BUSY → DIRECT SERVER-B
================================ */
if (!$gotLock) {
    $directUrl =
        'https://dl.inddrive.com/download/' .
        $msg_id . '/' . rawurlencode($filename) .
        '?code=' . urlencode($short) .
        '&p=' . urlencode($_GET['p']);

    header("Location: $directUrl", true, 302);
    exit;
}

/* ===============================
   FIRST USER → LIVE STREAM + CACHE
================================ */
$fp = fopen($tmpFile, 'wb');

$downloaderUrl =
    'https://dl.inddrive.com/download/' .
    $msg_id . '/' . rawurlencode($filename) .
    '?code=' . urlencode($short) .
    '&p=' . urlencode($_GET['p']);

header("Content-Type: $mime");
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Cache-Control: no-store");
header("X-Accel-Buffering: no");
header("Connection: keep-alive");

$ch = curl_init($downloaderUrl);

curl_setopt_array($ch, [
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS      => 5,
    CURLOPT_TIMEOUT        => 0,
    CURLOPT_CONNECTTIMEOUT => 15,
    CURLOPT_BUFFERSIZE     => 1048576,
    CURLOPT_RETURNTRANSFER => false,
    CURLOPT_HEADER         => false,

    // 🔥 forward browser range request
    CURLOPT_HTTPHEADER => array_filter([
        isset($_SERVER['HTTP_RANGE']) ? 'Range: '.$_SERVER['HTTP_RANGE'] : null
    ]),

    CURLOPT_WRITEFUNCTION => function ($ch, $data) use ($fp) {
        $len = strlen($data);
        if ($len === 0) return 0;

        echo $data;
        fwrite($fp, $data);

        flush();
        return $len;
    }
]);

curl_exec($ch);

$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

curl_close($ch);
fclose($fp);


/* ===============================
   COMMIT CACHE
================================ */
if (
    $http === 200 &&
    strpos($contentType, 'text/html') === false &&
    file_exists($tmpFile) &&
    filesize($tmpFile) > 1024
) {
    rename($tmpFile, $cacheFile);
    touch($cacheFile);
} else {
    @unlink($tmpFile);
}



/* ===============================
   RELEASE LOCK
================================ */
flock($lockFp, LOCK_UN);
fclose($lockFp);
@unlink($lockFile);
exit;
