<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Student Controller
 *
 * Manage student records with enrollment details.
 */
class AdminStudentController extends AdminController
{
    /**
     * List all students with course and branch info.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $stmt = $this->db->query(
            'SELECT s.*, u.name AS student_name, u.email AS student_email,
                    c.name AS course_name, b.name AS branch_name
             FROM `students` s
             LEFT JOIN `users` u ON s.user_id = u.id
             LEFT JOIN `courses` c ON s.course_id = c.id
             LEFT JOIN `branches` b ON s.branch_id = b.id
             ORDER BY s.created_at DESC'
        );
        $students = $stmt->fetchAll() ?: [];

        $this->adminView('students', [
            'title'       => 'Manage Students',
            'currentPage' => 'students',
            'students'    => $students,
            'viewStudent' => null,
            'editStudent' => null,
        ]);
    }

    /**
     * Show student details.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function show(array $params = []): void
    {
        requireAdmin();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare(
            'SELECT s.*, u.name AS student_name, u.email AS student_email, u.phone AS student_phone,
                    u.photo AS student_photo, u.is_active AS user_active,
                    c.name AS course_name, b.name AS branch_name
             FROM `students` s
             LEFT JOIN `users` u ON s.user_id = u.id
             LEFT JOIN `courses` c ON s.course_id = c.id
             LEFT JOIN `branches` b ON s.branch_id = b.id
             WHERE s.id = :id LIMIT 1'
        );
        $stmt->execute([':id' => $id]);
        $viewStudent = $stmt->fetch() ?: null;

        if ($viewStudent === null) {
            flash('error', 'Student not found.');
            redirect('/admin/students');
        }

        // Get exam results for this student
        $stmt = $this->db->prepare(
            'SELECT er.*, e.title AS exam_title
             FROM `exam_results` er
             LEFT JOIN `exams` e ON er.exam_id = e.id
             WHERE er.student_id = :student_id
             ORDER BY er.created_at DESC'
        );
        $stmt->execute([':student_id' => $id]);
        $examResults = $stmt->fetchAll() ?: [];

        $this->adminView('students', [
            'title'        => 'Student Details',
            'currentPage'  => 'students',
            'students'     => [],
            'viewStudent'  => $viewStudent,
            'editStudent'  => null,
            'examResults'  => $examResults,
            'showDetail'   => true,
        ]);
    }

    /**
     * Show the edit student form.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function edit(array $params = []): void
    {
        requireAdmin();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare(
            'SELECT s.*, u.name AS student_name, u.email AS student_email, u.phone AS student_phone,
                    c.name AS course_name, b.name AS branch_name
             FROM `students` s
             LEFT JOIN `users` u ON s.user_id = u.id
             LEFT JOIN `courses` c ON s.course_id = c.id
             LEFT JOIN `branches` b ON s.branch_id = b.id
             WHERE s.id = :id LIMIT 1'
        );
        $stmt->execute([':id' => $id]);
        $editStudent = $stmt->fetch() ?: null;

        if ($editStudent === null) {
            flash('error', 'Student not found.');
            redirect('/admin/students');
        }

        // Get courses and branches for dropdowns
        $stmt = $this->db->query('SELECT `id`, `name` FROM `courses` WHERE `active` = 1 ORDER BY `name` ASC');
        $courses = $stmt->fetchAll() ?: [];

        $stmt = $this->db->query('SELECT `id`, `name`, `city` FROM `branches` WHERE `active` = 1 ORDER BY `name` ASC');
        $branches = $stmt->fetchAll() ?: [];

        $this->adminView('students', [
            'title'       => 'Edit Student',
            'currentPage' => 'students',
            'students'    => [],
            'viewStudent' => null,
            'editStudent' => $editStudent,
            'courses'     => $courses,
            'branches'    => $branches,
            'showEdit'    => true,
        ]);
    }

    /**
     * Update a student record.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function update(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $status   = sanitize($_POST['status'] ?? 'active');
        $courseId = (int) ($_POST['course_id'] ?? 0);
        $branchId = (int) ($_POST['branch_id'] ?? 0);

        if (!in_array($status, ['active', 'completed', 'dropped'], true)) {
            $status = 'active';
        }

        $stmt = $this->db->prepare(
            'UPDATE `students` SET `status` = :status, `course_id` = :course_id, `branch_id` = :branch_id
             WHERE `id` = :id'
        );

        $stmt->execute([
            ':status'    => $status,
            ':course_id' => $courseId,
            ':branch_id' => $branchId,
            ':id'        => $id,
        ]);

        flash('success', 'Student updated successfully.');
        redirect('/admin/students');
    }

    /**
     * Delete a student record.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare('DELETE FROM `students` WHERE `id` = :id');
        $stmt->execute([':id' => $id]);

        flash('success', 'Student deleted successfully.');
        redirect('/admin/students');
    }
}
