<?php
// ===============================
// download.php  (Telegram Safe MIME)
// ===============================

require_once 'madeline.php';
use danog\MadelineProto\API;
ignore_user_abort(true);
set_time_limit(0);

$MadelineProto = null; // global for shutdown function

// --- Ensure MadelineProto closes no matter what ---
register_shutdown_function(function() use (&$MadelineProto) {
    if (isset($MadelineProto)) {
        try {
            $MadelineProto->close();
        } catch (Throwable $e) {}
        $MadelineProto = null;
    }
    gc_collect_cycles();
});

/* ===============================
   INPUT
================================ */
if (!isset($_GET['id'])) {
    http_response_code(400);
    exit('Missing message id');
}

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

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

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

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

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

try {

    $MadelineProto = new API('session1.madeline');
    $MadelineProto->start();

    /* ===============================
       FETCH MESSAGE
    ================================ */
    $message = $MadelineProto->channels->getMessages([
        'channel' => $channel,
        'id'      => [$msg_id]
    ]);

    $media = $message['messages'][0]['media'] ?? null;
    $doc   = $media['document'] ?? $media['video'] ?? null;

    if (!$doc) {
        http_response_code(404);
        exit('No media found');
    }
    
/* ===============================
   FILENAME FROM URL
================================ */
// Full request URI
$uri = $_SERVER['REQUEST_URI'];

// last part after /
$filename = basename(parse_url($uri, PHP_URL_PATH));

// fallback safety
if (!$filename) {
    $filename = 'Inddrive_File_'.$msg_id;
}

/* ===============================
HEADERS
================================ */
header("Content-Type: $mime");
header('Content-Disposition: inline; filename="'.$filename.'"');
header("Cache-Control: no-store");
header("Accept-Ranges: none");


    /* ===============================
       STREAM
    ================================ */
    $MadelineProto->downloadToBrowser($doc);

} catch (Throwable $e) {
    http_response_code(500);
    echo "Error: " . $e->getMessage();
} finally {
    if ($MadelineProto) {
        try { $MadelineProto->close(); } catch (Throwable $e) {}
    }
    gc_collect_cycles();
}
exit;
 
?>
