<?php
$allHolidayItems = $holidays ?? [];

$holidayMatchesForDate = static function (string $date, ?string $uf = '', ?string $city = '') use ($allHolidayItems): array {
    $uf = strtoupper(trim((string)$uf));
    $city = trim((string)$city);
    $matches = [];

    foreach ($allHolidayItems as $holiday) {
        if (empty($holiday['is_active'])) {
            continue;
        }
        $holidayDate = (string)($holiday['holiday_date'] ?? '');
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $holidayDate)) {
            continue;
        }

        $sameDate = $holidayDate === $date;
        $sameRecurringDay = !empty($holiday['repeat_yearly']) && substr($holidayDate, 5) === substr($date, 5);
        if (!$sameDate && !$sameRecurringDay) {
            continue;
        }

        if (!Holiday::appliesToPlace($holiday, $uf, $city)) {
            continue;
        }

        $copy = $holiday;
        $copy['original_holiday_date'] = $holidayDate;
        $copy['holiday_date'] = $date;
        $matches[] = $copy;
    }

    return $matches;
};

$selectedDateHolidays = !empty($filters['date'])
    ? Holiday::occurrencesForDateAdminAll($filters['date'])
    : [];
$appointmentsMonth = !empty($filters['date']) ? substr($filters['date'], 0, 7) : date('Y-m');
$monthHolidays = Holiday::occurrencesForMonthAdminAll($appointmentsMonth);
?>
<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 mb-4">
                <div>
                    <h1 class="h3 fw-bold text-cfc-dark mb-1">Agendamentos</h1>
                    <p class="text-muted mb-0">Gerencie as aulas criadas pelo aluno ou marcadas manualmente. Feriados e datas comemorativas aparecem destacadas nas datas de agendamento.</p>
                </div>
                <a class="btn btn-warning rounded-pill align-self-start" href="<?= e(url('admin/ratings')) ?>"><i class="bi bi-star-fill"></i> Ver pontuações</a>
            </div>


            <div class="card border-0 shadow-soft rounded-4 mb-4 holiday-admin-summary">
                <div class="card-body p-4">
                    <div class="d-flex align-items-start gap-3">
                        <span class="feature-icon bg-warning-subtle text-warning"><i class="bi bi-calendar-heart"></i></span>
                        <div class="flex-grow-1">
                            <h2 class="h6 fw-bold mb-1">Feriados / Datas comemorativas no agendamento</h2>
                            <p class="text-muted mb-2">Quando a data do agendamento tiver feriado ou data comemorativa cadastrada, o sistema mostra um aviso na lista e no histórico. Se precisar agendar manualmente mesmo assim, marque “Desbloquear feriado”.</p>
                            <?php if (!empty($filters['date']) && $selectedDateHolidays): ?>
                                <div class="alert alert-warning rounded-4 mb-3">
                                    <strong>Data selecionada <?= e(date('d/m/Y', strtotime($filters['date']))) ?> possui registro especial:</strong>
                                    <?php foreach ($selectedDateHolidays as $holiday): ?>
                                        <span class="badge text-bg-warning text-dark ms-1"><?= e($holiday['name']) ?> · <?= e(Holiday::typeLabel($holiday['type'])) ?><?= !empty($holiday['uf']) ? ' · ' . e($holiday['uf']) : '' ?><?= !empty($holiday['city']) ? ' · ' . e($holiday['city']) : '' ?></span>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            <?php if ($monthHolidays): ?>
                                <div class="d-flex flex-wrap gap-2">
                                    <?php foreach ($monthHolidays as $holiday): ?>
                                        <span class="badge rounded-pill text-bg-light border holiday-admin-pill">
                                            <i class="bi bi-calendar-event"></i>
                                            <?= e(date('d/m', strtotime($holiday['holiday_date']))) ?> -
                                            <?= e($holiday['name']) ?>
                                            <small class="text-muted">
                                                (<?= e(Holiday::typeLabel($holiday['type'])) ?><?= !empty($holiday['uf']) ? ' · ' . e($holiday['uf']) : '' ?><?= !empty($holiday['city']) ? ' · ' . e($holiday['city']) : '' ?>)
                                            </small>
                                        </span>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <span class="text-muted small">Nenhum feriado ou data comemorativa cadastrada para este mês.</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </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-x"></i></span><div><h2 class="h5 fw-bold mb-1">Folgas dos instrutores</h2><p class="text-muted mb-0">Marque uma folga única ou recorrente. Nos dias de folga o instrutor não aparece disponível e o servidor bloqueia novos agendamentos.</p></div></div>
                    <form method="post" action="<?= e(url('admin/appointments/day-off-save')) ?>" class="row g-3 mb-3">
                        <?= CSRF::input() ?>
                        <div class="col-md-4"><label class="form-label">Instrutor</label><select name="professional_id" class="form-select" id="professionalDayOffProfessional" required><option value="">Selecione</option><?php foreach($professionals as $p): ?><option value="<?= (int)$p['id'] ?>"><?= e($p['name']) ?> - <?= e($p['type']) ?></option><?php endforeach; ?></select></div>
                        <div class="col-md-3"><label class="form-label">Data inicial da folga</label><input type="date" name="off_date" class="form-control" required value="<?= e(date('Y-m-d')) ?>"></div>
                        <div class="col-md-2"><label class="form-label">Recorrência</label><select name="recurrence_days" class="form-select"><option value="0">Somente esta data</option><option value="8">A cada 8 dias</option><option value="15">A cada 15 dias</option></select></div>
                        <div class="col-md-2"><label class="form-label">Observação</label><input name="note" class="form-control" maxlength="255" placeholder="Ex.: folga"></div>
                        <div class="col-md-1 d-flex align-items-end"><button class="btn btn-warning w-100" title="Salvar folga"><i class="bi bi-check2"></i></button></div>
                    </form>
                    <?php if(!empty($professionalDayOffRules)): ?><div class="d-flex flex-wrap gap-2"><?php foreach($professionalDayOffRules as $rule): ?><div class="border rounded-pill px-3 py-2 d-flex align-items-center gap-2"><strong><?= e($rule['professional_name']) ?></strong><span><?= e(date('d/m/Y',strtotime($rule['off_date']))) ?><?= (int)$rule['recurrence_days']>0 ? ' · a cada '.(int)$rule['recurrence_days'].' dias' : '' ?></span><?php if(!empty($rule['note'])): ?><small class="text-muted"><?= e($rule['note']) ?></small><?php endif; ?><form method="post" action="<?= e(url('admin/appointments/day-off-delete')) ?>" onsubmit="return confirm('Remover esta regra de folga?');"><?= CSRF::input() ?><input type="hidden" name="day_off_id" value="<?= (int)$rule['id'] ?>"><button class="btn btn-sm btn-link text-danger p-0" title="Remover"><i class="bi bi-x-circle"></i></button></form></div><?php endforeach; ?></div><?php else: ?><span class="text-muted small">Nenhuma folga cadastrada.</span><?php endif; ?>
                </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-plus"></i></span>
                        <div>
                            <h2 class="h5 fw-bold mb-1">Agendamento manual pelo Administrador</h2>
                            <p class="text-muted mb-0">Marque uma aula para um aluno sem depender do calendário liberado. O sistema bloqueia conflito de horário automaticamente.</p>
                        </div>
                    </div>
                    <form method="post" action="<?= e(url('admin/appointments/manual')) ?>" class="row g-3" id="manualAppointmentForm" data-professional-options-url="<?= e(url('admin/appointments/professional-options')) ?>">
                        <?= CSRF::input() ?>
                        <div class="col-lg-3">
                            <label class="form-label">Aluno Ativo</label>
                            <select name="student_id" class="form-select" id="manualAppointmentStudent" required>
                                <option value="">Selecione o Aluno</option>
                                <?php foreach (($students ?? []) as $student): ?>
                                    <option value="<?= (int)$student['id'] ?>"><?= e($student['name']) ?><?= !empty($student['cpf']) ? ' - CPF ' . e(format_cpf($student['cpf'])) : '' ?><?= !empty($student['category']) ? ' / Cat. ' . e($student['category']) : '' ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12 d-none" id="manualBookingStatus" aria-live="polite"></div>
                        <div class="col-lg-2">
                            <label class="form-label">Profissional</label>
                            <select name="professional_id" class="form-select" id="manualAppointmentProfessional" required>
                                <option value="">Selecione</option>
                                <?php foreach ($professionals as $p): ?>
                                    <option value="<?= (int)$p['id'] ?>"><?= e($p['name']) ?> - <?= e($p['type']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-sm-4 col-lg-2">
                            <label class="form-label">Categoria da aula</label>
                            <select name="lesson_category" class="form-select" id="manualLessonCategory" required><option value="">Selecione</option><?php foreach (driving_category_options() as $catKey => $catLabel): ?><option value="<?= e($catKey) ?>"><?= e($catLabel) ?></option><?php endforeach; ?></select>
                        </div>
                        <div class="col-sm-4 col-lg-2">
                            <label class="form-label">Data</label>
                            <input type="date" name="date" class="form-control" id="manualAppointmentDate" value="<?= e($filters['date'] ?: date('Y-m-d')) ?>" required>
                            <small class="text-muted">Aviso se a data tiver feriado/data comemorativa aparecerá na lista abaixo.</small>
                        </div>
                        <div class="col-sm-6 col-lg-2 d-flex align-items-end">
                            <label class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" name="allow_holiday" value="1">
                                <span class="form-check-label">Desbloquear feriado</span>
                            </label>
                        </div>
                        <div class="col-sm-4 col-lg-1">
                            <label class="form-label">Hora</label>
                            <input type="time" name="time" class="form-control" value="06:00" required>
                        </div>
                        <div class="col-sm-4 col-lg-1">
                            <label class="form-label">Min</label>
                            <input type="number" name="duration" id="manualLessonDuration" class="form-control" value="100" min="50" max="240" step="10" required><small class="text-muted">Hora/Aula Padrão: 100 minutos</small>
                        </div>
                        <div class="col-sm-6 col-lg-2">
                            <label class="form-label">Status da aula</label>
                            <select name="lesson_color" class="form-select">
                                <option value="blue">Monitorada</option>
                                <option value="green">Sem Monitorar</option>
                                <option value="red">Conclusão</option>
                            </select>
                            <small class="text-muted">Use para diferenciar monitorada/normal.</small>
                        </div>
                        <div class="col-lg-3">
                            <label class="form-label">Tipo da aula</label>
                            <select name="lesson_process" class="form-select" required><option value="">Selecione</option><?php foreach(license_process_options() as $processKey=>$processLabel): ?><option value="<?= e($processKey) ?>"><?= e($processLabel) ?></option><?php endforeach; ?></select>
                        </div>
                        <div class="col-lg-4">
                            <label class="form-label">Aula que será ministrada</label>
                            <input name="lesson_subject" class="form-control" maxlength="255" required placeholder="Ex: saída, troca de marcha, baliza e controle de embreagem">
                        </div>
                        <div class="col-12"><details class="border rounded-4 p-3 bg-light"><summary class="fw-semibold text-danger"><i class="bi bi-unlock-fill"></i> Precisa ultrapassar o limite diário?</summary><label class="form-check mt-3 mb-0"><input class="form-check-input" type="checkbox" name="allow_daily_limit_override" value="1"><span class="form-check-label">Permitir mais aulas no mesmo dia para este aluno (exceção autorizada pelo administrador)</span></label><small class="text-muted d-block mt-2">Regra normal: até 3 aulas da mesma categoria; com A e B no mesmo dia, máximo de 2 A + 2 B.</small></details></div>
                        <div class="col-lg-1 d-flex align-items-end">
                            <button class="btn btn-success w-100" id="manualAppointmentSubmit" title="Criar Agendamento"><i class="bi bi-check2-circle"></i></button>
                        </div>
                    </form>
                    <?php if (empty($students)): ?>
                        <div class="alert alert-warning rounded-4 mt-3 mb-0">Nenhum aluno com aulas contratadas disponíveis para novo agendamento. Alunos com toda a carga concluída ou já agendada ficam ocultos deste seletor.</div>
                    <?php endif; ?>
                </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-box-seam"></i></span><div><h2 class="h5 fw-bold mb-1">Contrato rápido de aulas</h2><p class="text-muted mb-0">Defina ou ajuste a quantidade contratada diretamente nesta área de agendamento, sem abrir o cadastro do aluno.</p></div></div>
                    <form method="post" action="<?= e(url('admin/appointments/package')) ?>" class="row g-3 align-items-end">
                        <?= 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(($allStudents??[]) as $st): ?><?php if(($st['student_status']??'')==='active'): ?><option value="<?= (int)$st['id'] ?>"><?= e($st['name']) ?> · <?= e($st['category']??'-') ?></option><?php endif; ?><?php endforeach; ?></select></div>
                        <div class="col-md-2"><label class="form-label">Categoria</label><select name="category" id="quickPackageCategory" class="form-select" required><option value="A">A - Moto</option><option value="B">B - Carro</option><option value="AB">AB - Moto + carro</option><option value="C">C</option><option value="D">D</option><option value="E">E</option></select></div>
                        <div class="col-md-2"><label class="form-label">Qtd. moto</label><input type="number" name="lessons_a" id="quickPackageA" class="form-control" min="0" value="2"></div>
                        <div class="col-md-2"><label class="form-label">Qtd. carro</label><input type="number" name="lessons_b" id="quickPackageB" class="form-control" min="0" value="2"></div>
                        <div class="col-md-2"><label class="form-label">Qtd. C/D/E</label><input type="number" name="lessons_other" id="quickPackageOther" class="form-control" min="0" value="2"></div>
                        <div class="col-md-2"><button class="btn btn-success rounded-pill w-100"><i class="bi bi-save"></i> Salvar</button></div>
                    </form>
                    <small class="text-muted d-block mt-2">A, B e AB exigem mínimo de 2 aulas por categoria. C, D e E também usam mínimo de 2 nesta solicitação.</small>
                </div>
            </div>

            <div class="card border-0 shadow-soft rounded-4 mb-4">
                <div class="card-body p-4">
                    <div class="d-flex flex-column flex-md-row justify-content-between gap-3 mb-3"><div><h2 class="h5 fw-bold mb-1"><i class="bi bi-grid-3x3-gap"></i> Agenda semanal por instrutor</h2><p class="text-muted mb-0">Visualização em cards de segunda a sábado. Selecione o instrutor na coluna correspondente para organizar a agenda específica.</p></div><form method="get" class="d-flex gap-2"><input type="hidden" name="r" value="admin/appointments"><input type="date" name="week" class="form-control" value="<?= e($weekStart??date('Y-m-d')) ?>"><button class="btn btn-primary rounded-pill">Semana</button></form></div>
                    <?php
                    $boardByProfessional=[]; foreach(($weekAppointments??[]) as $wa){$boardByProfessional[(int)$wa['professional_id']][]=$wa;}
                    $weekDays=[]; $wd=DateTime::createFromFormat('Y-m-d',$weekStart??date('Y-m-d')); for($i=0;$i<6;$i++){$d=clone $wd;$d->modify('+'.$i.' day');$weekDays[]=$d;}
                    ?>
                    <div class="row g-3">
                    <?php foreach(($professionals??[]) as $bp): ?>
                        <div class="col-xl-4 col-md-6"><div class="border rounded-4 h-100 overflow-hidden"><div class="p-3 bg-primary-subtle"><strong><?= e($bp['name']) ?></strong><small class="d-block text-muted"><?= e($bp['type']??'Instrutor') ?></small></div><div class="p-2">
                        <?php foreach($weekDays as $day): $dateKey=$day->format('Y-m-d'); $off=ProfessionalDayOff::isOff((int)$bp['id'],$dateKey); $dayItems=array_values(array_filter($boardByProfessional[(int)$bp['id']]??[],fn($x)=>substr($x['start_at'],0,10)===$dateKey)); $holidayItems=Holiday::occurrencesForDateAdminAll($dateKey); $holiday=$holidayItems[0]??null; ?>
                            <div class="border rounded-3 p-2 mb-2 <?= $off||$holiday?'bg-warning-subtle':'' ?>"><div class="d-flex justify-content-between"><strong><?= e(weekday_pt_full($dateKey)) ?></strong><span><?= e($day->format('d/m')) ?></span></div>
                            <?php if($holiday): ?><span class="badge text-bg-warning text-dark mt-1"><i class="bi bi-calendar-heart"></i> <?= e($holiday['name']) ?></span><?php endif; ?><?php if($off): ?><span class="badge text-bg-secondary mt-1"><i class="bi bi-person-x"></i> Folga<?= !empty($off['note'])?' · '.e($off['note']):'' ?></span><?php endif; ?>
                            <?php if($dayItems): foreach($dayItems as $it): ?><div class="mt-2 p-2 rounded-3 border bg-white"><div class="d-flex justify-content-between"><strong><?= e(date('H:i',strtotime($it['start_at']))) ?> - <?= e(date('H:i',strtotime($it['end_at']))) ?></strong><span class="badge <?= ($it['status']??'')==='completed'?'text-bg-success':'text-bg-primary' ?>"><?= ($it['status']??'')==='completed'?'Concluída':'Agendada' ?></span></div><div class="small mt-1"><strong><?= e($it['student_name']) ?></strong> · Cat. <?= e($it['lesson_category']??$it['student_category']??'-') ?></div></div><?php endforeach; else: ?><small class="text-muted d-block mt-2">Sem aula agendada.</small><?php endif; ?></div>
                        <?php endforeach; ?></div></div></div>
                    <?php endforeach; ?>
                    </div>
                </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-clock-history"></i></span>
                        <div>
                            <h2 class="h5 fw-bold mb-1">Histórico completo por aluno</h2>
                            <p class="text-muted mb-0">Selecione um aluno para ver todos os agendamentos passados e futuros, inclusive cancelados/desbloqueados.</p>
                        </div>
                    </div>
                    <form class="row g-3 mb-4" method="get">
                        <input type="hidden" name="r" value="admin/appointments">
                        <div class="col-md-9">
                            <label class="form-label">Aluno</label>
                            <select name="history_student_id" class="form-select">
                                <option value="">Selecione o aluno</option>
                                <?php foreach (($allStudents ?? $students ?? []) as $student): ?>
                                    <option value="<?= (int)$student['id'] ?>" <?= ((int)($historyStudentId ?? 0) === (int)$student['id']) ? 'selected' : '' ?>><?= e($student['name']) ?><?= !empty($student['cpf']) ? ' - CPF ' . e(format_cpf($student['cpf'])) : '' ?><?= !empty($student['student_status']) ? ' / ' . e($student['student_status']) : '' ?></option>
                                <?php endforeach; ?>
                            </select>
                        </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 histórico</button>
                        </div>
                    </form>
                    <?php if (!empty($historyStudentId)): ?>
                        <?php if (empty($studentHistory)): ?>
                            <div class="alert alert-warning rounded-4 mb-0">Nenhum agendamento encontrado para este aluno.</div>
                        <?php else: ?>
                            <?php
                                $historyStudentName = 'Aluno';
                                foreach (($allStudents ?? []) as $studentItem) if ((int)$studentItem['id'] === (int)$historyStudentId) { $historyStudentName = (string)$studentItem['name']; break; }
                                $scheduleExportItems = [];
                                foreach ($studentHistory as $item) {
                                    if (($item['status'] ?? '') === 'canceled') continue;
                                    $scheduleExportItems[] = [
                                        'category'=>(string)($item['lesson_category']??'-'), 'date'=>date('d/m/Y',strtotime($item['start_at'])),
                                        'weekday'=>weekday_pt_full($item['start_at']), 'time'=>date('H:i',strtotime($item['start_at'])).' - '.date('H:i',strtotime($item['end_at'])),
                                        'professional'=>(string)($item['professional_name']??''), 'subject'=>(string)($item['lesson_subject']??''),
                                        'status'=>(string)($item['status']??'')
                                    ];
                                }
                            ?>
                            <div class="d-flex justify-content-end gap-2 mb-3"><form method="post" action="<?= e(url('admin/appointments/history-delete-all')) ?>" onsubmit="return confirm('Apagar todas as aulas concluídas/canceladas deste aluno? As aulas futuras não serão afetadas.');"><?= CSRF::input() ?><input type="hidden" name="student_id" value="<?= (int)$historyStudentId ?>"><button class="btn btn-outline-danger rounded-pill"><i class="bi bi-trash3"></i> Apagar histórico encerrado</button></form><button type="button" class="btn btn-success rounded-pill" id="downloadSchedulePng"><i class="bi bi-image"></i> Gerar agenda em PNG</button></div>
                            <script type="application/json" id="scheduleExportJson"><?= json_encode(['student'=>$historyStudentName,'school'=>(string)($settings['receipt_company_name']??$settings['site_name']??'Autoescola'),'logo'=>(!empty($settings['logo_path'])?asset($settings['logo_path']):''),'items'=>$scheduleExportItems], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT) ?></script>
                            <div class="table-responsive">
                                <table class="table table-sm align-middle mb-0">
                                    <thead><tr><th>Data</th><th>Profissional</th><th>Aula</th><th>Status</th><th>Ocorrências</th></tr></thead>
                                    <tbody>
                                        <?php foreach ($studentHistory as $h): ?>
                                            <?php
                                                $absenceNotifiedH = !empty($h['absence_notified_at']);
                                                $studentNoShowH = !empty($h['student_no_show_at']);
                                                $professionalAbsenceH = !empty($h['professional_absence_notified_at']);
                                                $historyDateHolidays = $holidayMatchesForDate(substr($h['start_at'], 0, 10), $h['student_uf'] ?? '', $h['student_city'] ?? '');
                                            ?>
                                            <tr class="<?= e((!empty($historyDateHolidays) ? 'table-warning ' : '') . lesson_color_row_class($h['lesson_color'] ?? 'blue')) ?>">
                                                <td>
                                                    <strong><?= e(date('d/m/Y H:i', strtotime($h['start_at']))) ?></strong>
                                                    <small class="d-block text-muted"><?= e(weekday_pt_full($h['start_at'])) ?> até <?= e(date('H:i', strtotime($h['end_at']))) ?></small>
                                                    <?php foreach ($historyDateHolidays as $holiday): ?>
                                                        <span class="badge text-bg-warning text-dark mt-1"><i class="bi bi-calendar-heart"></i> <?= e($holiday['name']) ?></span>
                                                    <?php endforeach; ?>
                                                </td>
                                                <td><?= e($h['professional_name'] ?? '') ?><small class="d-block text-muted"><?= e($h['professional_type'] ?? '') ?></small></td>
                                                <td><span class="badge text-bg-primary">Cat. <?= e($h['lesson_category'] ?? '-') ?></span><strong class="d-block mt-1"><?= e($h['lesson_subject'] ?? 'Conteúdo não informado') ?></strong><?php if(!empty($h['lesson_process'])): ?><small class="d-block text-info"><?= e(license_process_options()[$h['lesson_process']]??$h['lesson_process']) ?></small><?php endif; ?><small class="d-block text-muted"><?= (int)($h['lesson_units'] ?: Appointment::lessonUnitsFromRange($h['start_at'], $h['end_at'])) ?> aula(s) · <?= e(lesson_color_label($h['lesson_color'] ?? 'blue')) ?></small><?php if (!empty($h['lesson_confirmed_at'])): ?><span class="badge text-bg-success mt-1">Confirmada <?= e(date('d/m/Y H:i', strtotime($h['lesson_confirmed_at']))) ?></span><?php endif; ?></td>
                                                <td><span class="badge <?= ($h['status'] ?? '') === 'completed' ? 'text-bg-success' : (($h['status'] ?? '') === 'booked' ? 'text-bg-primary' : 'text-bg-secondary') ?>"><?= e(($h['status'] ?? '') === 'completed' ? 'concluída' : ($h['status'] ?? '')) ?></span></td>
                                                <td>
                                                    <div class="d-flex flex-column gap-2">
                                                    <?php if (!$absenceNotifiedH && !$studentNoShowH && !$professionalAbsenceH): ?>
                                                        <span class="text-muted small">Sem ocorrências</span>
                                                    <?php else: ?>
                                                        <?php if ($absenceNotifiedH): ?><span class="badge text-bg-danger mb-1">Aluno avisou ausência</span><br><?php endif; ?>
                                                        <?php if ($studentNoShowH): ?><span class="badge text-bg-danger mb-1">Falta registrada</span><br><?php endif; ?>
                                                        <?php if ($professionalAbsenceH): ?><span class="badge text-bg-warning text-dark mb-1">Instrutor ausente</span><?php endif; ?>
                                                    <?php endif; ?>
                                                    <?php if (in_array(($h['status'] ?? ''), ['completed','canceled'], true)): ?><form method="post" action="<?= e(url('admin/appointments/history-delete')) ?>" onsubmit="return confirm('Apagar este registro do histórico?');"><?= CSRF::input() ?><input type="hidden" name="appointment_id" value="<?= (int)$h['id'] ?>"><input type="hidden" name="student_id" value="<?= (int)$historyStudentId ?>"><button class="btn btn-sm btn-outline-danger rounded-pill align-self-start"><i class="bi bi-trash3"></i> Apagar registro</button></form><?php endif; ?>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card border-0 shadow-soft rounded-4 mb-4"><div class="card-body p-4">
                <form class="row g-3">
                    <input type="hidden" name="r" value="admin/appointments">
                    <div class="col-md-3"><label class="form-label">Data</label><input type="date" class="form-control" name="date" value="<?= e($filters['date']) ?>"></div>
                    <div class="col-md-4"><label class="form-label">Profissional</label><select name="professional_id" class="form-select"><option value="">Todos</option><?php foreach ($professionals as $p): ?><option value="<?= (int)$p['id'] ?>" <?= ((string)$filters['professional_id']===(string)$p['id'])?'selected':'' ?>><?= e($p['name']) ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-4"><label class="form-label">Aluno / CPF / e-mail</label><input class="form-control" name="student" value="<?= e($filters['student']) ?>"></div>
                    <div class="col-md-1 d-flex align-items-end"><button class="btn btn-primary w-100"><i class="bi bi-search"></i></button></div>
                </form>
            </div></div>
            <div class="card border-0 shadow-soft rounded-4"><div class="card-body p-4">
                <?php $appointmentGroupCounts=[]; foreach($appointments as $countA){ $key=(string)($countA['professional_name']??'Sem instrutor'); $appointmentGroupCounts[$key]=($appointmentGroupCounts[$key]??0)+max(1,(int)($countA['lesson_units']?:Appointment::lessonUnitsFromRange($countA['start_at'],$countA['end_at']))); } $currentProfessionalGroup=null; $professionalSequence=0; ?>
                <div class="table-responsive"><table class="table align-middle"><thead><tr><th>Data</th><th>Aluno</th><th>Profissional</th><th>Aula</th><th>Ocorrencias</th><th>Status</th><th class="text-end">Ações</th></tr></thead><tbody>
                <?php foreach ($appointments as $a): ?>
                    <?php
                        $groupName=(string)($a['professional_name']??'Sem instrutor');
                        if($currentProfessionalGroup!==$groupName){ $currentProfessionalGroup=$groupName; $professionalSequence=0; echo '<tr class="table-light"><td colspan="7"><strong><i class="bi bi-person-badge"></i> '.e($groupName).'</strong> <span class="badge text-bg-primary ms-2">'.(int)($appointmentGroupCounts[$groupName]??0).' aula(s) no resultado</span></td></tr>'; }
                        $professionalSequence++;
                        $absenceNotified = !empty($a['absence_notified_at']);
                        $studentNoShow = !empty($a['student_no_show_at']);
                        $professionalAbsence = !empty($a['professional_absence_notified_at']);
                        $dateHolidays = $holidayMatchesForDate(substr($a['start_at'], 0, 10), $a['student_uf'] ?? '', $a['student_city'] ?? '');
                        $rowClass = (($absenceNotified || $studentNoShow) ? 'table-danger' : ($professionalAbsence ? 'table-warning' : (!empty($dateHolidays) ? 'table-warning' : ''))) . ' ' . lesson_color_row_class($a['lesson_color'] ?? 'blue');
                    ?>
                    <tr class="<?= e($rowClass) ?>">
                        <td>
                            <?= e(date('d/m/Y H:i', strtotime($a['start_at']))) ?>
                            <small class="d-block text-muted"><?= e(weekday_pt_full($a['start_at'])) ?></small>
                            <?php foreach ($dateHolidays as $holiday): ?>
                                <span class="badge text-bg-warning text-dark mt-1"><i class="bi bi-calendar-heart"></i> <?= e($holiday['name']) ?></span>
                            <?php endforeach; ?>
                        </td>
                        <td>
                            <strong class="<?= ($absenceNotified || $studentNoShow) ? 'text-danger' : '' ?>"><?= e($a['student_name']) ?></strong>
                            <?php if ($absenceNotified): ?>
                                <span class="badge text-bg-danger ms-1"><i class="bi bi-exclamation-triangle"></i> Aluno avisou que não vem</span>
                                <small class="d-block text-danger">Avisou em <?= e(date('d/m/Y H:i', strtotime($a['absence_notified_at']))) ?><?= !empty($a['absence_reason']) ? ' - ' . e($a['absence_reason']) : '' ?></small>
                            <?php endif; ?>
                            <?php if ($studentNoShow): ?>
                                <span class="badge text-bg-danger ms-1"><i class="bi bi-person-x"></i> Profissional marcou falta</span>
                                <small class="d-block text-danger">Registrada em <?= e(date('d/m/Y H:i', strtotime($a['student_no_show_at']))) ?><?= !empty($a['student_no_show_reason']) ? ' - ' . e($a['student_no_show_reason']) : '' ?></small>
                            <?php endif; ?>
                            <small class="d-block text-muted"><?= e($a['student_email']) ?> / <?= e(format_whatsapp($a['student_whatsapp'] ?? '')) ?></small>
                        </td>
                        <td>
                            <span class="badge text-bg-light border text-dark me-1">#<?= (int)$professionalSequence ?></span><?= e($a['professional_name']) ?><small class="d-block text-muted"><?= e($a['professional_type']) ?></small>
                            <?php if ($professionalAbsence): ?>
                                <span class="badge text-bg-warning text-dark mt-1"><i class="bi bi-exclamation-octagon"></i> Instrutor não vai comparecer</span>
                                <small class="d-block text-warning-emphasis">Avisou em <?= e(date('d/m/Y H:i', strtotime($a['professional_absence_notified_at']))) ?><?= !empty($a['professional_absence_reason']) ? ' - ' . e($a['professional_absence_reason']) : '' ?></small>
                            <?php endif; ?>
                        </td>
                        <td style="min-width:250px">
                            <span class="badge text-bg-primary">Categoria <?= e($a['lesson_category'] ?? '-') ?></span>
                            <span class="badge <?= e(lesson_color_badge_class($a['lesson_color'] ?? 'blue')) ?>"><?= e(lesson_color_label($a['lesson_color'] ?? 'blue')) ?></span>
                            <strong class="d-block mt-2"><?= e($a['lesson_subject'] ?? 'Conteúdo ainda não informado') ?></strong><?php if(!empty($a['lesson_process'])): ?><small class="d-block text-info"><?= e(license_process_options()[$a['lesson_process']]??$a['lesson_process']) ?></small><?php endif; ?>
                            <small class="d-block text-muted"><?= (int)($a['lesson_units'] ?: Appointment::lessonUnitsFromRange($a['start_at'], $a['end_at'])) ?> aula(s) de 50 min</small>
                            <?php if (!empty($a['lesson_confirmed_at'])): ?><span class="badge text-bg-success mt-1"><i class="bi bi-check2-circle"></i> Confirmada pelo instrutor</span><?php endif; ?>
                        </td>
                        <td>
                            <?php if (!$absenceNotified && !$studentNoShow && !$professionalAbsence): ?>
                                <span class="text-muted small">Sem ocorrencias</span>
                            <?php else: ?>
                                <?php if ($absenceNotified): ?><span class="badge text-bg-danger mb-1">Aluno avisou ausência</span><br><?php endif; ?>
                                <?php if ($studentNoShow): ?><span class="badge text-bg-danger mb-1">Falta do aluno registrada</span><br><?php endif; ?>
                                <?php if ($professionalAbsence): ?><span class="badge text-bg-warning text-dark mb-1">Ausencia do Instrutor</span><?php endif; ?>
                            <?php endif; ?>
                        </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></td>
                        <td class="text-end">
                            <?php if (($a['status'] ?? '') === 'booked'): ?>
                                <details class="border rounded-3 p-2 mb-2 text-start"><summary class="small fw-semibold text-primary"><i class="bi bi-calendar2-week"></i> Alterar data / hora</summary>
                                    <form method="post" action="<?= e(url('admin/appointments/reschedule')) ?>" class="row g-2 mt-2">
                                        <?= CSRF::input() ?><input type="hidden" name="appointment_id" value="<?= (int)$a['id'] ?>"><input type="hidden" name="return_date" value="<?= e($filters['date']) ?>">
                                        <div class="col-7"><input type="date" name="new_date" class="form-control form-control-sm" required value="<?= e(substr($a['start_at'],0,10)) ?>"></div><div class="col-5"><input type="time" name="new_time" class="form-control form-control-sm" required value="<?= e(date('H:i',strtotime($a['start_at']))) ?>"></div>
                                        <div class="col-5"><input type="number" name="duration" min="50" max="240" step="10" class="form-control form-control-sm" value="<?= max(50,(int)round((strtotime($a['end_at'])-strtotime($a['start_at']))/60)) ?>"></div>
                                        <div class="col-7 small"><label class="form-check"><input class="form-check-input" type="checkbox" name="allow_holiday" value="1"> Desbloquear feriado</label><label class="form-check"><input class="form-check-input" type="checkbox" name="allow_daily_limit_override" value="1"> Exceção limite aluno</label></div>
                                        <div class="col-12"><button class="btn btn-sm btn-primary rounded-pill w-100"><i class="bi bi-save"></i> Salvar nova data/hora</button></div>
                                    </form>
                                </details>
                                <form method="post" action="<?= e(url('admin/appointments/lesson')) ?>" class="border rounded-3 p-2 mb-2 text-start">
                                    <?= CSRF::input() ?><input type="hidden" name="appointment_id" value="<?= (int)$a['id'] ?>"><input type="hidden" name="date" value="<?= e($filters['date']) ?>">
                                    <div class="row g-2"><div class="col-4"><select name="lesson_category" class="form-select form-select-sm" required><?php foreach (driving_category_options() as $catKey => $catLabel): ?><option value="<?= e($catKey) ?>" <?= ($a['lesson_category'] ?? '')===$catKey?'selected':'' ?>><?= e($catKey) ?></option><?php endforeach; ?></select></div><div class="col-8"><select name="lesson_process" class="form-select form-select-sm" required><option value="">Tipo da aula</option><?php foreach(license_process_options() as $processKey=>$processLabel): ?><option value="<?= e($processKey) ?>" <?= ($a['lesson_process']??'')===$processKey?'selected':'' ?>><?= e($processLabel) ?></option><?php endforeach; ?></select></div><div class="col-12"><input name="lesson_subject" class="form-control form-control-sm" value="<?= e($a['lesson_subject'] ?? '') ?>" required placeholder="Conteúdo da aula"></div><div class="col-12"><button class="btn btn-sm btn-outline-success rounded-pill w-100"><i class="bi bi-journal-check"></i> Salvar Aula</button></div></div>
                                </form>
                                <form method="post" action="<?= e(url('admin/appointments/color')) ?>" class="d-flex justify-content-end gap-2 mb-2">
                                    <?= CSRF::input() ?>
                                    <input type="hidden" name="appointment_id" value="<?= (int)$a['id'] ?>">
                                    <input type="hidden" name="date" value="<?= e($filters['date']) ?>">
                                    <select name="lesson_color" class="form-select form-select-sm" style="max-width:130px">
                                        <option value="blue" <?= normalize_lesson_color($a['lesson_color'] ?? 'blue') === 'blue' ? 'selected' : '' ?>>Monitorada</option>
                                        <option value="green" <?= normalize_lesson_color($a['lesson_color'] ?? 'blue') === 'green' ? 'selected' : '' ?>>Sem Monitorar</option>
                                        <option value="red" <?= normalize_lesson_color($a['lesson_color'] ?? 'blue') === 'red' ? 'selected' : '' ?>>Conclusão</option>
                                    </select>
                                    <button class="btn btn-sm btn-outline-primary rounded-pill">Salvar Status</button>
                                </form>
                                <form method="post" action="<?= e(url('admin/appointments/unlock')) ?>" onsubmit="return confirm('Desbloquear está aula? O horário ficará livre e depois poderá ser removido na disponibilidade.');">
                                    <?= CSRF::input() ?>
                                    <input type="hidden" name="appointment_id" value="<?= (int)$a['id'] ?>">
                                    <input type="hidden" name="date" value="<?= e($filters['date']) ?>">
                                    <button class="btn btn-sm btn-warning rounded-pill"><i class="bi bi-unlock"></i> Desbloquear</button>
                                </form>
                            <?php elseif (($a['status'] ?? '') === 'completed'): ?>
                                <form method="post" action="<?= e(url('admin/appointments/reopen')) ?>" onsubmit="return confirm('Desfazer a confirmação e devolver as aulas ao saldo do aluno?');"><?= CSRF::input() ?><input type="hidden" name="appointment_id" value="<?= (int)$a['id'] ?>"><input type="hidden" name="date" value="<?= e($filters['date']) ?>"><button class="btn btn-sm btn-outline-warning rounded-pill"><i class="bi bi-arrow-counterclockwise"></i> Desfazer confirmação</button></form>
                            <?php else: ?>
                                <span class="text-muted small">Sem ação</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (!$appointments): ?>
                    <tr><td colspan="7" class="text-center text-muted py-4">Nenhum agendamento encontrado.</td></tr>
                <?php endif; ?>
                </tbody></table></div>
            </div></div>
        </div>
    </div>
</main>

<script>
(()=>{const c=document.getElementById('quickPackageCategory'),a=document.getElementById('quickPackageA'),b=document.getElementById('quickPackageB'),o=document.getElementById('quickPackageOther'); if(!c)return; const sync=()=>{const v=c.value;a.disabled=!['A','AB'].includes(v);b.disabled=!['B','AB'].includes(v);o.disabled=!['C','D','E'].includes(v);if(['A','AB'].includes(v))a.value=Math.max(2,parseInt(a.value||2));if(['B','AB'].includes(v))b.value=Math.max(2,parseInt(b.value||2));if(['C','D','E'].includes(v))o.value=Math.max(2,parseInt(o.value||2));};c.addEventListener('change',sync);sync();})();
</script>
<script type="application/json" id="manualBookingSummariesJson"><?= json_encode($studentBookingSummaries ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?></script>
<script>
(() => {
    const form = document.getElementById('manualAppointmentForm');
    const student = document.getElementById('manualAppointmentStudent');
    const category = document.getElementById('manualLessonCategory');
    const duration = document.getElementById('manualLessonDuration');
    const professional = document.getElementById('manualAppointmentProfessional');
    const appointmentDate = document.getElementById('manualAppointmentDate');
    const status = document.getElementById('manualBookingStatus');
    const submit = document.getElementById('manualAppointmentSubmit');
    const dataNode = document.getElementById('manualBookingSummariesJson');
    if (!form || !student || !category || !duration || !professional || !appointmentDate || !status || !submit || !dataNode) return;
    let summaries = {};
    try { summaries = JSON.parse(dataNode.textContent || '{}'); } catch (_) { summaries = {}; }
    const unitsNeeded = () => Math.max(1, Math.ceil((parseInt(duration.value || '50', 10) || 50) / 50));
    const escapeHtml = (value) => String(value ?? '').replace(/[&<>'"]/g, char => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#039;','"':'&quot;'}[char]));
    const refreshProfessionals = async () => {
        const endpoint = form.dataset.professionalOptionsUrl || '';
        if (!endpoint || !appointmentDate.value) return;
        const current = professional.value;
        professional.disabled = true;
        try {
            const joiner = endpoint.includes('?') ? '&' : '?';
            const response = await fetch(`${endpoint}${joiner}date=${encodeURIComponent(appointmentDate.value)}&units=${encodeURIComponent(unitsNeeded())}`, {headers:{'X-Requested-With':'XMLHttpRequest'}});
            const payload = await response.json();
            const list = Array.isArray(payload.professionals) ? payload.professionals.filter(item => item.available) : [];
            professional.innerHTML = '<option value="">Selecione</option>' + list.map(item => {
                const limit = Number(item.daily_lesson_limit || 0);
                const detail = limit > 0 ? ` · ${Number(item.used || 0)}/${limit} aulas` : ' · sem limite diário';
                return `<option value="${Number(item.id)}">${escapeHtml(item.name)} - ${escapeHtml(item.type || 'Instrutor')}${detail}</option>`;
            }).join('');
            if (list.some(item => String(item.id) === String(current))) professional.value = current;
            if (!list.length) professional.innerHTML = '<option value="">Nenhum instrutor disponível nesta data</option>';
        } catch (_) {
            // Mantém a validação do servidor como proteção principal.
        } finally {
            professional.disabled = false;
        }
    };
    const render = () => {
        const summary = summaries[String(student.value)] || null;
        status.className = 'col-12 d-none'; status.innerHTML = ''; submit.disabled = false;
        if (!summary) return;
        const rows = Array.isArray(summary.categories) ? summary.categories : [];
        if (!rows.length) {
            status.className = 'col-12 alert alert-danger rounded-4 mb-0';
            status.innerHTML = '<i class="bi bi-exclamation-triangle-fill"></i> Este aluno não possui aulas práticas contratadas. Cadastre um pacote antes de agendar.';
            submit.disabled = true; return;
        }
        const badges = rows.map(row => `<span class="badge text-bg-light border text-dark me-1 mb-1">Cat. ${escapeHtml(row.category)}: ${Number(row.used || 0)} concluída(s), ${Number(row.scheduled || 0)} agendada(s), ${Number(row.available_to_schedule || 0)} disponível(is)</span>`).join('');
        const selected = rows.find(row => String(row.category || '') === String(category.value || ''));
        const required = unitsNeeded();
        let blocked = Boolean(summary.completed_or_scheduled);
        let message = blocked
            ? '<strong><i class="bi bi-check-circle-fill"></i> Quantidade de aulas completada:</strong> todas as aulas contratadas já foram concluídas ou estão agendadas.'
            : '<strong>Resumo do pacote do aluno:</strong>';
        if (!blocked && category.value && (!selected || Number(selected.available_to_schedule || 0) < required)) {
            blocked = true;
            message = `<strong><i class="bi bi-lock-fill"></i> Não é possível criar este agendamento:</strong> a categoria ${escapeHtml(category.value)} não possui ${required} aula(s) disponível(is).`;
        }
        status.className = `col-12 alert ${blocked ? 'alert-danger' : 'alert-info'} rounded-4 mb-0`;
        status.innerHTML = `${message}<div class="mt-2">${badges}</div>`;
        submit.disabled = blocked;
    };
    student.addEventListener('change', render);
    category.addEventListener('change', render);
    duration.addEventListener('input', () => { render(); refreshProfessionals(); });
    appointmentDate.addEventListener('change', refreshProfessionals);
    render();
    refreshProfessionals();
})();
</script>

<script>
(() => {
    const button = document.getElementById('downloadSchedulePng');
    const node = document.getElementById('scheduleExportJson');
    if (!button || !node) return;
    let data={}; try{data=JSON.parse(node.textContent||'{}');}catch(_){return;}
    const parseDate = value => { const parts=String(value||'').split('/'); return parts.length===3 ? new Date(Number(parts[2]),Number(parts[1])-1,Number(parts[0])) : new Date(0); };
    const draw = async () => {
        const items=(Array.isArray(data.items)?data.items:[]).slice().sort((a,b)=>String(a.category).localeCompare(String(b.category),'pt-BR') || parseDate(a.date)-parseDate(b.date) || String(a.time).localeCompare(String(b.time)));
        const rows=Math.max(1,items.length); const height=Math.max(900,330+rows*92+120);
        const canvas=document.createElement('canvas'); canvas.width=1080; canvas.height=height; const ctx=canvas.getContext('2d');
        ctx.fillStyle='#f4f7fb'; ctx.fillRect(0,0,canvas.width,canvas.height); ctx.fillStyle='#ffffff'; ctx.fillRect(45,45,990,height-90);
        ctx.fillStyle='#123f73'; ctx.fillRect(45,45,990,220); ctx.fillStyle='#ffffff'; ctx.font='700 42px Arial'; ctx.fillText(String(data.school||'Autoescola'),90,115); ctx.font='700 30px Arial'; ctx.fillText('AGENDA DE AULAS',90,165); ctx.font='24px Arial'; ctx.fillText('Aluno: '+String(data.student||'Aluno'),90,210);
        if(data.logo){ try{ const img=new Image(); await new Promise((resolve,reject)=>{img.onload=resolve;img.onerror=reject;img.src=data.logo;}); ctx.drawImage(img,835,70,155,155); }catch(_){} }
        let y=315, current='';
        if(!items.length){ ctx.fillStyle='#374151';ctx.font='26px Arial';ctx.fillText('Nenhuma aula ativa para gerar.',90,y+40); }
        for(const item of items){
            if(String(item.category)!==current){ current=String(item.category); ctx.fillStyle='#e8f1fb';ctx.fillRect(75,y,930,54);ctx.fillStyle='#123f73';ctx.font='700 25px Arial';ctx.fillText('Categoria '+current,95,y+35);y+=70; }
            ctx.fillStyle='#111827';ctx.font='700 23px Arial';ctx.fillText(`${item.date} · ${item.weekday} · ${item.time}`,95,y+27);
            ctx.fillStyle='#374151';ctx.font='21px Arial';ctx.fillText('Instrutor: '+String(item.professional||'-'),95,y+57);
            const subject=String(item.subject||'Aula prática'); ctx.fillStyle='#6b7280';ctx.font='19px Arial';ctx.fillText(subject.length>72?subject.slice(0,69)+'...':subject,560,y+57); y+=88;
        }
        ctx.fillStyle='#6b7280';ctx.font='18px Arial';ctx.fillText('Gerado pelo sistema em '+new Date().toLocaleString('pt-BR'),90,height-70);
        const link=document.createElement('a'); link.download='agenda-'+String(data.student||'aluno').normalize('NFD').replace(/[\u0300-\u036f]/g,'').replace(/[^a-z0-9]+/gi,'-').replace(/^-|-$/g,'').toLowerCase()+'.png'; link.href=canvas.toDataURL('image/png'); link.click();
    };
    button.addEventListener('click',()=>draw().catch(()=>alert('Não foi possível gerar a imagem da agenda.')));
})();
</script>
