<?php
require_once __DIR__ . '/config.php';
if (function_exists('gemaccAdminChatEnsureSchema')) gemaccAdminChatEnsureSchema($pdo);
$messageId=(int)($_GET['message_id']??0);
$uid=miniapp_authenticated_user_id();
if($messageId<=0||$uid<=0){http_response_code(400);exit('invalid request');}
$st=$pdo->prepare("SELECT sm.*,t.user_id FROM support_messages sm JOIN support_tickets t ON t.id=sm.ticket_id WHERE sm.id=? LIMIT 1");
$st->execute([$messageId]);$m=$st->fetch(PDO::FETCH_ASSOC);
if(!$m || (!isAdmin($uid) && (int)$m['user_id']!==$uid)){http_response_code(403);exit('forbidden');}
$local=trim((string)($m['attachment_path']??''));
if($local!==''){
    $root=realpath(dirname(__DIR__,3));
    $allowedRoot=realpath(dirname(__DIR__,3).'/public/mini_app/uploads/support');
    $abs=realpath(dirname(__DIR__,3).'/'.ltrim($local,'/'));
    if($root===false||$allowedRoot===false||$abs===false||!is_file($abs)||!str_starts_with($abs,$allowedRoot.DIRECTORY_SEPARATOR)){http_response_code(404);exit('file not found');}
    $mime=trim((string)($m['attachment_mime']??''))?:'application/octet-stream';
    header('Content-Type: '.$mime);header('X-Content-Type-Options: nosniff');header('Cache-Control: private, max-age=300');
    header('Content-Disposition: inline; filename="'.preg_replace('/[^A-Za-z0-9._-]+/','_',basename((string)($m['attachment_name']?:$abs))).'"');
    readfile($abs);exit;
}
$fileId=trim((string)($m['telegram_file_id']??''));
if($fileId===''){http_response_code(404);exit('file not found');}
$res=tg('getFile',['file_id'=>$fileId]);
if(!is_array($res)||empty($res['ok'])||empty($res['result']['file_path'])){http_response_code(404);exit('file not found');}
$path=(string)$res['result']['file_path'];$ext=strtolower(pathinfo($path,PATHINFO_EXTENSION));
$map=['jpg'=>'image/jpeg','jpeg'=>'image/jpeg','png'=>'image/png','gif'=>'image/gif','webp'=>'image/webp','pdf'=>'application/pdf','mp4'=>'video/mp4','ogg'=>'audio/ogg','mp3'=>'audio/mpeg','zip'=>'application/zip'];
header('Content-Type: '.($map[$ext]??((string)($m['attachment_mime']??'application/octet-stream'))));
header('X-Content-Type-Options: nosniff');
$url='https://api.telegram.org/file/bot'.BOT_TOKEN.'/'.str_replace('%2F','/',rawurlencode($path));
if(function_exists('curl_init')){$ch=curl_init($url);curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_FOLLOWLOCATION=>true,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;exit;}}
if(ini_get('allow_url_fopen')){$body=@file_get_contents($url);if($body!==false){echo $body;exit;}}
http_response_code(502);echo 'download failed';
