<?php
$editing = !empty($editGroup);
$selectedMembers = array_fill_keys(array_map('intval', $editMemberIds ?? []), true);
?>
<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">Grupos teóricos</h1>
                    <p class="text-muted mb-0">Forme turmas, escolha o instrutor, adicione alunos e use mensagens internas.</p>
                </div>
                <a class="btn btn-primary rounded-pill" href="<?= e(url('portal/messages')) ?>"><i class="bi bi-chat-dots"></i> Abrir mensagens</a>
            </div>

            <div class="card border-0 shadow-soft rounded-4 mb-4">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-center gap-3 mb-3">
                        <h2 class="h5 fw-bold mb-0"><?= $editing ? 'Editar turma' : 'Criar turma' ?></h2>
                        <?php if($editing): ?><a class="btn btn-sm btn-outline-secondary rounded-pill" href="<?= e(url('admin/theory-groups')) ?>">Cancelar edição</a><?php endif; ?>
                    </div>
                    <form method="post" action="<?= e(url('admin/theory-groups/save')) ?>" enctype="multipart/form-data" class="row g-3">
                        <?= CSRF::input() ?>
                        <?php if($editing): ?><input type="hidden" name="group_id" value="<?= (int)$editGroup['id'] ?>"><?php endif; ?>
                        <div class="col-md-5"><label class="form-label">Nome da turma</label><input name="name" class="form-control" value="<?= e($editGroup['name'] ?? '') ?>" required></div>
                        <div class="col-md-4"><label class="form-label">Instrutor</label><select name="instructor_id" class="form-select" required><option value="">Selecione...</option><?php foreach($professionals as $professional): ?><option value="<?= (int)$professional['id'] ?>" <?= (int)($editGroup['instructor_id'] ?? 0)===(int)$professional['id']?'selected':'' ?>><?= e($professional['name']) ?></option><?php endforeach; ?></select></div>
                        <div class="col-md-3"><label class="form-label">Imagem do grupo</label><input type="file" name="group_image" class="form-control" accept="image/*"><?php if($editing&&!empty($editGroup['image_path'])): ?><small class="text-muted">Envie outra imagem somente para substituir.</small><?php endif; ?></div>
                        <div class="col-12"><label class="form-label">Descrição</label><textarea name="description" rows="2" class="form-control"><?= e($editGroup['description'] ?? '') ?></textarea></div>
                        <div class="col-12"><label class="form-label">Alunos da turma</label><div class="student-check-grid"><?php foreach($students as $student): ?><label class="student-check"><input type="checkbox" name="student_ids[]" value="<?= (int)$student['id'] ?>" <?= isset($selectedMembers[(int)$student['id']])?'checked':'' ?>> <span><?= e(short_person_name($student['name'])) ?></span></label><?php endforeach; ?></div></div>
                        <div class="col-12"><button class="btn btn-primary rounded-pill px-4"><?= $editing ? 'Atualizar turma teórica' : 'Salvar turma teórica' ?></button></div>
                    </form>
                </div>
            </div>

            <div class="row g-4">
                <?php foreach($groups as $group): ?>
                    <?php $members=TheoryGroup::members((int)$group['id']); ?>
                    <div class="col-xl-6">
                        <div class="card border-0 shadow-soft rounded-4 h-100 overflow-hidden">
                            <div class="row g-0 h-100">
                                <div class="col-sm-4"><?php if(!empty($group['image_path'])): ?><img src="<?= e(asset($group['image_path'])) ?>" class="group-admin-image" alt="Grupo"><?php else: ?><div class="group-cover-placeholder h-100"><i class="bi bi-people-fill"></i></div><?php endif; ?></div>
                                <div class="col-sm-8"><div class="card-body p-4">
                                    <div class="d-flex justify-content-between gap-2"><div><h2 class="h5 fw-bold mb-1"><?= e($group['name']) ?></h2><small class="text-muted">Código <?= e($group['group_code']) ?> · <?= count($members) ?> aluno(s)</small></div><span class="badge <?= !empty($group['is_active'])?'text-bg-success':'text-bg-secondary' ?>"><?= !empty($group['is_active'])?'Ativa':'Inativa' ?></span></div>
                                    <p class="text-muted mt-2 mb-2"><?= e($group['description']??'') ?></p>
                                    <small class="d-block mb-3">Instrutor: <strong><?= e(short_person_name($group['instructor_name']??'')) ?></strong></small>
                                    <div class="d-flex flex-wrap gap-1 mb-3"><?php foreach($members as $member): ?><span class="badge text-bg-light border text-dark"><?= e(short_person_name($member['name'])) ?></span><?php endforeach; ?></div>
                                    <div class="d-flex flex-wrap gap-2">
                                        <a class="btn btn-sm btn-primary rounded-pill" href="<?= e(url('portal/messages/group',['id'=>(int)$group['id']])) ?>">Mensagens</a>
                                        <a class="btn btn-sm btn-outline-secondary rounded-pill" href="<?= e(url('admin/theory-groups',['edit'=>(int)$group['id']])) ?>">Editar</a>
                                        <form method="post" action="<?= e(url('admin/theory-groups/toggle')) ?>"><?= CSRF::input() ?><input type="hidden" name="group_id" value="<?= (int)$group['id'] ?>"><button class="btn btn-sm btn-outline-primary rounded-pill"><?= !empty($group['is_active'])?'Desativar':'Ativar' ?></button></form>
                                        <form method="post" action="<?= e(url('admin/theory-groups/delete')) ?>" onsubmit="return confirm('Apagar a turma e suas mensagens?');"><?= CSRF::input() ?><input type="hidden" name="group_id" value="<?= (int)$group['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill">Apagar</button></form>
                                    </div>
                                </div></div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
                <?php if(empty($groups)): ?><div class="col-12"><div class="alert alert-info rounded-4">Nenhuma turma criada.</div></div><?php endif; ?>
            </div>
        </div>
    </div>
</main>
