<?php
$monthLabels=[1=>'Janeiro',2=>'Fevereiro',3=>'Março',4=>'Abril',5=>'Maio',6=>'Junho',7=>'Julho',8=>'Agosto',9=>'Setembro',10=>'Outubro',11=>'Novembro',12=>'Dezembro'];
$monthTitle=function(string $month)use($monthLabels){$parts=explode('-',$month);return ($monthLabels[(int)($parts[1]??0)]??$month).' de '.($parts[0]??'');};
$currentAppointments=$months[$selectedMonth]??[];
?>
<main class="container py-4 py-md-5">
    <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-3 mb-4"><div><h1 class="h3 fw-bold text-cfc-dark mb-1"><i class="bi bi-calendar2-check"></i> Quantidade e histórico de aulas</h1><p class="text-muted mb-0">As aulas estão organizadas por mês. Escolha um mês para ver os detalhes.</p></div><a class="btn btn-outline-primary rounded-pill" href="<?= e(url('dashboard')) ?>"><i class="bi bi-arrow-left"></i> Voltar ao início</a></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">Contrato de aulas</h2><div class="row g-3">
        <?php foreach($lessonPackages as $pkg): ?><div class="col-sm-6 col-lg-3"><div class="border rounded-4 p-3 h-100"><span class="badge text-bg-primary mb-2">Categoria <?= e($pkg['category']) ?></span><div class="row text-center g-2"><div class="col-4"><strong class="d-block fs-4"><?= (int)$pkg['contracted_lessons'] ?></strong><small class="text-muted">Contratadas</small></div><div class="col-4"><strong class="d-block fs-4 text-success"><?= (int)$pkg['used_lessons'] ?></strong><small class="text-muted">Realizadas</small></div><div class="col-4"><strong class="d-block fs-4 text-primary"><?= (int)$pkg['remaining_lessons'] ?></strong><small class="text-muted">Restantes</small></div></div></div></div><?php endforeach; ?>
        <?php if(empty($lessonPackages)): ?><div class="col-12"><div class="alert alert-warning rounded-4 mb-0">O administrador ainda não configurou seu pacote de aulas.</div></div><?php endif; ?>
    </div></div></div>

    <div class="month-selector mb-4">
        <?php foreach(array_keys($months) as $month): ?><a class="btn <?= $month===$selectedMonth?'btn-primary':'btn-outline-primary' ?> rounded-pill" href="<?= e(url('lessons',['month'=>$month])) ?>"><?= e($monthTitle($month)) ?> <span class="badge text-bg-light text-dark ms-1"><?= count($months[$month]) ?></span></a><?php endforeach; ?>
        <?php if(empty($months)): ?><span class="text-muted">Nenhum mês com aulas registrado.</span><?php endif; ?>
    </div>

    <div class="card border-0 shadow-soft rounded-4"><div class="card-body p-4"><h2 class="h5 fw-bold mb-3"><?= e($monthTitle($selectedMonth)) ?></h2>
        <?php if(empty($currentAppointments)): ?><div class="alert alert-info rounded-4 mb-0">Nenhuma aula encontrada neste mês.</div><?php else: ?><div class="row g-3">
        <?php foreach($currentAppointments as $a): ?>
            <?php $canRate=in_array($a['status'],['booked','completed'],true)&&Appointment::canRateByDate($a['start_at']);$absence=!empty($a['absence_notified_at']);$noShow=!empty($a['student_no_show_at']);$profAbsence=!empty($a['professional_absence_notified_at']);$canNotify=$a['status']==='booked'&&!$absence&&!$noShow&&!$profAbsence&&strtotime($a['start_at'])>=strtotime(date('Y-m-d 00:00:00')); ?>
            <div class="col-12"><div class="lesson-month-card border rounded-4 p-3 <?= $a['status']==='completed'?'lesson-completed':'' ?>">
                <div class="row g-3 align-items-start"><div class="col-md-2"><strong class="d-block fs-5"><?= e(date('d/m/Y',strtotime($a['start_at']))) ?></strong><small class="text-muted"><?= e(date('H:i',strtotime($a['start_at']))) ?>–<?= e(date('H:i',strtotime($a['end_at']))) ?></small></div><div class="col-md-3"><div class="d-flex align-items-center gap-2"><?php if(!empty($a['professional_photo_path'])): ?><img src="<?= e(asset($a['professional_photo_path'])) ?>" class="profile-avatar" alt="Foto de <?= e($a['professional_name']) ?>"><?php else: ?><span class="profile-avatar profile-placeholder"><i class="bi bi-person-fill"></i></span><?php endif; ?><div><strong><?= e($a['professional_name']) ?></strong><small class="d-block text-muted"><?= e($a['professional_type']) ?></small><?php if(!empty($a['professional_internal_code'])): ?><small class="d-block text-primary">Mensagem: <?= e($a['professional_internal_code']) ?></small><?php endif; ?></div></div></div><div class="col-md-3"><span class="badge text-bg-primary">Categoria <?= e($a['lesson_category']??'-') ?></span><strong class="d-block mt-1"><?= e($a['lesson_subject']??'Conteúdo não informado') ?></strong><small class="text-muted"><?= (int)($a['lesson_units']?:Appointment::lessonUnitsFromRange($a['start_at'],$a['end_at'])) ?> aula(s) registrada(s)</small></div><div class="col-md-2"><span class="badge <?= $a['status']==='completed'?'text-bg-success':($a['status']==='booked'?'text-bg-primary':'text-bg-secondary') ?>"><?= e($a['status']==='completed'?'Realizada':($a['status']==='booked'?'Agendada':'Cancelada')) ?></span><?php if($absence||$noShow||$profAbsence): ?><span class="badge text-bg-danger d-block mt-2">Ocorrência registrada</span><?php endif; ?></div>
                <div class="col-md-2 d-grid gap-2">
                    <?php if($canNotify): ?><form method="post" action="<?= e(url('absence/notify')) ?>" onsubmit="return confirm('Avisar que você não vai comparecer?');"><?= CSRF::input() ?><input type="hidden" name="appointment_id" value="<?= (int)$a['id'] ?>"><input type="text" name="reason" class="form-control form-control-sm mb-2" placeholder="Motivo opcional"><button class="btn btn-sm btn-danger w-100">Avisar ausência</button></form><?php endif; ?>
                    <?php if($a['status']==='booked'): ?><form method="post" action="<?= e(url('cancel')) ?>" onsubmit="return confirm('Cancelar esta aula?');"><?= CSRF::input() ?><input type="hidden" name="appointment_id" value="<?= (int)$a['id'] ?>"><button class="btn btn-sm btn-outline-danger w-100">Cancelar</button></form><?php endif; ?>
                </div></div>
                <?php if(!empty($a['student_rating'])): ?><div class="alert alert-success rounded-3 mt-3 mb-0">Avaliação enviada: <?= (int)$a['student_rating'] ?>/5.</div><?php elseif($canRate&&!$absence&&!$noShow&&!$profAbsence): ?><form method="post" action="<?= e(url('rate/professional')) ?>" class="row g-2 mt-2"><?= CSRF::input() ?><input type="hidden" name="appointment_id" value="<?= (int)$a['id'] ?>"><div class="col-md-3"><select name="rating" class="form-select form-select-sm" required><option value="">Avaliar instrutor</option><option value="5">5 - Excelente</option><option value="4">4 - Muito bom</option><option value="3">3 - Bom</option><option value="2">2 - Regular</option><option value="1">1 - Ruim</option></select></div><div class="col-md-7"><input name="comment" class="form-control form-control-sm" placeholder="Comentário opcional"></div><div class="col-md-2"><button class="btn btn-success btn-sm w-100">Enviar</button></div></form><?php endif; ?>
            </div></div>
        <?php endforeach; ?>
        </div><?php endif; ?>
    </div></div>
</main>
