<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/_vpn_helpers.php';
if (function_exists('vpnEnsureColumns')) vpnEnsureColumns($pdo);
$deliveryId=(int)($_GET['delivery_id']??0);
$uid=miniapp_authenticated_user_id();
if($deliveryId<=0||$uid<=0){http_response_code(400);exit('invalid request');}
$st=$pdo->prepare("SELECT d.id,d.user_id,d.qr_code_file_id,d.qr_code_path,d.service_type,o.user_id AS order_user_id FROM deliveries d LEFT JOIN orders o ON o.id=d.order_id WHERE d.id=? LIMIT 1");
$st->execute([$deliveryId]);$row=$st->fetch(PDO::FETCH_ASSOC);
if(!$row){http_response_code(404);exit('not found');}
$owner=(int)($row['user_id']??$row['order_user_id']??0);
if(!isAdmin($uid) && $owner!==$uid){http_response_code(403);exit('forbidden');}
$service=function_exists('vpnServiceType')?vpnServiceType(['service_type'=>(string)($row['service_type']??'')]):(string)($row['service_type']??'');
if($service!=='v2ray'){http_response_code(404);exit('not a v2ray delivery');}
$local=trim((string)($row['qr_code_path']??''));
if($local!==''){
    $root=realpath(dirname(__DIR__,3));
    $allowedRoot=realpath(dirname(__DIR__,3).'/public/mini_app/uploads/v2ray_qr');
    $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');}
    $ext=strtolower(pathinfo($abs,PATHINFO_EXTENSION));$map=['jpg'=>'image/jpeg','jpeg'=>'image/jpeg','png'=>'image/png','webp'=>'image/webp','gif'=>'image/gif'];
    header('Content-Type: '.($map[$ext]??'application/octet-stream'));header('X-Content-Type-Options: nosniff');header('Cache-Control: private, max-age=300');
    readfile($abs);exit;
}
$fileId=trim((string)($row['qr_code_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'];
header('Content-Type: '.($map[$ext]??'image/jpeg'));header('X-Content-Type-Options: nosniff');header('Cache-Control: private, max-age=300');
$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';
