<?php
require_once __DIR__ . '/config.php';

$adminId = miniapp_require_admin();
$fileId = trim((string)($_GET['file_id'] ?? $_POST['file_id'] ?? ''));
if ($fileId === '') {
    http_response_code(400);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'file_id required';
    exit;
}

$res = tg('getFile', ['file_id' => $fileId]);
if (!is_array($res) || empty($res['ok']) || empty($res['result']['file_path'])) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'file not found';
    exit;
}

$path = (string)$res['result']['file_path'];
$basename = basename($path);
$ext = strtolower(pathinfo($basename, PATHINFO_EXTENSION));
$mimeMap = [
    'jpg'=>'image/jpeg','jpeg'=>'image/jpeg','png'=>'image/png','gif'=>'image/gif','webp'=>'image/webp',
    'pdf'=>'application/pdf','txt'=>'text/plain','mp4'=>'video/mp4','mov'=>'video/quicktime','webm'=>'video/webm',
    'zip'=>'application/zip','rar'=>'application/vnd.rar','7z'=>'application/x-7z-compressed'
];
$mime = $mimeMap[$ext] ?? 'application/octet-stream';
$url = 'https://api.telegram.org/file/bot' . BOT_TOKEN . '/' . str_replace('%2F', '/', rawurlencode($path));

header('Content-Type: ' . $mime);
header('Content-Disposition: inline; filename="' . preg_replace('/[^A-Za-z0-9._-]+/', '_', $basename) . '"');
header('X-Content-Type-Options: nosniff');

$sent = false;
if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_FOLLOWLOCATION=>true, CURLOPT_CONNECTTIMEOUT=>10, CURLOPT_TIMEOUT=>60]);
    $body = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($body !== false && $code >= 200 && $code < 300) { echo $body; $sent = true; }
}
if (!$sent && ini_get('allow_url_fopen')) {
    $body = @file_get_contents($url);
    if ($body !== false) { echo $body; $sent = true; }
}
if (!$sent) {
    http_response_code(502);
    echo 'download failed';
}
