<?php
require_once __DIR__ . '/../includes/header.php';

$id = intval($_GET['id'] ?? 0);
$r = ['nome'=>'','cpf'=>'','telefone'=>'','whatsapp'=>'','email'=>'','endereco'=>'','aluno_id'=>''];

if ($id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM responsaveis WHERE id = :id");
    $stmt->execute(['id' => $id]);
    $r = $stmt->fetch() ?: $r;
}

$alunos = $pdo->query("SELECT id, nome FROM alunos WHERE status='Ativo' ORDER BY nome")->fetchAll();
$titulo = $id > 0 ? 'Editar Responsavel' : 'Novo Responsavel';
?>

<div class="page-header">
    <div><h2><?= $titulo ?></h2><div class="subtitle">Preencha os dados do responsavel</div></div>
    <div><a href="responsaveis.php" class="btn btn-secondary">Voltar</a></div>
</div>

<form method="POST" action="responsavel_salvar.php">
<input type="hidden" name="id" value="<?= $id ?>">

<div class="card-premium" style="padding:25px;margin-bottom:20px;">
    <h3 style="color:var(--accent);margin-bottom:15px;border-bottom:1px solid var(--border);padding-bottom:10px;">Dados do Responsavel</h3>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:15px;">
        <div class="form-group"><label>Nome Completo *</label><input name="nome" value="<?= sanitize($r['nome']) ?>" required></div>
        <div class="form-group"><label>CPF</label><input name="cpf" value="<?= sanitize($r['cpf']) ?>"></div>
        <div class="form-group"><label>Telefone</label><input name="telefone" value="<?= sanitize($r['telefone']) ?>"></div>
        <div class="form-group"><label>WhatsApp</label><input name="whatsapp" value="<?= sanitize($r['whatsapp']) ?>"></div>
        <div class="form-group"><label>Email</label><input type="email" name="email" value="<?= sanitize($r['email']) ?>"></div>
        <div class="form-group"><label>Aluno Vinculado</label>
            <select name="aluno_id"><option value="">Selecione</option><?php foreach($alunos as $a): ?><option value="<?= $a['id'] ?>" <?= $r['aluno_id']==$a['id']?'selected':'' ?>><?= sanitize($a['nome']) ?></option><?php endforeach; ?></select></div>
        <div class="form-group" style="grid-column:span 2;"><label>Endereco</label><textarea name="endereco" rows="2"><?= sanitize($r['endereco']) ?></textarea></div>
    </div>
</div>

<div style="display:flex;gap:10px;justify-content:flex-end;margin-bottom:30px;">
    <a href="responsaveis.php" class="btn btn-secondary">Cancelar</a>
    <button type="submit" class="btn btn-novo">Salvar Responsavel</button>
</div>
</form>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
