<main class="container py-4 py-md-5">
    <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">Pagamentos dos alunos</h1>
                    <p class="text-muted mb-0">Cadastre valores, PIX e links de pagamento individualmente para cada aluno.</p>
                </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"><i class="bi bi-cash-coin"></i> Novo pagamento</h2>
                    <form method="post" action="<?= e(url('admin/student-payments/save')) ?>" class="row g-3">
                        <?= CSRF::input() ?>
                        <div class="col-md-5">
                            <label class="form-label">Aluno</label>
                            <select name="student_id" class="form-select" required>
                                <option value="">Selecione...</option>
                                <?php foreach ($students as $s): ?>
                                    <option value="<?= (int)$s['id'] ?>"><?= e($s['name']) ?> - <?= e(format_cpf($s['cpf'] ?? '')) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4"><label class="form-label">Título</label><input name="title" class="form-control" required placeholder="Ex: Parcela da CNH"></div>
                        <div class="col-md-3"><label class="form-label">Valor</label><input name="amount" class="form-control" placeholder="Ex: 250,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-md-3"><label class="form-label">Status</label><select name="status" class="form-select"><option value="pending">Pendente</option><option value="paid">Pago</option><option value="canceled">Cancelado</option></select></div>
                        <div class="col-md-3 d-flex align-items-end"><label class="form-check mb-2"><input class="form-check-input" type="checkbox" name="is_active" value="1" checked> <span class="form-check-label">Mostrar para aluno</span></label></div>
                        <div class="col-md-3 d-flex align-items-end"><button class="btn btn-success rounded-pill px-4"><i class="bi bi-check2-circle"></i> Salvar</button></div>
                        <div class="col-md-6"><label class="form-label">Link de pagamento</label><input name="payment_link" class="form-control" placeholder="https://..."></div>
                        <div class="col-md-6"><label class="form-label">PIX copia e cola</label><textarea name="pix_code" class="form-control" rows="2"></textarea></div>
                        <div class="col-12"><label class="form-label">Observação interna</label><textarea name="notes" class="form-control" rows="2"></textarea></div>
                    </form>
                </div>
            </div>

            <div class="card border-0 shadow-soft rounded-4">
                <div class="card-body p-4">
                    <h2 class="h5 fw-bold mb-3">Lançamentos cadastrados</h2>
                    <div class="table-responsive">
                        <table class="table align-middle mb-0">
                            <thead><tr><th>Aluno</th><th>Pagamento</th><th>Valor</th><th>Vencimento</th><th>Status</th><th>Aluno vê?</th><th class="text-end">Ações</th></tr></thead>
                            <tbody>
                            <?php foreach ($payments as $p): ?>
                                <tr>
                                    <td><strong><?= e($p['student_name']) ?></strong><small class="d-block text-muted"><?= e(format_cpf($p['student_cpf'] ?? '')) ?></small></td>
                                    <td>
                                        <strong><?= e($p['title']) ?></strong>
                                        <?php if (!empty($p['payment_link'])): ?><a class="btn btn-sm btn-outline-primary rounded-pill d-block mt-2" target="_blank" href="<?= e($p['payment_link']) ?>"><i class="bi bi-box-arrow-up-right"></i> Abrir link</a><?php endif; ?>
                                        <?php if (!empty($p['pix_code'])): ?><small class="d-block text-muted mt-2">PIX configurado</small><?php endif; ?>
                                    </td>
                                    <td><?= e(format_money_br($p['amount'])) ?></td>
                                    <td><?= !empty($p['due_date']) ? e(date('d/m/Y', strtotime($p['due_date']))) : '-' ?></td>
                                    <td><span class="badge <?= $p['status']==='paid'?'text-bg-success':($p['status']==='canceled'?'text-bg-secondary':'text-bg-warning text-dark') ?>"><?= e(StudentPayment::statusLabel($p['status'])) ?></span></td>
                                    <td><?= !empty($p['is_active']) ? '<span class="badge text-bg-success">Sim</span>' : '<span class="badge text-bg-secondary">Não</span>' ?></td>
                                    <td class="text-end">
                                        <div class="d-inline-flex gap-2 flex-wrap justify-content-end">
                                            <button type="button" class="btn btn-sm btn-outline-primary rounded-pill" onclick='fillPaymentForm(<?= json_encode($p, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>)'><i class="bi bi-pencil"></i> Editar</button>
                                            <form method="post" action="<?= e(url('admin/student-payments/delete')) ?>" onsubmit="return confirm('Apagar este pagamento?');">
                                                <?= CSRF::input() ?>
                                                <input type="hidden" name="payment_id" value="<?= (int)$p['id'] ?>">
                                                <button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-trash"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (!$payments): ?><tr><td colspan="7" class="text-center text-muted py-4">Nenhum pagamento cadastrado.</td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <form id="edit-payment-form" method="post" action="<?= e(url('admin/student-payments/save')) ?>" class="d-none">
                <?= CSRF::input() ?>
                <input type="hidden" name="payment_id" id="edit_payment_id">
                <input type="hidden" name="student_id" id="edit_student_id">
                <input type="hidden" name="title" id="edit_title">
                <input type="hidden" name="amount" id="edit_amount">
                <input type="hidden" name="due_date" id="edit_due_date">
                <input type="hidden" name="payment_link" id="edit_payment_link">
                <input type="hidden" name="pix_code" id="edit_pix_code">
                <input type="hidden" name="status" id="edit_status">
                <input type="hidden" name="is_active" id="edit_is_active">
                <input type="hidden" name="notes" id="edit_notes">
            </form>
        </div>
    </div>
</main>

<script>
function fillPaymentForm(p) {
    const title = prompt('Título do pagamento:', p.title || '');
    if (title === null) return;
    const amount = prompt('Valor:', (Number(p.amount || 0)).toLocaleString('pt-BR', {minimumFractionDigits:2, maximumFractionDigits:2}));
    if (amount === null) return;
    const due = prompt('Vencimento (AAAA-MM-DD):', p.due_date || '');
    if (due === null) return;
    const link = prompt('Link de pagamento:', p.payment_link || '');
    if (link === null) return;
    const pix = prompt('PIX copia e cola:', p.pix_code || '');
    if (pix === null) return;
    const status = prompt('Status: pending, paid ou canceled', p.status || 'pending');
    if (status === null) return;
    document.getElementById('edit_payment_id').value = p.id;
    document.getElementById('edit_student_id').value = p.student_id;
    document.getElementById('edit_title').value = title;
    document.getElementById('edit_amount').value = amount;
    document.getElementById('edit_due_date').value = due;
    document.getElementById('edit_payment_link').value = link;
    document.getElementById('edit_pix_code').value = pix;
    document.getElementById('edit_status').value = status;
    document.getElementById('edit_is_active').value = p.is_active ? '1' : '';
    document.getElementById('edit_notes').value = p.notes || '';
    document.getElementById('edit-payment-form').submit();
}
</script>
