<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="mb-4"><h1 class="h3 fw-bold text-cfc-dark mb-1">Formação e venda para instrutores</h1><p class="text-muted mb-0">Publique e-books, livros, manuais e videoaulas, envie cobranças, analise comprovantes e libere o acesso.</p></div>

            <div class="row g-4 mb-4">
                <div class="col-xl-6"><div class="card border-0 shadow-soft rounded-4 h-100"><div class="card-body p-4">
                    <h2 class="h5 fw-bold mb-3"><i class="bi bi-cloud-arrow-up"></i> Publicar conteúdo</h2>
                    <form method="post" action="<?= e(url('admin/beginner-training/content-save')) ?>" enctype="multipart/form-data" class="row g-3" id="trainingContentForm">
                        <?= CSRF::input() ?>
                        <div class="col-md-7"><label class="form-label">Título</label><input name="title" class="form-control" required></div>
                        <div class="col-md-5"><label class="form-label">Tipo</label><select name="content_type" id="trainingContentType" class="form-select"><option value="ebook">E-book</option><option value="manual">Livro / Manual</option><option value="video">Videoaula</option></select></div>
                        <div class="col-md-5"><label class="form-label">Valor</label><input name="price" class="form-control" inputmode="decimal" placeholder="0,00" value="0,00"></div>
                        <div class="col-md-7" id="trainingFileWrap"><label class="form-label">Arquivo</label><input type="file" name="content_file" class="form-control" accept=".pdf,.epub,.doc,.docx,image/*"></div>
                        <div class="col-12 d-none" id="trainingVideoWrap"><label class="form-label">Link da videoaula</label><input type="url" name="video_url" class="form-control" placeholder="https://..."></div>
                        <div class="col-12"><label class="form-label">Imagem de apresentação</label><input type="file" name="cover_image" class="form-control" accept="image/jpeg,image/png,image/webp"><small class="text-muted">Opcional. Será exibida na página inicial e na área do instrutor em aprendizado.</small></div>
                        <div class="col-12"><label class="form-label">Descrição</label><textarea name="description" class="form-control" rows="3" placeholder="Explique o que o instrutor aprenderá."></textarea></div>
                        <div class="col-12"><button class="btn btn-success rounded-pill px-4"><i class="bi bi-check2-circle"></i> Publicar conteúdo</button></div>
                    </form>
                </div></div></div>
                <div class="col-xl-6"><div class="card border-0 shadow-soft rounded-4 h-100"><div class="card-body p-4">
                    <h2 class="h5 fw-bold mb-3"><i class="bi bi-cash-coin"></i> Enviar cobrança ou atualizar solicitação</h2>
                    <form method="post" action="<?= e(url('admin/beginner-training/charge')) ?>" class="row g-3">
                        <?= CSRF::input() ?>
                        <div class="col-md-6"><label class="form-label">Instrutor em Aprendizado</label><select name="beginner_id" class="form-select" required><option value="">Selecione</option><?php foreach ($beginners as $b): ?><option value="<?= (int)$b['id'] ?>"><?= e($b['name']) ?> - <?= e($b['email']) ?></option><?php endforeach; ?></select></div>
                        <div class="col-md-6"><label class="form-label">Conteúdo</label><select name="content_id" class="form-select" required><option value="">Selecione</option><?php foreach ($contents as $c): ?><option value="<?= (int)$c['id'] ?>"><?= e($c['title']) ?> (<?= e(training_content_type_label($c['content_type'])) ?>)</option><?php endforeach; ?></select></div>
                        <div class="col-md-4"><label class="form-label">Ação inicial</label><select name="initial_status" class="form-select"><option value="awaiting_payment">Enviar cobrança</option><option value="granted">Liberar gratuitamente agora</option></select></div>
                        <div class="col-md-4"><label class="form-label">Valor</label><input name="amount" class="form-control" inputmode="decimal" placeholder="0,00"></div>
                        <div class="col-md-4"><label class="form-label">Link de pagamento</label><input type="url" name="payment_link" class="form-control" placeholder="https://..."></div>
                        <div class="col-12"><label class="form-label">Código PIX</label><textarea name="pix_code" class="form-control" rows="2"></textarea></div>
                        <div class="col-12"><label class="form-label">Mensagem para o cliente</label><textarea name="admin_message" class="form-control" rows="2" placeholder="Orientações de pagamento ou prazo."></textarea></div>
                        <div class="col-12"><button class="btn btn-primary rounded-pill px-4"><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">Conteúdos publicados</h2>
                <div class="table-responsive"><table class="table align-middle"><thead><tr><th>Imagem</th><th>Conteúdo</th><th>Tipo</th><th>Valor</th><th>Solicitações</th><th>Status</th><th class="text-end">Ações</th></tr></thead><tbody>
                    <?php foreach ($contents as $c): ?><tr><td style="min-width:150px"><?php if (!empty($c['cover_path'])): ?><img class="content-cover-thumb mb-2" src="<?= e(url('media/training-cover', ['id'=>(int)$c['id']])) ?>" alt="Imagem"><?php else: ?><div class="content-cover-placeholder mb-2"><i class="bi bi-mortarboard"></i></div><?php endif; ?><form method="post" action="<?= e(url('admin/beginner-training/content-cover')) ?>" enctype="multipart/form-data" class="d-flex flex-column gap-1"><?= CSRF::input() ?><input type="hidden" name="content_id" value="<?= (int)$c['id'] ?>"><input type="file" name="cover_image" class="form-control form-control-sm" accept="image/jpeg,image/png,image/webp" required><button class="btn btn-sm btn-outline-primary">Salvar imagem</button></form></td><td><strong><?= e($c['title']) ?></strong><small class="d-block text-muted"><?= e($c['original_name'] ?? $c['video_url'] ?? '') ?></small></td><td><?= e(training_content_type_label($c['content_type'])) ?></td><td><?= e(format_money_br($c['price'])) ?></td><td><span class="badge text-bg-info"><?= (int)$c['total_orders'] ?></span></td><td><?= !empty($c['is_active']) ? '<span class="badge text-bg-success">Publicado</span>' : '<span class="badge text-bg-secondary">Oculto</span>' ?></td><td class="text-end"><div class="d-flex gap-2 justify-content-end"><form method="post" action="<?= e(url('admin/beginner-training/content-toggle')) ?>"><?= CSRF::input() ?><input type="hidden" name="content_id" value="<?= (int)$c['id'] ?>"><button class="btn btn-sm btn-outline-primary rounded-pill"><?= !empty($c['is_active']) ? 'Ocultar' : 'Publicar' ?></button></form><form method="post" action="<?= e(url('admin/beginner-training/content-delete')) ?>" onsubmit="return confirm('Apagar este conteúdo e todas as solicitações relacionadas?');"><?= CSRF::input() ?><input type="hidden" name="content_id" value="<?= (int)$c['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill">Apagar</button></form></div></td></tr><?php endforeach; ?>
                    <?php if (!$contents): ?><tr><td colspan="7" class="text-center text-muted py-4">Nenhum conteúdo publicado.</td></tr><?php endif; ?>
                </tbody></table></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">Solicitações, cobranças e comprovantes</h2>
                <div class="table-responsive"><table class="table align-middle"><thead><tr><th>Cliente</th><th>Conteúdo</th><th>Cobrança</th><th>Comprovante</th><th>Status / Liberação</th></tr></thead><tbody>
                    <?php foreach ($orders as $o): ?><tr>
                        <td><strong><?= e($o['beginner_name']) ?></strong><small class="d-block text-muted"><?= e($o['beginner_email']) ?></small><a target="_blank" class="btn btn-sm btn-success rounded-pill mt-1" href="<?= e(whatsapp_url($o['beginner_whatsapp'], 'Olá ' . $o['beginner_name'] . ', sobre o conteúdo ' . $o['content_title'] . '.')) ?>"><i class="bi bi-whatsapp"></i></a></td>
                        <td><strong><?= e($o['content_title']) ?></strong><small class="d-block text-muted"><?= e(training_content_type_label($o['content_type'])) ?></small></td>
                        <td><?= e(format_money_br($o['amount'])) ?><small class="d-block text-muted"><?= e($o['admin_message'] ?? '') ?></small></td>
                        <td><?php if (!empty($o['proof_path'])): ?><a target="_blank" class="btn btn-sm btn-outline-primary rounded-pill" href="<?= e(url('admin/beginner-training/proof', ['id'=>(int)$o['id']])) ?>"><i class="bi bi-receipt"></i> Abrir comprovante</a><small class="d-block text-muted mt-1"><?= !empty($o['proof_submitted_at']) ? e(date('d/m/Y H:i', strtotime($o['proof_submitted_at']))) : '' ?></small><?php else: ?><span class="text-muted small">Não enviado</span><?php endif; ?></td>
                        <td style="min-width:310px"><span class="badge <?= e(training_order_status_badge($o['status'])) ?> mb-2"><?= e(training_order_status_label($o['status'])) ?></span><form method="post" action="<?= e(url('admin/beginner-training/order-status')) ?>" class="row g-2"><?= CSRF::input() ?><input type="hidden" name="order_id" value="<?= (int)$o['id'] ?>"><div class="col-12"><select name="status" class="form-select form-select-sm"><option value="awaiting_payment" <?= in_array($o['status'], ['pending','awaiting_payment','proof_sent'], true)?'selected':'' ?>>Aguardando pagamento</option><option value="approved" <?= $o['status']==='approved'?'selected':'' ?>>Pagamento confirmado e liberar</option><option value="granted" <?= $o['status']==='granted'?'selected':'' ?>>Liberar gratuitamente</option><option value="rejected" <?= $o['status']==='rejected'?'selected':'' ?>>Recusar comprovante</option></select></div><div class="col-8"><input name="admin_message" class="form-control form-control-sm" value="<?= e($o['admin_message'] ?? '') ?>" placeholder="Mensagem"></div><div class="col-4"><button class="btn btn-sm btn-success rounded-pill w-100">Salvar</button></div></form></td>
                    </tr><?php endforeach; ?>
                    <?php if (!$orders): ?><tr><td colspan="5" class="text-center text-muted py-4">Nenhuma solicitação ou cobrança.</td></tr><?php endif; ?>
                </tbody></table></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">Instrutores cadastrados</h2>
                <div class="table-responsive"><table class="table align-middle"><thead><tr><th>Nome</th><th>Contato</th><th>Cadastro</th><th>Status e observações</th></tr></thead><tbody>
                    <?php foreach ($beginners as $b): ?><tr><td><strong><?= e($b['name']) ?></strong><small class="d-block text-muted">CPF <?= e(format_cpf($b['cpf'])) ?></small></td><td><?= e($b['email']) ?><small class="d-block text-muted"><?= e(format_whatsapp($b['whatsapp'])) ?></small></td><td><?= e(date('d/m/Y H:i', strtotime($b['created_at']))) ?></td><td style="min-width:360px"><form method="post" action="<?= e(url('admin/beginner-training/instructor-status')) ?>" class="row g-2"><?= CSRF::input() ?><input type="hidden" name="beginner_id" value="<?= (int)$b['id'] ?>"><div class="col-4"><select name="status" class="form-select form-select-sm"><option value="active" <?= $b['status']==='active'?'selected':'' ?>>Ativo</option><option value="blocked" <?= $b['status']==='blocked'?'selected':'' ?>>Bloqueado</option></select></div><div class="col-6"><input name="admin_notes" class="form-control form-control-sm" value="<?= e($b['admin_notes'] ?? '') ?>" placeholder="Observação interna"></div><div class="col-2"><button class="btn btn-sm btn-outline-primary rounded-pill w-100"><i class="bi bi-save"></i></button></div></form><form method="post" action="<?= e(url('admin/beginner-training/instructor-delete')) ?>" class="mt-2" onsubmit="return confirm('Apagar definitivamente a conta deste instrutor em formação? Esta ação não poderá ser desfeita.');"><?= CSRF::input() ?><input type="hidden" name="beginner_id" value="<?= (int)$b['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-trash"></i> Apagar conta</button></form></td></tr><?php endforeach; ?>
                    <?php if (!$beginners): ?><tr><td colspan="4" class="text-center text-muted py-4">Nenhum instrutor em aprendizado cadastrado.</td></tr><?php endif; ?>
                </tbody></table></div>
            </div></div>
        </div>
    </div>
</main>
<script>
(function(){var type=document.getElementById('trainingContentType'), file=document.getElementById('trainingFileWrap'), video=document.getElementById('trainingVideoWrap'); function sync(){var isVideo=type.value==='video'; file.classList.toggle('d-none',isVideo); video.classList.toggle('d-none',!isVideo); file.querySelector('input').required=!isVideo; video.querySelector('input').required=isVideo;} type.addEventListener('change',sync); sync();})();
</script>
