<?php
require_roles('super_admin');
$code=strtoupper(preg_replace('/[^A-Z0-9]/','',trim((string)request('code',''))));
$results=[];
$seen=[];
$pushReceipt=function(array $r,string $kind='Pagamento',?string $displayCode=null)use(&$results,&$seen){
    $id=(int)($r['id']??0);if($id<1||isset($seen['receipt:'.$id]))return;
    $seen['receipt:'.$id]=true;
    $results[]=[
        'kind'=>$kind,
        'code'=>$displayCode?:transaction_receipt_code($r),
        'title'=>(string)($r['description']?:status_label((string)$r['source_type']).' #'.(int)$r['source_id']),
        'party'=>(string)($r['payer_name']?:'Cliente').' → '.(string)($r['company_name']?:$r['recipient_name']?:platform_name()),
        'date'=>(string)$r['created_at'],
        'amount'=>(float)$r['amount'],
        'url'=>'receipt.php?id='.$id.'&return=receipt_search',
    ];
};
if($code!==''){
    // 1) Código atual persistido no banco (quando a coluna receipt_code já existe).
    try{
        $q=db()->prepare("SELECT r.*,pu.name payer_name,ru.name recipient_name,c.name company_name
            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 upper(COALESCE(r.receipt_code,''))=?
            ORDER BY r.id DESC LIMIT 20");
        $q->execute([$code]);
        foreach($q->fetchAll() as $r)$pushReceipt($r);
    }catch(Throwable $ignored){}

    // 2) Número do pedido LX... exibido no corpo do comprovante.
    // Esta busca NÃO depende da coluna receipt_code, portanto funciona também
    // em bancos antigos que ainda não executaram a migração mais recente.
    try{
        $q=db()->prepare("SELECT r.*,pu.name payer_name,ru.name recipient_name,c.name company_name,o.order_number
            FROM receipts r
            JOIN orders o ON r.source_type='order' AND o.id=r.source_id
            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 upper(COALESCE(o.order_number,''))=?
            ORDER BY r.id DESC LIMIT 20");
        $q->execute([$code]);
        foreach($q->fetchAll() as $r)$pushReceipt($r);
    }catch(Throwable $ignored){}

    // 3) Compatibilidade total com comprovantes antigos. Calcula tanto o código
    // atual quanto o código legado diretamente dos dados, sem exigir receipt_code.
    try{
        $q=db()->query("SELECT r.*,pu.name payer_name,ru.name recipient_name,c.name company_name
            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
            ORDER BY r.id DESC LIMIT 5000");
        foreach($q->fetchAll() as $r){
            $current=transaction_receipt_code($r);
            $legacy=strtoupper(substr(hash('sha256',(string)$r['source_type'].'|'.(int)$r['source_id'].'|'.(int)$r['payer_user_id'].'|'.(int)$r['recipient_user_id'].'|'.(string)$r['created_at']),0,12));
            if($current===$code)$pushReceipt($r,'Pagamento',$current);
            elseif($legacy===$code)$pushReceipt($r,'Pagamento (código antigo)',$legacy);
        }
    }catch(Throwable $ignored){}

    // 4) Agendamentos de clínica: primeiro tenta a coluna persistida e depois
    // calcula o código em memória, permitindo localizar comprovantes de versões antigas.
    try{
        $q=db()->prepare("SELECT a.*,c.name company_name,pa.name patient_name,u.name platform_patient_name,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 u ON u.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 upper(COALESCE(a.receipt_code,''))=? LIMIT 20");
        $q->execute([$code]);
        foreach($q->fetchAll() as $a){
            $key='clinic:'.(int)$a['id'];if(isset($seen[$key]))continue;$seen[$key]=true;
            $results[]=['kind'=>'Agendamento de clínica','code'=>clinic_appointment_receipt_code($a),'title'=>(string)($a['specialty_name']?:'Consulta').' • '.(string)$a['company_name'],'party'=>(string)($a['platform_patient_name']?:$a['patient_name']?:'Paciente').' • '.(string)($a['professional_name']?:'Profissional a definir'),'date'=>(string)$a['appointment_date'].' '.substr((string)$a['appointment_time'],0,5),'amount'=>(float)$a['amount'],'url'=>'clinic_receipt.php?id='.(int)$a['id'].'&return=receipt_search'];
        }
    }catch(Throwable $ignored){}
    try{
        $q=db()->query("SELECT a.*,c.name company_name,pa.name patient_name,u.name platform_patient_name,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 u ON u.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 COALESCE(a.receipt_path,'')<>'' ORDER BY a.id DESC LIMIT 5000");
        foreach($q->fetchAll() as $a){
            if(clinic_appointment_receipt_code($a)!==$code)continue;
            $key='clinic:'.(int)$a['id'];if(isset($seen[$key]))continue;$seen[$key]=true;
            $results[]=['kind'=>'Agendamento de clínica','code'=>clinic_appointment_receipt_code($a),'title'=>(string)($a['specialty_name']?:'Consulta').' • '.(string)$a['company_name'],'party'=>(string)($a['platform_patient_name']?:$a['patient_name']?:'Paciente').' • '.(string)($a['professional_name']?:'Profissional a definir'),'date'=>(string)$a['appointment_date'].' '.substr((string)$a['appointment_time'],0,5),'amount'=>(float)$a['amount'],'url'=>'clinic_receipt.php?id='.(int)$a['id'].'&return=receipt_search'];
        }
    }catch(Throwable $ignored){}

    // 5) Cobranças: compatibilidade com coluna nova e com registros antigos.
    try{
        $q=db()->prepare("SELECT ch.*,u.name payer_name,iu.name issuer_name
            FROM charges ch
            LEFT JOIN users u ON u.id=ch.user_id
            LEFT JOIN users iu ON iu.id=ch.issuer_user_id
            WHERE upper(COALESCE(ch.receipt_code,''))=? LIMIT 20");
        $q->execute([$code]);
        foreach($q->fetchAll() as $ch){
            $key='charge:'.(int)$ch['id'];if(isset($seen[$key]))continue;$seen[$key]=true;
            $url=(string)($ch['receipt_path']??'');
            $results[]=['kind'=>'Cobrança','code'=>charge_receipt_code($ch),'title'=>(string)($ch['description']?:'Cobrança #'.$ch['id']),'party'=>(string)($ch['payer_name']?:'Cliente').' → '.(string)($ch['issuer_name']?:platform_name()),'date'=>(string)($ch['updated_at']?:$ch['created_at']),'amount'=>(float)$ch['amount'],'url'=>$url!==''?generated_receipt_url($url,'charge',(int)$ch['id']):''];
        }
    }catch(Throwable $ignored){}
    try{
        $q=db()->query("SELECT ch.*,u.name payer_name,iu.name issuer_name FROM charges ch LEFT JOIN users u ON u.id=ch.user_id LEFT JOIN users iu ON iu.id=ch.issuer_user_id WHERE COALESCE(ch.receipt_path,'')<>'' ORDER BY ch.id DESC LIMIT 5000");
        foreach($q->fetchAll() as $ch){
            if(charge_receipt_code($ch)!==$code)continue;
            $key='charge:'.(int)$ch['id'];if(isset($seen[$key]))continue;$seen[$key]=true;
            $url=(string)($ch['receipt_path']??'');
            $results[]=['kind'=>'Cobrança','code'=>charge_receipt_code($ch),'title'=>(string)($ch['description']?:'Cobrança #'.$ch['id']),'party'=>(string)($ch['payer_name']?:'Cliente').' → '.(string)($ch['issuer_name']?:platform_name()),'date'=>(string)($ch['updated_at']?:$ch['created_at']),'amount'=>(float)$ch['amount'],'url'=>$url!==''?generated_receipt_url($url,'charge',(int)$ch['id']):''];
        }
    }catch(Throwable $ignored){}
}
?>
<section class="page-intro"><div><span class="mini-label">🔎 ADMINISTRAÇÃO</span><h2>Buscar comprovante</h2><p>Digite o código do rodapé ou o código do pedido (LX...) para localizar o documento e conferir os dados.</p></div></section>
<section class="panel">
<form class="module-toolbar" method="get" action="dashboard.php">
<input type="hidden" name="page" value="receipt_search">
<div class="form-group" style="min-width:min(100%,420px)"><label>Código do comprovante ou pedido</label><input class="input" name="code" value="<?=e($code)?>" maxlength="30" autocomplete="off" placeholder="Ex.: 953CC8A52FBE ou LX26082122255030"></div>
<button class="btn btn-primary">🔎 Buscar</button>
</form>
<?php if($code!==''&&!$results):?><div class="empty-state" style="margin-top:18px"><strong>Comprovante não encontrado</strong>Confira o código do rodapé ou o número LX do pedido e tente novamente.</div><?php endif;?>
<?php if($results):?><div class="cards-list" style="margin-top:18px"><?php foreach($results as $r):?><article class="item-card"><div class="item-body"><div class="panel-header"><div><span class="mini-label"><?=e($r['kind'])?></span><h3><?=e($r['title'])?></h3></div><span class="status status-active"><?=e($r['code'])?></span></div><p><?=e($r['party'])?></p><div class="item-meta"><span><?=e(date('d/m/Y H:i',strtotime($r['date'])))?></span><?php if($r['amount']>0):?><strong><?=money($r['amount'])?></strong><?php endif;?></div><?php if($r['url']):?><div class="actions" style="margin-top:12px"><a class="btn btn-primary btn-sm" href="<?=e($r['url'])?>">Acessar Comprovante</a></div><?php endif;?></div></article><?php endforeach;?></div><?php endif;?>
</section>
