<?php $base=array_filter(['token'=>$token]); ?>
<main class="container py-4 py-md-5">
    <div class="d-flex flex-column flex-md-row justify-content-between gap-3 align-items-md-center mb-4">
        <div>
            <h1 class="h3 fw-bold text-cfc-dark mb-1"><i class="bi bi-bank"></i> Bancos, cobranças e comprovantes</h1>
            <p class="text-muted mb-0">Consulte as cobranças do administrador, envie seu comprovante e acompanhe a confirmação do pagamento.</p>
        </div>
        <a class="btn btn-outline-primary rounded-pill" href="<?= e($actorType==='student'?url('dashboard'):($actorType==='professional'?url('professional/panel',$base):url('beginner/panel'))) ?>"><i class="bi bi-arrow-left"></i> Voltar</a>
    </div>

    <?php $manualPortalReceipts=array_values(array_filter($receipts??[],static fn(array $r):bool=>($r['receipt_source']??'')==='manual')); ?>
    <?php if($manualPortalReceipts): ?>
        <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4"><div class="d-flex align-items-center gap-3 mb-3"><span class="feature-icon"><i class="bi bi-receipt-cutoff"></i></span><div><h2 class="h5 fw-bold mb-1">Meus comprovantes emitidos pela autoescola</h2><p class="text-muted mb-0">Comprovantes registrados diretamente pelo administrador.</p></div></div><div class="row g-3"><?php foreach($manualPortalReceipts as $receipt): ?><div class="col-md-6"><div class="border rounded-4 p-3 h-100"><div class="d-flex justify-content-between gap-2"><div><strong><?= e($receipt['service_title']) ?></strong><small class="d-block text-muted"><?= e(date('d/m/Y',strtotime($receipt['paid_at']))) ?> · <?= e($receipt['payment_method']??'') ?></small></div><span class="badge text-bg-success align-self-start"><?= e(format_money_br($receipt['amount'])) ?></span></div><div class="d-grid gap-2 mt-3"><a class="btn btn-primary rounded-pill" href="<?= e(url('receipt/view',['code'=>$receipt['receipt_code']])) ?>"><i class="bi bi-receipt"></i> Abrir comprovante</a><a class="btn btn-outline-primary rounded-pill" href="<?= e(url('receipt/view',['code'=>$receipt['receipt_code']])) ?>"><i class="bi bi-image"></i> Ver e baixar PNG</a></div></div></div><?php endforeach; ?></div></div></div>
    <?php endif; ?>

    <div class="row g-4">
        <?php foreach($charges as $charge): ?>
            <?php
            $isPaid=($charge['status']??'pending')==='paid';
            $receiptCode=(string)($charge['receipt_code']??'');
            $proofPath=trim((string)($charge['proof_path']??''));
            $proofMime=trim((string)($charge['proof_mime']??''));
            $proofName=trim((string)($charge['proof_name']??'Comprovante')) ?: 'Comprovante';
            $proofUrl=url('portal/payments/proof-file',array_filter(['charge_id'=>(int)$charge['id'],'token'=>$token]));
            $isProofImage=str_starts_with($proofMime,'image/');
            ?>
            <div class="col-md-6 col-xl-4">
                <div class="card border-0 shadow-soft rounded-4 h-100 overflow-hidden payment-charge-card <?= $isPaid?'payment-charge-paid':'' ?>">
                    <?php if(!empty($charge['bank_image'])): ?><img src="<?= e(asset($charge['bank_image'])) ?>" class="bank-image" alt="Imagem do banco <?= e($charge['bank_name']) ?>"><?php endif; ?>
                    <div class="card-body p-4">
                        <div class="d-flex justify-content-between gap-2 align-items-start mb-2">
                            <h2 class="h5 fw-bold mb-0"><?= e($charge['title']) ?></h2>
                            <div class="text-end"><span class="badge text-bg-warning text-dark"><?= e(format_money_br($charge['amount'])) ?></span><span class="badge <?= $isPaid?'text-bg-success':'text-bg-secondary' ?> d-block mt-1"><?= $isPaid?'Pago':'Pendente' ?></span></div>
                        </div>
                        <strong class="d-block mb-2"><?= e($charge['bank_name']) ?></strong>
                        <?php if(!empty($charge['due_date'])): ?><small class="text-muted d-block mb-2">Vencimento: <?= e(date('d/m/Y',strtotime($charge['due_date']))) ?></small><?php endif; ?>
                        <?php if(!empty($charge['notes'])): ?><p class="text-muted"><?= e($charge['notes']) ?></p><?php endif; ?>

                        <?php if(!$isPaid): ?>
                            <div class="d-grid gap-2 mt-3">
                                <?php if(!empty($charge['access_url'])): ?><a class="btn btn-primary rounded-pill" target="_blank" rel="noopener" href="<?= e($charge['access_url']) ?>"><i class="bi bi-box-arrow-up-right"></i> Acessar banco</a><?php endif; ?>
                                <?php if(!empty($charge['pix_code'])): ?><button type="button" class="btn btn-success rounded-pill" data-copy="<?= e($charge['pix_code']) ?>"><i class="bi bi-copy"></i> Copiar PIX</button><?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <div class="payment-proof-box mt-3">
                            <div class="d-flex align-items-center justify-content-between gap-2 mb-2">
                                <strong><i class="bi bi-paperclip"></i> Seu comprovante</strong>
                                <?php if($proofPath!==''): ?><span class="badge text-bg-info">Enviado</span><?php endif; ?>
                            </div>

                            <?php if($proofPath!==''): ?>
                                <div class="payment-proof-file mb-3">
                                    <?php if($isProofImage): ?>
                                        <img class="payment-proof-thumb" src="<?= e($proofUrl) ?>" alt="Comprovante enviado: <?= e($proofName) ?>">
                                    <?php else: ?>
                                        <i class="bi bi-file-earmark-pdf-fill text-danger"></i>
                                    <?php endif; ?>
                                    <div class="min-w-0 flex-grow-1">
                                        <div class="payment-proof-file-name fw-semibold"><?= e($proofName) ?></div>
                                        <?php if(!empty($charge['proof_submitted_at'])): ?><small class="text-muted">Enviado em <?= e(date('d/m/Y H:i',strtotime($charge['proof_submitted_at']))) ?></small><?php endif; ?>
                                    </div>
                                </div>
                                <a class="btn btn-outline-primary rounded-pill w-100 mb-2" target="_blank" href="<?= e($proofUrl) ?>"><i class="bi bi-eye"></i> Abrir comprovante enviado</a>
                            <?php else: ?>
                                <p class="small text-muted mb-3">Envie uma imagem ou PDF referente a esta cobrança.</p>
                            <?php endif; ?>

                            <?php if(!$isPaid): ?>
                                <form method="post" action="<?= e(url('portal/payments/proof-upload')) ?>" enctype="multipart/form-data" class="d-grid gap-2">
                                    <?= CSRF::input() ?>
                                    <input type="hidden" name="charge_id" value="<?= (int)$charge['id'] ?>">
                                    <?php if($token!==''): ?><input type="hidden" name="token" value="<?= e($token) ?>"><?php endif; ?>
                                    <label class="btn btn-outline-success rounded-pill payment-proof-upload-label">
                                        <i class="bi bi-upload"></i> <?= $proofPath!==''?'Escolher outro arquivo':'Escolher comprovante' ?>
                                        <input type="file" name="payment_proof" accept="image/jpeg,image/png,image/webp,image/gif,application/pdf" required class="visually-hidden">
                                    </label>
                                    <button class="btn btn-success rounded-pill"><i class="bi bi-send-check"></i> <?= $proofPath!==''?'Substituir comprovante':'Enviar ao administrador' ?></button>
                                    <small class="text-muted text-center">Imagem ou PDF, até 10 MB. As imagens grandes são reduzidas automaticamente.</small>
                                </form>
                            <?php else: ?>
                                <div class="alert alert-success rounded-4 py-2 mb-0"><i class="bi bi-check-circle"></i> Pagamento confirmado pelo administrador.</div>
                            <?php endif; ?>
                        </div>

                        <?php if($isPaid && $receiptCode!==''): ?>
                            <div class="payment-receipt-mini mt-3">
                                <strong class="d-block mb-2"><i class="bi bi-patch-check-fill text-success"></i> Comprovante oficial</strong>
                                <img src="<?= e(url('receipt/image',['code'=>$receiptCode])) ?>" alt="Comprovante oficial de pagamento <?= e($receiptCode) ?>" loading="lazy">
                                <div class="d-grid gap-2 mt-3">
                                    <a class="btn btn-primary rounded-pill" href="<?= e(url('receipt/view',['code'=>$receiptCode])) ?>"><i class="bi bi-receipt"></i> Abrir comprovante oficial</a>
                                    <a class="btn btn-outline-primary rounded-pill" href="<?= e(url('receipt/view',['code'=>$receiptCode])) ?>"><i class="bi bi-download"></i> Ver e baixar PNG</a>
                                </div>
                            </div>
                        <?php elseif($isPaid): ?>
                            <div class="alert alert-success rounded-4 mt-3 mb-0"><i class="bi bi-check-circle"></i> Pagamento confirmado.</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
        <?php if(empty($charges)): ?><div class="col-12"><div class="alert alert-success rounded-4">Nenhuma cobrança ativa no momento.</div></div><?php endif; ?>
    </div>
</main>
<script>
document.querySelectorAll('[data-copy]').forEach(function(button){button.addEventListener('click',async function(){try{await navigator.clipboard.writeText(button.dataset.copy||'');button.innerHTML='<i class="bi bi-check2"></i> PIX copiado';}catch(e){alert('Não foi possível copiar automaticamente.');}});});
</script>
