<?php
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'] ?? 'seudominio.com';
?>
<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">
            <h1 class="h3 fw-bold text-cfc-dark mb-4">Profissionais / Instrutores</h1>
            <div class="alert alert-info rounded-4 shadow-soft border-0">
                Somente o administrador visualiza o WhatsApp e os dados de acesso dos instrutores. Agora cada instrutor também pode entrar com usuário e senha pelo botão <strong>Instrutor</strong> na tela inicial.
            </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">Adicionar Profissional</h2>
                <form method="post" action="<?= e(url('admin/professionals/save')) ?>" class="row g-3 js-mask-form">
                    <?= CSRF::input() ?>
                    <div class="col-md-3"><label class="form-label">Nome</label><input name="name" class="form-control" required></div>
                    <div class="col-md-2"><label class="form-label">Tipo</label><input name="type" class="form-control" value="Instrutor"></div>
                    <div class="col-md-2"><label class="form-label">WhatsApp</label><input name="whatsapp" class="form-control whatsapp-mask" inputmode="tel" placeholder="(00) 00000-0000"></div>
                    <div class="col-md-2"><label class="form-label">Usuário</label><input name="username" class="form-control" placeholder="ex: joao"></div>
                    <div class="col-md-2"><label class="form-label">Senha</label><input type="password" name="password" class="form-control" placeholder="mín. 6 caracteres"></div>
                    <div class="col-md-2"><label class="form-label">Máx. aulas/dia</label><input type="number" name="daily_lesson_limit" class="form-control" min="0" max="99" value="0"><small class="text-muted">0 = sem limite</small></div>
                    <div class="col-md-10"><label class="form-label">Bloco de notas do admin</label><textarea name="admin_notes" class="form-control" rows="2" placeholder="Informações internas sobre este instrutor. Somente o admin vê."></textarea></div>
                    <div class="col-md-10 d-flex flex-wrap gap-4 align-items-center">
                        <label class="form-check-label"><input type="checkbox" class="form-check-input me-1" name="can_manage_theory_groups" value="1"> Pode criar e editar turmas teóricas</label>
                        <label class="form-check-label"><input type="checkbox" class="form-check-input me-1" name="can_manage_theory_videos" value="1"> Pode adicionar vídeos às turmas</label>
                    </div>
                    <div class="col-md-2 d-flex align-items-end"><button class="btn btn-primary w-100">Adicionar</button></div>
                </form>
            </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-calendar-month"></i></span>
                        <div>
                            <h2 class="h5 fw-bold mb-1">Aulas do Mês</h2>
                            <p class="text-muted mb-0">Selecione o instrutor e o mês para ver todas as aulas administradas por ele.</p>
                        </div>
                    </div>
                    <form class="row g-3 mb-4" method="get">
                        <input type="hidden" name="r" value="admin/professionals">
                        <div class="col-md-6">
                            <label class="form-label">Instrutor</label>
                            <select name="history_professional_id" class="form-select">
                                <option value="">Selecione</option>
                                <?php foreach ($professionals as $pOpt): ?>
                                    <option value="<?= (int)$pOpt['id'] ?>" <?= ((int)($historyProfessionalId ?? 0) === (int)$pOpt['id']) ? 'selected' : '' ?>><?= e($pOpt['name']) ?> - <?= e($pOpt['type']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Mês</label>
                            <input type="month" name="history_month" class="form-control" value="<?= e($historyMonth ?? date('Y-m')) ?>">
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button class="btn btn-primary w-100 rounded-pill"><i class="bi bi-search"></i> Mostrar aulas</button>
                        </div>
                    </form>
                    <?php if (!empty($historyProfessionalId)): ?>
                        <?php if (empty($professionalMonthAppointments)): ?>
                            <div class="alert alert-warning rounded-4 mb-0">Nenhuma aula encontrada para esse instrutor no mês selecionado.</div>
                        <?php else: ?>
                            <?php
                                $monthlyLessonUnits = 0;
                                $monthlyDoneUnits = 0;
                                $monthlyFutureUnits = 0;
                                $monthlyNotDoneUnits = 0;
                                foreach ($professionalMonthAppointments as $countItem) {
                                    $units = max(1, (int)($countItem['lesson_units'] ?: Appointment::lessonUnitsFromRange($countItem['start_at'] ?? null, $countItem['end_at'] ?? null)));
                                    $monthlyLessonUnits += $units;
                                    $hasOccurrence = !empty($countItem['absence_notified_at']) || !empty($countItem['student_no_show_at']) || !empty($countItem['professional_absence_notified_at']);
                                    if (($countItem['status'] ?? '') === 'completed' || !empty($countItem['lesson_confirmed_at'])) {
                                        $monthlyDoneUnits += $units;
                                    } elseif (($countItem['status'] ?? '') === 'canceled' || (($countItem['start_at'] ?? '') <= date('Y-m-d H:i:s') && ($hasOccurrence || ($countItem['status'] ?? '') === 'booked'))) {
                                        $monthlyNotDoneUnits += $units;
                                    } elseif (($countItem['status'] ?? '') === 'booked' && ($countItem['start_at'] ?? '') > date('Y-m-d H:i:s')) {
                                        $monthlyFutureUnits += $units;
                                    }
                                }
                            ?>
                            <div class="row g-3 mb-3">
                                <div class="col-md-3"><div class="alert alert-success rounded-4 mb-0"><strong><?= (int)$monthlyDoneUnits ?></strong><br><small>Aulas Cocluidas</small></div></div>
                                <div class="col-md-3"><div class="alert alert-primary rounded-4 mb-0"><strong><?= (int)$monthlyFutureUnits ?></strong><br><small>Aulas futuras</small></div></div>
                                <div class="col-md-3"><div class="alert alert-danger rounded-4 mb-0"><strong><?= (int)$monthlyNotDoneUnits ?></strong><br><small>Não feitas</small></div></div>
                                <div class="col-md-3"><div class="alert alert-secondary rounded-4 mb-0"><strong><?= (int)$monthlyLessonUnits ?></strong><br><small>Total no mês<br>50 min = 1 aula</small></div></div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-sm align-middle mb-0">
                                    <thead><tr><th>Data</th><th>Aulas</th><th>Aluno</th><th>Contato</th><th>Cor</th><th>Status/Ocorrências</th></tr></thead>
                                    <tbody>
                                        <?php foreach ($professionalMonthAppointments as $a): ?>
                                            <?php
                                                $absenceNotified = !empty($a['absence_notified_at']);
                                                $studentNoShow = !empty($a['student_no_show_at']);
                                                $professionalAbsence = !empty($a['professional_absence_notified_at']);
                                                $rowClass = (($absenceNotified || $studentNoShow) ? 'table-danger' : ($professionalAbsence ? 'table-warning' : '')) . ' ' . lesson_color_row_class($a['lesson_color'] ?? 'blue');
                                            ?>
                                            <tr class="<?= e($rowClass) ?>">
                                                <td><strong><?= e(date('d/m/Y H:i', strtotime($a['start_at']))) ?></strong><small class="d-block text-muted"><?= e(weekday_pt_full($a['start_at'])) ?> até <?= e(date('H:i', strtotime($a['end_at']))) ?></small></td>
                                                <td><span class="badge text-bg-info"><?= max(1, (int)($a['lesson_units'] ?: Appointment::lessonUnitsFromRange($a['start_at'] ?? null, $a['end_at'] ?? null))) ?> aula(s)</span><small class="d-block text-muted">50 min = 1</small></td>
                                                <td><strong class="<?= ($absenceNotified || $studentNoShow) ? 'text-danger' : '' ?>"><?= e($a['student_name'] ?? 'Aluno removido') ?></strong><small class="d-block text-muted"><?= e($a['student_category'] ?? '') ?><?= !empty($a['student_cpf']) ? ' / CPF ' . e(format_cpf($a['student_cpf'])) : '' ?></small></td>
                                                <td><?= e(format_whatsapp($a['student_whatsapp'] ?? '')) ?></td>
                                                <td><span class="badge <?= e(lesson_color_badge_class($a['lesson_color'] ?? 'blue')) ?>"><?= e(lesson_color_label($a['lesson_color'] ?? 'blue')) ?></span></td>
                                                <td>
                                                    <span class="badge <?= ($a['status'] ?? '') === 'completed' ? 'text-bg-success' : (($a['status'] ?? '') === 'booked' ? 'text-bg-primary' : 'text-bg-secondary') ?>"><?= e(($a['status'] ?? '') === 'completed' ? 'concluída' : ($a['status'] ?? '')) ?></span>
                                                    <?php if ($absenceNotified): ?><span class="badge text-bg-danger ms-1">Aluno avisou ausência</span><?php endif; ?>
                                                    <?php if ($studentNoShow): ?><span class="badge text-bg-danger ms-1">Falta registrada</span><?php endif; ?>
                                                    <?php if ($professionalAbsence): ?><span class="badge text-bg-warning text-dark ms-1">Instrutor ausente</span><?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card border-0 shadow-soft rounded-4"><div class="card-body p-4"><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Dados</th><th>Acesso</th><th>Painel semanal</th><th>Editar Informações / Bloco de notas</th><th class="text-end">Ações</th></tr></thead><tbody>
                <?php foreach ($professionals as $p): ?>
                    <?php
                        $panelLink = $scheme . $host . url('professional/panel', ['token' => $p['panel_token'] ?? '']);
                        $loginLink = $scheme . $host . url('professional/login');
                        $phone = $p['whatsapp'] ?? '';
                        $sendPanelMsg = 'Olá ' . ($p['name'] ?? 'instrutor') . ', Segue seu painel semanal de aulas: ' . $panelLink . ' Você também pode entrar com usuário e senha em: ' . $loginLink;
                        $whatsLink = whatsapp_url($phone, $sendPanelMsg);
                    ?>
                <tr>
                    <td>
                        <div class="d-flex align-items-center gap-3 mb-2">
                            <?php if(!empty($p['profile_photo_path'])): ?><img src="<?= e(asset($p['profile_photo_path'])) ?>" class="profile-avatar" alt="Foto de <?= e($p['name']) ?>"><?php else: ?><span class="profile-avatar profile-placeholder"><i class="bi bi-person-fill"></i></span><?php endif; ?>
                            <div><strong><?= e($p['name']) ?></strong><small class="d-block text-muted"><?= e($p['type']) ?></small></div>
                        </div>
                        <?php if (!empty($phone)): ?>
                            <small class="d-block text-muted"><i class="bi bi-whatsapp"></i> <?= e(format_whatsapp($phone)) ?></small>
                        <?php else: ?>
                            <small class="d-block text-muted">WhatsApp não informado</small>
                        <?php endif; ?>
                        <?php if (!empty($p['admin_notes'])): ?>
                            <small class="d-block mt-2 text-warning"><i class="bi bi-journal-text"></i> Possui bloco de notas interno</small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span class="badge <?= $p['is_active']?'text-bg-success':'text-bg-secondary' ?>"><?= $p['is_active']?'ativo':'inativo' ?></span>
                        <span class="badge <?= !empty($p['access_enabled'])?'text-bg-primary':'text-bg-secondary' ?>"><?= !empty($p['access_enabled'])?'login liberado':'login bloqueado' ?></span>
                        <small class="d-block mt-2"><strong>Usuário:</strong> <?= e($p['username'] ?? '') ?: '<span class="text-muted">não definido</span>' ?></small>
                        <small class="d-block text-muted">Senha fica protegida e não aparece depois de salva.</small>
                        <small class="d-block mt-2"><strong>Limite diário:</strong> <?= (int)($p['daily_lesson_limit'] ?? 0) > 0 ? (int)$p['daily_lesson_limit'].' aula(s)' : 'sem limite' ?></small>
                    </td>
                    <td style="min-width:290px">
                        <div class="input-group input-group-sm mb-2">
                            <input class="form-control" readonly value="<?= e($panelLink) ?>" onclick="this.select();">
                            <a target="_blank" class="btn btn-outline-primary" href="<?= e($panelLink) ?>">Abrir</a>
                        </div>
                        <?php if ($whatsLink): ?>
                            <a class="btn btn-sm btn-success rounded-pill" target="_blank" href="<?= e($whatsLink) ?>"><i class="bi bi-whatsapp"></i> Enviar no WhatsApp dele</a>
                        <?php else: ?>
                            <span class="small text-muted">Cadastre o WhatsApp para enviar direto.</span>
                        <?php endif; ?>
                    </td>
                    <td style="min-width:420px">
                        <form method="post" action="<?= e(url('admin/professionals/save')) ?>" class="row g-2 js-mask-form">
                            <?= CSRF::input() ?>
                            <input type="hidden" name="professional_id" value="<?= (int)$p['id'] ?>">
                            <div class="col-md-6"><input name="name" class="form-control form-control-sm" value="<?= e($p['name']) ?>" required placeholder="Nome"></div>
                            <div class="col-md-6"><input name="type" class="form-control form-control-sm" value="<?= e($p['type']) ?>" placeholder="Tipo"></div>
                            <div class="col-md-4"><input name="whatsapp" class="form-control form-control-sm whatsapp-mask" value="<?= e(format_whatsapp($phone)) ?>" inputmode="tel" placeholder="WhatsApp"></div>
                            <div class="col-md-4"><input name="username" class="form-control form-control-sm" value="<?= e($p['username'] ?? '') ?>" placeholder="Usuário de login"></div>
                            <div class="col-md-4"><input type="password" name="password" class="form-control form-control-sm" placeholder="Nova Senha opcional"></div>
                            <div class="col-md-4"><label class="small">Máx. aulas/dia</label><input type="number" name="daily_lesson_limit" class="form-control form-control-sm" min="0" max="99" value="<?= (int)($p['daily_lesson_limit'] ?? 0) ?>"><small class="text-muted">0 = sem limite</small></div>
                            <div class="col-12"><textarea name="admin_notes" class="form-control form-control-sm" rows="3" placeholder="Bloco de notas interno do admin sobre este instrutor"><?= e($p['admin_notes'] ?? '') ?></textarea></div>
                            <div class="col-12 d-flex flex-wrap gap-2 align-items-center">
                                <label class="form-check-label small"><input type="checkbox" class="form-check-input me-1" name="access_enabled" value="1" <?= !empty($p['access_enabled']) ? 'checked' : '' ?>> Login liberado</label>
                                <label class="form-check-label small"><input type="checkbox" class="form-check-input me-1" name="can_manage_theory_groups" value="1" <?= !empty($p['can_manage_theory_groups']) ? 'checked' : '' ?>> Gerenciar turmas</label>
                                <label class="form-check-label small"><input type="checkbox" class="form-check-input me-1" name="can_manage_theory_videos" value="1" <?= !empty($p['can_manage_theory_videos']) ? 'checked' : '' ?>> Adicionar vídeos</label>
                                <button class="btn btn-sm btn-primary rounded-pill px-3"><i class="bi bi-save"></i> Salvar Edição</button>
                            </div>
                        </form>
                    </td>
                    <td class="text-end">
                        <div class="d-flex flex-wrap gap-2 justify-content-end">
                            <form method="post" action="<?= e(url('admin/professionals/toggle')) ?>"><?= CSRF::input() ?><input type="hidden" name="professional_id" value="<?= (int)$p['id'] ?>"><button class="btn btn-sm btn-outline-primary rounded-pill">Alterar status</button></form>
                            <form method="post" action="<?= e(url('admin/professionals/refresh-token')) ?>" onsubmit="return confirm('Gerar um novo link? O link antigo deixará de funcionar.');"><?= CSRF::input() ?><input type="hidden" name="professional_id" value="<?= (int)$p['id'] ?>"><button class="btn btn-sm btn-outline-warning rounded-pill">Renovar link</button></form>
                            <form method="post" action="<?= e(url('admin/professionals/delete')) ?>" onsubmit="return confirm('Apagar este profissional? Só sera permitido se ele não possuir aulas agendadas.');"><?= CSRF::input() ?><input type="hidden" name="professional_id" value="<?= (int)$p['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-pill">Apagar</button></form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody></table></div></div></div>
        </div>
    </div>
</main>

<script>
document.querySelectorAll('.whatsapp-mask').forEach(function(input) {
    input.addEventListener('input', function() {
        let v = input.value.replace(/\D/g, '').slice(0, 11);
        if (v.length > 10) {
            v = v.replace(/^(\d{2})(\d{5})(\d{0,4}).*/, '($1) $2-$3');
        } else if (v.length > 6) {
            v = v.replace(/^(\d{2})(\d{4})(\d{0,4}).*/, '($1) $2-$3');
        } else if (v.length > 2) {
            v = v.replace(/^(\d{2})(\d{0,5})/, '($1) $2');
        } else if (v.length > 0) {
            v = v.replace(/^(\d*)/, '($1');
        }
        input.value = v;
    });
});
</script>
