<?php
require __DIR__.'/app/bootstrap.php';require_auth();
$id=(int)request('id',0);if($id<1){http_response_code(404);exit('Consulta não encontrada.');}
$q=db()->prepare("SELECT a.*,c.name clinic_name,c.document clinic_document,c.logo clinic_logo,c.phone clinic_phone,c.address,c.address_number,c.city,c.state,pa.platform_user_id,pa.name patient_name,pu.name platform_patient_name,pu.username patient_username,pu.public_id patient_public_id,pr.user_id professional_user_id,pr.name professional_name,s.name specialty_name FROM clinic_appointments a JOIN companies c ON c.id=a.company_id JOIN clinic_patients pa ON pa.id=a.patient_id LEFT JOIN users pu ON pu.id=pa.platform_user_id LEFT JOIN clinic_professionals pr ON pr.id=a.professional_id LEFT JOIN clinic_specialties s ON s.id=a.specialty_id WHERE a.id=? LIMIT 1");
$q->execute([$id]);$a=$q->fetch();if(!$a){http_response_code(404);exit('Consulta não encontrada.');}
$u=current_user();$uid=(int)$u['id'];$companyId=resolve_company_id_for_user($u);
$allowed=is_admin()||$uid===(int)$a['platform_user_id']||$uid===(int)($a['professional_user_id']??0)||($companyId>0&&$companyId===(int)$a['company_id']);
if(!$allowed){http_response_code(403);exit('Sem permissão para acessar este comprovante.');}

$code=clinic_appointment_receipt_code($a);
if(trim((string)($a['receipt_code']??''))===''){
    try{db()->prepare('UPDATE clinic_appointments SET receipt_code=? WHERE id=?')->execute([$code,$id]);}catch(Throwable $ignored){}
}
$paid=in_array((string)($a['payment_status']??''),['paid','confirmed','approved'],true);
$title=$paid?'COMPROVANTE DE PAGAMENTO':'COMPROVANTE DE AGENDAMENTO';
$statusLabel=status_label((string)($a['status']??'scheduled'));$status=$paid?'PAGAMENTO CONFIRMADO':(function_exists('mb_strtoupper')?mb_strtoupper($statusLabel,'UTF-8'):strtoupper($statusLabel));
$patient=user_public_name(['name'=>$a['platform_patient_name']?:$a['patient_name'],'username'=>$a['patient_username']??'','public_id'=>$a['patient_public_id']??'']);
$when=date('d/m/Y',strtotime((string)$a['appointment_date'])).' às '.substr((string)$a['appointment_time'],0,5);
$payment=$paid?status_label((string)($a['payment_method']?:'pix')):status_label((string)($a['payment_status']?:'pending'));
$created=(string)($a['updated_at']?:$a['created_at']?:now());
$svg=receipt_svg_document([
    'title'=>$title,
    'business'=>(string)$a['clinic_name'],
    'document'=>!empty($a['clinic_document'])?masked_tax_document((string)$a['clinic_document']):'',
    'status'=>$status,
    'client_label'=>'Paciente',
    'client'=>$patient,
    'service_label'=>'Consulta / serviço',
    'service'=>(string)($a['specialty_name']?:'Consulta'),
    'value_label'=>$paid?'Valor pago':'Valor',
    'value'=>money((float)$a['amount']),
    'date_label'=>'Data e horário',
    'date'=>$when,
    'payment_label'=>'Pagamento',
    'payment'=>$payment,
    'responsible_label'=>'Profissional responsável',
    'responsible'=>(string)($a['professional_name']?:'A definir'),
    'code'=>$code,
    'generated'=>date('d/m/Y',strtotime($created)),
    'platform_logo'=>trim((string)setting('brand_logo','')),
    'company_logo'=>(string)($a['clinic_logo']??''),
    'footer'=>'Documento digital de confirmação do agendamento',
]);
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=$uid===(int)$a['platform_user_id']?'clinic_patient':'clinic';
$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;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}.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="clinic_receipt.php?id=<?=$id?>&svg=1" alt="Comprovante de agendamento"></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('clinic_receipt.php?id=<?=$id?>&svg=1',{credentials:'same-origin',cache:'no-store'});if(!response.ok)throw new Error();
 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;canvas.getContext('2d').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();const link=document.createElement('a');link.href=URL.createObjectURL(png);link.download='comprovante-agendamento-<?=$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>
