<?php
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? '';
$receiptCompany = trim((string)($settings['receipt_company_name'] ?? '')) ?: (string)($settings['site_name'] ?? 'CFC CONTROLE');
?>
<main class="container-fluid py-4">
    <div class="row g-4">
        <div class="col-lg-3"><?php require APP_PATH.'/Views/admin/_sidebar.php'; ?></div>
        <div class="col-lg-9">
            <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">Bancos, cobranças e comprovantes</h1>
                    <p class="text-muted mb-0">Ao confirmar um pagamento, o sistema cria e salva automaticamente um comprovante digital.</p>
                </div>
                <a class="btn btn-outline-primary rounded-pill" href="<?= e(url('admin/settings')) ?>"><i class="bi bi-receipt"></i> Configurar comprovante</a>
            </div>

            <div class="alert alert-info rounded-4 d-flex gap-3 align-items-start">
                <i class="bi bi-info-circle-fill fs-4"></i>
                <div><strong>Identidade do comprovante:</strong> <?= e($receiptCompany) ?>. A logo vem da Identidade Visual e o CNPJ/CPF é opcional.</div>
            </div>

            <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">Gerar comprovante avulso para aluno</h2><p class="text-muted mb-0">Use mesmo quando o pagamento não foi feito por uma cobrança do sistema. O comprovante usa a logo e o CNPJ configurados.</p></div></div>
                <form method="post" action="<?= e(url('admin/payment-center/receipt-manual')) ?>" class="row g-3">
                    <?= CSRF::input() ?>
                    <div class="col-md-4"><label class="form-label">Aluno</label><select name="student_id" class="form-select" required><option value="">Selecione</option><?php foreach(($receiptStudents??$students) as $p): ?><option value="<?= (int)$p['id'] ?>"><?= e($p['name']) ?><?= !empty($p['cpf'])?' - '.e(format_cpf($p['cpf'])):'' ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-2"><label class="form-label">Valor pago</label><input name="amount" class="form-control" required placeholder="0,00"></div>
                    <div class="col-md-2"><label class="form-label">Data pagamento</label><input type="date" name="paid_date" class="form-control" required value="<?= e(date('Y-m-d')) ?>"></div>
                    <div class="col-md-2"><label class="form-label">Referente a</label><input name="service_title" class="form-control" placeholder="Ex.: Aulas práticas"></div>
                    <div class="col-md-2"><label class="form-label">Forma</label><input name="payment_method" class="form-control" placeholder="PIX / dinheiro"></div>
                    <div class="col-12"><button class="btn btn-success rounded-pill px-4"><i class="bi bi-file-earmark-check"></i> Gerar comprovante</button></div>
                </form>
                <?php if(!empty($manualReceipts)): ?><hr><h3 class="h6 fw-bold">Comprovantes avulsos recentes</h3><div class="table-responsive"><table class="table table-sm align-middle"><thead><tr><th>Aluno</th><th>Data</th><th>Referência</th><th>Valor</th><th>Ações</th></tr></thead><tbody><?php foreach($manualReceipts as $r): ?><?php $receiptPath=url('receipt/view',['code'=>$r['receipt_code']]); $receiptUrl=$host!==''?$scheme.'://'.$host.$receiptPath:$receiptPath; $share='Olá '.$r['client_name'].'! Segue seu comprovante de '.format_money_br((float)$r['amount']).': '.$receiptUrl; $rw=whatsapp_url((string)($r['recipient_whatsapp']??''),$share); ?><tr><td><?= e($r['client_name']) ?></td><td><?= e(date('d/m/Y',strtotime($r['paid_at']))) ?></td><td><?= e($r['service_title']) ?></td><td><?= e(format_money_br($r['amount'])) ?></td><td><div class="d-flex gap-1"><a target="_blank" class="btn btn-sm btn-primary rounded-pill" href="<?= e($receiptPath) ?>"><i class="bi bi-receipt"></i> Abrir/PNG</a><?php if($rw): ?><a target="_blank" rel="noopener" class="btn btn-sm btn-success rounded-pill" href="<?= e($rw) ?>"><i class="bi bi-whatsapp"></i> WhatsApp</a><?php endif; ?></div></td></tr><?php endforeach; ?></tbody></table></div><?php endif; ?>
            </div></div>

            <div class="row g-4 mb-4">
                <div class="col-xl-5">
                    <div class="card border-0 shadow-soft rounded-4 h-100"><div class="card-body p-4">
                        <h2 class="h5 fw-bold mb-3">Cadastrar banco</h2>
                        <form method="post" action="<?= e(url('admin/payment-center/bank-save')) ?>" enctype="multipart/form-data" class="row g-3">
                            <?= CSRF::input() ?>
                            <div class="col-12"><label class="form-label">Nome</label><input name="name" class="form-control" required></div>
                            <div class="col-12"><label class="form-label">Link de acesso</label><input name="access_url" class="form-control" placeholder="https://..."></div>
                            <div class="col-12"><label class="form-label">Código PIX</label><textarea name="pix_code" rows="2" class="form-control"></textarea></div>
                            <div class="col-12"><label class="form-label">Imagem do banco</label><input type="file" name="bank_image" class="form-control" accept="image/*"></div>
                            <div class="col-12"><label class="form-label">Descrição</label><textarea name="description" rows="2" class="form-control"></textarea></div>
                            <div class="col-12"><button class="btn btn-primary rounded-pill w-100">Salvar banco</button></div>
                        </form>
                    </div></div>
                </div>
                <div class="col-xl-7">
                    <div class="card border-0 shadow-soft rounded-4 h-100"><div class="card-body p-4">
                        <h2 class="h5 fw-bold mb-3">Enviar cobrança</h2>
                        <form method="post" action="<?= e(url('admin/payment-center/charge-save')) ?>" class="row g-3">
                            <?= CSRF::input() ?>
                            <div class="col-md-6"><label class="form-label">Destinatário</label><select name="recipient_key" class="form-select" required><option value="">Selecione...</option><optgroup label="Alunos"><?php foreach($students as $p): ?><option value="student:<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?></optgroup><optgroup label="Em formação"><?php foreach($beginners as $p): ?><option value="beginner:<?= (int)$p['id'] ?>"><?= e($p['name']) ?></option><?php endforeach; ?></optgroup></select></div>
                            <div class="col-md-6"><label class="form-label">Banco</label><select name="bank_id" class="form-select" required><option value="">Selecione...</option><?php foreach($banks as $b): if(empty($b['is_active']))continue; ?><option value="<?= (int)$b['id'] ?>"><?= e($b['name']) ?></option><?php endforeach; ?></select></div>
                            <div class="col-md-6"><label class="form-label">Título</label><input name="title" class="form-control" required placeholder="Ex.: Mensalidade de julho"></div>
                            <div class="col-md-3"><label class="form-label">Valor</label><input name="amount" class="form-control" placeholder="0,00"></div>
                            <div class="col-md-3"><label class="form-label">Vencimento</label><input type="date" name="due_date" class="form-control"></div>
                            <div class="col-12"><label class="form-label">Observações</label><textarea name="notes" rows="2" class="form-control"></textarea></div>
                            <input type="hidden" name="status" value="pending"><input type="hidden" name="is_active" value="1">
                            <div class="col-12"><button class="btn btn-success rounded-pill w-100"><i class="bi bi-send"></i> Enviar cobrança</button></div>
                        </form>
                    </div></div>
                </div>
            </div>

            <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4">
                <h2 class="h5 fw-bold mb-3">Bancos cadastrados</h2>
                <div class="row g-3">
                    <?php foreach($banks as $b): ?><div class="col-md-6 col-xl-4"><div class="border rounded-4 p-3 h-100">
                        <?php if(!empty($b['image_path'])): ?><img src="<?= e(asset($b['image_path'])) ?>" class="bank-image mb-3" alt="Banco <?= e($b['name']) ?>"><?php endif; ?>
                        <h3 class="h6 fw-bold"><?= e($b['name']) ?></h3><p class="small text-muted"><?= e($b['description']??'') ?></p>
                        <div class="d-flex gap-2 flex-wrap">
                            <?php if(!empty($b['access_url'])): ?><a target="_blank" rel="noopener" class="btn btn-sm btn-primary rounded-pill" href="<?= e($b['access_url']) ?>">Acessar</a><?php endif; ?>
                            <form method="post" action="<?= e(url('admin/payment-center/bank-toggle')) ?>"><?= CSRF::input() ?><input type="hidden" name="bank_id" value="<?= (int)$b['id'] ?>"><button class="btn btn-sm btn-outline-primary rounded-pill"><?= !empty($b['is_active'])?'Desativar':'Ativar' ?></button></form>
                            <form method="post" action="<?= e(url('admin/payment-center/bank-delete')) ?>" onsubmit="return confirm('Apagar este banco?');"><?= CSRF::input() ?><input type="hidden" name="bank_id" value="<?= (int)$b['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill">Apagar</button></form>
                        </div>
                    </div></div><?php endforeach; ?>
                </div>
            </div></div>

            <div class="card border-0 shadow-soft rounded-4"><div class="card-body p-4">
                <h2 class="h5 fw-bold mb-3">Cobranças enviadas</h2>
                <div class="table-responsive"><table class="table align-middle">
                    <thead><tr><th>Destinatário</th><th>Banco</th><th>Cobrança</th><th>Valor</th><th>Status</th><th>Enviado pelo aluno</th><th>Comprovante oficial</th><th></th></tr></thead>
                    <tbody>
                    <?php foreach($charges as $c): ?>
                        <?php
                        $receiptPath = !empty($c['receipt_code']) ? url('receipt/view',['code'=>$c['receipt_code']]) : '';
                        $receiptUrl = $receiptPath !== '' && $host !== '' ? $scheme.'://'.$host.$receiptPath : $receiptPath;
                        $shareMessage = 'Olá '.$c['recipient_name'].'! Seu pagamento de '.format_money_br((float)$c['amount']).' foi confirmado. Comprovante: '.$receiptUrl;
                        $whats = $receiptUrl !== '' ? whatsapp_url((string)($c['recipient_whatsapp']??''), $shareMessage) : '';
                        $studentProofPath = trim((string)($c['proof_path'] ?? ''));
                        $studentProofUrl = $studentProofPath !== '' ? url('portal/payments/proof-file',['charge_id'=>(int)$c['id']]) : '';
                        $studentProofIsImage = str_starts_with((string)($c['proof_mime'] ?? ''), 'image/');
                        ?>
                        <tr>
                            <td><strong><?= e($c['recipient_name']) ?></strong><small class="d-block text-muted"><?= e(internal_actor_label($c['recipient_type'])) ?></small></td>
                            <td><?= e($c['bank_name']) ?></td>
                            <td><?= e($c['title']) ?><?php if(!empty($c['due_date'])): ?><small class="d-block text-muted">Vence <?= e(date('d/m/Y',strtotime($c['due_date']))) ?></small><?php endif; ?></td>
                            <td><?= e(format_money_br($c['amount'])) ?></td>
                            <td><form method="post" action="<?= e(url('admin/payment-center/charge-status')) ?>" class="d-flex gap-2 align-items-center"><?= CSRF::input() ?><input type="hidden" name="charge_id" value="<?= (int)$c['id'] ?>"><select name="status" class="form-select form-select-sm"><option value="pending" <?= $c['status']==='pending'?'selected':'' ?>>Pendente</option><option value="paid" <?= $c['status']==='paid'?'selected':'' ?>>Pago</option></select><button class="btn btn-sm btn-outline-primary">Salvar</button></form></td>
                            <td style="min-width:210px">
                                <?php if($studentProofUrl!==''): ?>
                                    <?php if($studentProofIsImage): ?><img class="payment-proof-thumb mb-2" src="<?= e($studentProofUrl) ?>" alt="Comprovante enviado por <?= e($c['recipient_name']) ?>"><?php else: ?><div class="mb-2"><i class="bi bi-file-earmark-pdf-fill text-danger fs-2"></i></div><?php endif; ?>
                                    <small class="d-block text-muted mb-2"><?= e($c['proof_name']??'Comprovante') ?><?php if(!empty($c['proof_submitted_at'])): ?><br><?= e(date('d/m/Y H:i',strtotime($c['proof_submitted_at']))) ?><?php endif; ?></small>
                                    <div class="d-flex flex-wrap gap-1">
                                        <a class="btn btn-sm btn-outline-primary rounded-pill" target="_blank" href="<?= e($studentProofUrl) ?>"><i class="bi bi-eye"></i> Abrir</a>
                                        <form method="post" action="<?= e(url('admin/payment-center/proof-delete')) ?>" onsubmit="return confirm('Apagar somente o comprovante enviado? A cobrança será mantida.');"><?= CSRF::input() ?><input type="hidden" name="charge_id" value="<?= (int)$c['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-trash"></i> Apagar</button></form>
                                    </div>
                                <?php else: ?><span class="text-muted small">Ainda não enviado</span><?php endif; ?>
                            </td>
                            <td>
                                <?php if($receiptPath!==''): ?>
                                    <div class="d-flex flex-wrap gap-1">
                                        <a class="btn btn-sm btn-primary rounded-pill" target="_blank" href="<?= e($receiptPath) ?>"><i class="bi bi-receipt"></i> Abrir</a>
                                        <?php if($whats!==''): ?><a class="btn btn-sm btn-success rounded-pill" target="_blank" rel="noopener" href="<?= e($whats) ?>"><i class="bi bi-whatsapp"></i> Enviar</a><?php endif; ?>
                                    </div>
                                <?php else: ?><span class="text-muted small">Disponível após marcar como pago</span><?php endif; ?>
                            </td>
                            <td class="text-end"><form method="post" action="<?= e(url('admin/payment-center/charge-delete')) ?>" onsubmit="return confirm('Apagar a cobrança e todos os arquivos relacionados?');"><?= CSRF::input() ?><input type="hidden" name="charge_id" value="<?= (int)$c['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill">Apagar cobrança</button></form></td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if(empty($charges)): ?><tr><td colspan="8" class="text-center text-muted py-4">Nenhuma cobrança enviada.</td></tr><?php endif; ?>
                    </tbody>
                </table></div>
            </div></div>
        </div>
    </div>
</main>
