<?php
$first = DateTime::createFromFormat('Y-m-d', $month . '-01') ?: new DateTime('first day of this month');
$prev = (clone $first)->modify('-1 month')->format('Y-m');
$next = (clone $first)->modify('+1 month')->format('Y-m');
$daysInMonth = (int)$first->format('t');
$startWeekday = (int)$first->format('N');
$byDate = [];
foreach ($slots as $slot) {
    $byDate[substr($slot['start_at'], 0, 10)][] = $slot;
}
$holidayByDate = [];
foreach (($holidays ?? []) as $holiday) {
    $holidayByDate[$holiday['holiday_date']][] = $holiday;
}
$weekDays = ['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'];
?>
<main class="container py-4 py-md-5">
<?php $hasBookingPackages=!empty($bookingSummary['has_packages']); $bookingCompleted=!empty($bookingSummary['completed_or_scheduled']); $bookingBlocked=!$hasBookingPackages||$bookingCompleted; ?>
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4 calendar-header-wrap">
        <div>
            <h1 class="h3 fw-bold text-cfc-dark mb-1">Calendário de Aulas</h1>
            <p class="text-muted mb-0">Horários ocupados por outros alunos aparecem indisponíveis, sem expor dados pessoais.</p>
        </div>
        <div class="btn-group calendar-month-nav">
            <a class="btn btn-outline-primary" href="<?= e(url('calendar', ['month' => $prev])) ?>">Anterior</a>
            <a class="btn btn-primary" href="<?= e(url('calendar', ['month' => date('Y-m')])) ?>"><?= e($first->format('m/y')) ?></a>
            <a class="btn btn-outline-primary" href="<?= e(url('calendar', ['month' => $next])) ?>">Próximo</a>
        </div>
    </div>

    <?php if(!$hasBookingPackages): ?><div class="alert alert-danger rounded-4 shadow-soft"><i class="bi bi-exclamation-triangle-fill"></i> <strong>Nenhum pacote de aulas práticas disponível.</strong> Procure a administração para cadastrar/liberar suas aulas antes de agendar.</div><?php elseif($bookingCompleted): ?><div class="alert alert-success rounded-4 shadow-soft"><i class="bi bi-check-circle-fill"></i> <strong>Quantidade de aulas completada:</strong> todas as aulas contratadas já foram concluídas ou estão agendadas. Novos agendamentos foram bloqueados.</div><?php elseif(!empty($bookingSummary['categories'])): ?><div class="alert alert-info rounded-4"><strong>Saldo disponível para agendar:</strong> <?php foreach($bookingSummary['categories'] as $balance): ?><span class="badge text-bg-light border text-dark me-1">Categoria <?= e($balance['category']) ?>: <?= (int)$balance['available_to_schedule'] ?></span><?php endforeach; ?></div><?php endif; ?>

    <div class="calendar-week-head" aria-hidden="true">
        <?php foreach ($weekDays as $weekDay): ?>
            <div><?= e($weekDay) ?></div>
        <?php endforeach; ?>
    </div>

    <div class="calendar-grid">
        <?php for ($blank = 1; $blank < $startWeekday; $blank++): ?>
            <div class="calendar-empty"></div>
        <?php endfor; ?>

        <?php for ($day = 1; $day <= $daysInMonth; $day++): ?>
            <?php $date = $first->format('Y-m-') . str_pad((string)$day, 2, '0', STR_PAD_LEFT); ?>
            <?php $dayHolidays = $holidayByDate[$date] ?? []; ?>
            <div class="calendar-cell">
                <div class="calendar-day <?= $date === date('Y-m-d') ? 'today' : '' ?> <?= $dayHolidays ? 'calendar-holiday' : '' ?>">
                    <div class="calendar-date-line mb-2">
                        <strong><?= $day ?></strong>
                        <span class="calendar-mobile-weekday text-muted"><?= e(weekday_pt($date)) ?></span>
                    </div>

                    <?php if ($dayHolidays): ?>
                        <?php foreach ($dayHolidays as $holiday): ?>
                            <div class="holiday-pill mb-2">
                                <i class="bi bi-calendar-heart"></i>
                                <strong><?= e($holiday['name']) ?></strong><br>
                                <small><?= e(Holiday::typeLabel($holiday['type'])) ?></small>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

                    <?php foreach ($byDate[$date] ?? [] as $slot): ?>
                        <?php
                            $isBooked = !empty($slot['appointment_id']);
                            $isMine = $isBooked && ((int)$slot['booked_student_id'] === Auth::id());
                            $slotClass = $isMine ? 'slot-mine' : ($isBooked ? 'slot-busy' : 'slot-free');
                        ?>
                        <?php if ($dayHolidays): ?>
                            <div class="slot-pill slot-busy">
                                <strong><?= e(date('H:i', strtotime($slot['start_at']))) ?></strong> <?= e($slot['professional_name']) ?><br>
                                <small>Feriado - Indisponível para agendamento</small>
                            </div>
                        <?php elseif (!$isBooked && !$bookingBlocked): ?>
                            <form method="post" action="<?= e(url('book')) ?>" onsubmit="return confirm('Confirmar agendamento deste horário?');">
                                <?= CSRF::input() ?>
                                <input type="hidden" name="slot_id" value="<?= (int)$slot['id'] ?>">
                                <input type="hidden" name="month" value="<?= e($month) ?>">
                                <button class="slot-pill <?= e($slotClass) ?>">
                                    <strong><?= e(date('H:i', strtotime($slot['start_at']))) ?></strong> <?= e($slot['professional_name']) ?><br>
                                    <small>Livre - Clique Para Agendar</small>
                                </button>
                            </form>
                        <?php else: ?>
                            <div class="slot-pill <?= e($slotClass) ?>">
                                <strong><?= e(date('H:i', strtotime($slot['start_at']))) ?></strong> <?= e($slot['professional_name']) ?><br>
                                <small><?= $isMine ? 'Minha Aula' : 'Indisponível' ?></small>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>

                    <?php if (empty($byDate[$date])): ?>
                        <small class="text-muted">Sem horários</small>
                    <?php endif; ?>
                </div>
            </div>
        <?php endfor; ?>
    </div>
</main>
