<?php
class StudentController
{
    public function dashboard(): void
    {
        Auth::requireStudent();
        $student = User::find(Auth::id());
        $appointments = Appointment::myAppointments(Auth::id());
        View::render('student/dashboard', [
            'appointments' => $appointments,
            'student' => $student,
            'lessonPackages' => StudentLessonPackage::forStudent(Auth::id()),
            'portalCharges' => PaymentCenter::forActor('student', Auth::id()),
            'pendingPortalCharges' => PaymentCenter::pendingForActor('student', Auth::id()),
            'videoCount' => count(VideoLesson::forActor('student', Auth::id())),
            'ebookCount' => count(Ebook::forStudent(Auth::id())),
            'availableSlotCount' => Slot::availableCountForStudent(Auth::id()),
            'learningLevels' => StudentLearningLevel::forStudent(Auth::id()),
            'unreadMessages' => Communication::unreadCount('student', Auth::id()),
            'unreadAudioMessages' => Communication::unreadAudioCount('student', Auth::id()),
            'studentAnnouncements' => Announcement::activeForStudents(),
            'groupCount' => count(TheoryGroup::forActor('student', Auth::id())),
            'studentSettings' => $this->studentSettings(),
        ]);
    }

    public function theory(): void
    {
        Auth::requireStudent();
        View::render('student/theory', [
            'lessons' => TheoryLesson::upcoming(),
            'studentSettings' => $this->studentSettings(),
        ]);
    }

    public function calendar(): void
    {
        Auth::requireStudent();
        $month = $_GET['month'] ?? date('Y-m');
        if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
            $month = date('Y-m');
        }
        $student = User::find(Auth::id()) ?: [];
        $slots = Slot::byMonthForStudent($month, Auth::id());
        $holidays = Holiday::byMonth($month, $student['uf'] ?? '', $student['city'] ?? '');
        View::render('student/calendar', ['slots' => $slots, 'month' => $month, 'holidays' => $holidays, 'bookingSummary'=>Appointment::studentBookingSummary(Auth::id())]);
    }

    public function book(): void
    {
        Auth::requireStudent();
        CSRF::check();
        $result = Appointment::book(Auth::id(), (int)($_POST['slot_id'] ?? 0));
        flash($result['ok'] ? 'success' : 'danger', $result['message']);
        redirect('calendar', ['month' => $_POST['month'] ?? date('Y-m')]);
    }

    public function cancel(): void
    {
        Auth::requireStudent();
        CSRF::check();
        $result = Appointment::cancelByStudent(Auth::id(), (int)($_POST['appointment_id'] ?? 0));
        flash($result['ok'] ? 'success' : 'danger', $result['message']);
        redirect('lessons');
    }


    public function notifyAbsence(): void
    {
        Auth::requireStudent();
        CSRF::check();
        $result = Appointment::notifyAbsenceByStudent(
            Auth::id(),
            (int)($_POST['appointment_id'] ?? 0),
            trim($_POST['reason'] ?? '')
        );
        flash($result['ok'] ? 'success' : 'danger', $result['message']);
        redirect('lessons');
    }

    public function ebooks(): void
    {
        Auth::requireStudent();
        View::render('student/ebooks', ['ebooks' => Ebook::forStudent(Auth::id())]);
    }

    public function downloadEbook(): void
    {
        Auth::requireStudent();
        $ebook = Ebook::findForStudent((int)($_GET['id'] ?? 0), Auth::id());
        if (!$ebook) {
            http_response_code(404);
            exit('E-book não encontrado ou não liberado para seu cadastro.');
        }
        Ebook::streamFile($ebook);
    }

    public function rateProfessional(): void
    {
        Auth::requireStudent();
        CSRF::check();
        $result = Appointment::rateProfessionalByStudent(
            Auth::id(),
            (int)($_POST['appointment_id'] ?? 0),
            (int)($_POST['rating'] ?? 0),
            trim($_POST['comment'] ?? '')
        );
        flash($result['ok'] ? 'success' : 'danger', $result['message']);
        redirect('lessons');
    }

    public function lessons(): void
    {
        Auth::requireStudent();
        $month = trim($_GET['month'] ?? date('Y-m'));
        if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
            $month = date('Y-m');
        }
        $all = Appointment::myAppointments(Auth::id());
        $months = [];
        foreach ($all as $appointment) {
            $key = substr((string)$appointment['start_at'], 0, 7);
            $months[$key][] = $appointment;
        }
        krsort($months);
        if ($months && !isset($months[$month])) {
            $month = (string)array_key_first($months);
        }
        View::render('student/lessons', [
            'student' => User::find(Auth::id()),
            'lessonPackages' => StudentLessonPackage::forStudent(Auth::id()),
            'months' => $months,
            'selectedMonth' => $month,
        ]);
    }

    public function quickLinks(): void
    {
        Auth::requireStudent();
        flash('info', 'A área de links foi removida do painel do aluno. Você foi direcionado para a prova teórica.');
        redirect('theory');
    }

    public function updateProfilePhoto(): void
    {
        Auth::requireStudent();
        CSRF::check();
        $result = User::updateProfilePhoto(Auth::id(), $_FILES['profile_photo'] ?? []);
        flash($result['ok'] ? 'success' : 'danger', $result['message']);
        redirect('dashboard');
    }


    private function studentSettings(): array
    {
        $settings = Settings::safeAll();
        if (normalize_http_url($settings['detran_simulado_url'] ?? '') !== '') {
            return $settings;
        }

        // Compatibilidade com instalações antigas: reaproveita o link DETRAN
        // já cadastrado em Links Rápidos quando o novo campo ainda estiver vazio.
        foreach (QuickLink::active() as $link) {
            $name = mb_strtolower(trim((string)($link['name'] ?? '')));
            if (str_contains($name, 'detran') || str_contains($name, 'simulado') || str_contains($name, 'prova')) {
                $url = normalize_http_url($link['url'] ?? '');
                if ($url !== '') {
                    $settings['detran_simulado_url'] = $url;
                    if (trim((string)($settings['detran_simulado_button_text'] ?? '')) === '') {
                        $settings['detran_simulado_button_text'] = 'Abrir Simulado DETRAN';
                    }
                    break;
                }
            }
        }
        return $settings;
    }

}
