<?php
require __DIR__ . '/app/bootstrap.php';
require_auth();

$id=(int)request('id',0);
if($id<1){http_response_code(404);exit('Comprovante não encontrado.');}
$q=db()->prepare('SELECT r.*,pu.name payer_name,pu.username payer_username,pu.public_id payer_public_id,ru.name recipient_name,c.name company_name,c.logo company_logo,c.document company_document FROM receipts r LEFT JOIN users pu ON pu.id=r.payer_user_id LEFT JOIN users ru ON ru.id=r.recipient_user_id LEFT JOIN companies c ON c.id=r.company_id WHERE r.id=? LIMIT 1');
$q->execute([$id]);$receipt=$q->fetch();
if(!$receipt){http_response_code(404);exit('Comprovante não encontrado.');}

$user=current_user();$uid=(int)$user['id'];
$allowed=is_admin()||$uid===(int)$receipt['payer_user_id']||$uid===(int)$receipt['recipient_user_id'];
if(!$allowed){http_response_code(403);exit('Sem permissão para acessar este comprovante.');}

$code=transaction_receipt_code($receipt);
if(trim((string)($receipt['receipt_code']??''))===''){
    try{db()->prepare('UPDATE receipts SET receipt_code=? WHERE id=?')->execute([$code,$id]);}catch(Throwable $ignored){}
}
$business=(string)($receipt['company_name']?:$receipt['recipient_name']?:platform_name());
$created=(string)($receipt['created_at']?:now());
$svg=receipt_svg_document([
    'title'=>'COMPROVANTE DE PAGAMENTO',
    'business'=>$business,
    'document'=>!empty($receipt['company_document'])?masked_tax_document((string)$receipt['company_document']):'',
    'status'=>'PAGAMENTO CONFIRMADO',
    'client'=>user_public_name(['name'=>$receipt['payer_name']??'','username'=>$receipt['payer_username']??'','public_id'=>$receipt['payer_public_id']??'']),
    'service'=>(string)($receipt['description']?:status_label((string)$receipt['source_type']).' #'.(int)$receipt['source_id']),
    'value'=>money((float)$receipt['amount']),
    'date'=>date('d/m/Y \à\s H:i',strtotime($created)),
    'payment'=>status_label((string)($receipt['payment_method']?:'pix')),
    'responsible'=>$business,
    'code'=>$code,
    'generated'=>date('d/m/Y',strtotime($created)),
    'platform_logo'=>trim((string)setting('brand_logo','')),
    'company_logo'=>(string)($receipt['company_logo']??''),
    'footer'=>'Documento digital de confirmação do pagamento',
]);

if((int)request('svg',0)===1 || (int)request('raw',0)===1){
    header('Content-Type: image/svg+xml; charset=UTF-8');
    header('Cache-Control: private, max-age=300');
    header('X-Content-Type-Options: nosniff');
    echo $svg;exit;
}

$returnPage=preg_replace('/[^a-z_]/','',(string)request('return',''));
if($returnPage===''){
    $returnPage=match((string)$receipt['source_type']){
        'order'=>'orders','service'=>'services','ride'=>'rides','vehicle_rental'=>'vehicles',
        'property_booking'=>'properties','charge','subscription'=>'charges',default=>'finance'
    };
}
$returnUrl='dashboard.php?page='.$returnPage;
$autoDownload=(int)request('download',0)===1;
?>
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Comprovante <?=$code?></title>
<style>
*{box-sizing:border-box}body{margin:0;background:#edf5ff;color:#162033;font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
.bar{position:sticky;top:0;z-index:10;display:flex;gap:10px;justify-content:center;align-items:center;padding:12px;background:#fff;border-bottom:1px solid #dbe5ef;box-shadow:0 4px 18px #17375b12}
.btn{border:0;border-radius:12px;padding:11px 16px;font:inherit;font-weight:800;text-decoration:none;cursor:pointer}.primary{background:#1763aa;color:#fff}.secondary{background:#eef3f8;color:#162033}
.wrap{padding:16px}.receipt-img{display:block;width:min(100%,760px);height:auto;margin:auto;border-radius:22px;box-shadow:0 16px 45px #183b6828;background:#fff}
@media(max-width:600px){.bar{padding:9px;position:sticky}.btn{padding:10px 12px;font-size:14px}.wrap{padding:8px}.receipt-img{border-radius:16px}}
</style>
</head>
<body>
<div class="bar">
<button class="btn secondary" type="button" onclick="closeReceipt()">✕ Fechar</button>
<button class="btn primary" type="button" onclick="downloadReceiptPng()">⬇ Baixar PNG</button>
</div>
<main class="wrap"><img class="receipt-img" src="receipt.php?id=<?=$id?>&svg=1" alt="Comprovante de pagamento"></main>
<script>
const receiptReturn=<?=json_encode($returnUrl,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)?>;
function closeReceipt(){
  if(window.opener&&!window.opener.closed){window.close();return;}
  window.location.href=receiptReturn;
}
async function downloadReceiptPng(){
  const button=document.activeElement; if(button&&button.tagName==='BUTTON')button.disabled=true;
  try{
    const response=await fetch('receipt.php?id=<?=$id?>&svg=1',{credentials:'same-origin',cache:'no-store'});
    if(!response.ok)throw new Error('Falha ao carregar comprovante');
    const text=await response.text();
    const blob=new Blob([text],{type:'image/svg+xml;charset=utf-8'});
    const objectUrl=URL.createObjectURL(blob);
    const img=new Image();
    await new Promise((resolve,reject)=>{img.onload=resolve;img.onerror=reject;img.src=objectUrl;});
    const canvas=document.createElement('canvas');canvas.width=1080;canvas.height=1350;
    const ctx=canvas.getContext('2d');ctx.drawImage(img,0,0,1080,1350);URL.revokeObjectURL(objectUrl);
    const png=await new Promise(resolve=>canvas.toBlob(resolve,'image/png',0.96));
    if(!png)throw new Error('Falha ao gerar PNG');
    const link=document.createElement('a');link.href=URL.createObjectURL(png);link.download='comprovante-<?=$code?>.png';document.body.appendChild(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(link.href),1200);
  }catch(error){alert('Não foi possível gerar o PNG agora. Tente novamente.');}
  finally{if(button&&button.tagName==='BUTTON')button.disabled=false;}
}
<?php if($autoDownload):?>window.addEventListener('load',()=>setTimeout(downloadReceiptPng,250));<?php endif;?>
</script>
</body></html>
