<?php
require_once 'madeline.php';
use danog\MadelineProto\API;

ignore_user_abort(true); // continue script if user cancels download
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 check ---
if (!isset($_GET['id'])) {
    http_response_code(400);
    exit("❌ Missing id");
}

$msg_id  = (int)$_GET['id'];
$channel = '-1002982748822';

try {
    
        // --- Close any previous MadelineProto session first ---
    if (isset($MadelineProto)) {
        try {
            $MadelineProto->close();
        } catch (Throwable $e) {}
        $MadelineProto = null;
        gc_collect_cycles();
    }
    
    // --- Init MadelineProto session ---
    $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");
    }

    // --- Get download info ---
    $info = $MadelineProto->getDownloadInfo($doc);
    $name = $info['name'] ?? 'file';
    $mime = $info['mime'] ?? 'application/octet-stream';

    // --- Auto add missing extension ---
    if (!pathinfo($name, PATHINFO_EXTENSION)) {
        $extMap = [
            'video/mp4'              => 'mp4',
            'video/x-matroska'       => 'mkv',
            'audio/mpeg'             => 'mp3',
            'application/vnd.android.package-archive' => 'apk',
            'application/zip'        => 'zip',
            'image/jpeg'             => 'jpg',
            'image/png'              => 'png',
            'application/pdf'        => 'pdf'
        ];
        $ext = $extMap[$mime] ?? '';
        if ($ext) $name .= ".$ext";
    }

    // --- Send headers ---
    header("Content-Type: $mime");
    header("Content-Disposition: inline; filename=\"" . basename($name) . "\"");
    header("Cache-Control: public, must-revalidate, max-age=0");

    // --- Stream file to browser ---
    $MadelineProto->downloadToStream($doc, fopen('php://output', 'w'));


} catch (Throwable $e) {
    http_response_code(500);
    echo "❌ Error: " . $e->getMessage();
}

// --- cleanup handled by shutdown_function ---
exit;
