<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Topper Controller
 *
 * CRUD operations for top-performing students.
 */
class AdminTopperController extends AdminController
{
    /**
     * List all toppers.
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $stmt = $this->db->query(
            'SELECT t.*, c.name AS course_name, b.name AS branch_name
             FROM `toppers` t
             LEFT JOIN `courses` c ON t.course_id = c.id
             LEFT JOIN `branches` b ON t.branch_id = b.id
             ORDER BY t.sort_order ASC, t.created_at DESC'
        );
        $toppers = $stmt->fetchAll() ?: [];

        // Fetch courses and branches for the add/edit form
        $courses = $this->db->query('SELECT `id`, `name` FROM `courses` WHERE `active` = 1 ORDER BY `name` ASC')->fetchAll() ?: [];
        $branches = $this->db->query('SELECT `id`, `name`, `city` FROM `branches` WHERE `active` = 1 ORDER BY `name` ASC')->fetchAll() ?: [];

        $this->adminView('toppers', [
            'title'       => 'Manage Toppers',
            'currentPage' => 'toppers',
            'toppers'     => $toppers,
            'courses'     => $courses,
            'branches'    => $branches,
            'editTopper'  => null,
            'showForm'    => false,
        ]);
    }

    /**
     * Show the edit form for a topper.
     */
    public function edit(array $params = []): void
    {
        requireAdmin();

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

        $stmt = $this->db->prepare(
            'SELECT t.*, c.name AS course_name, b.name AS branch_name
             FROM `toppers` t
             LEFT JOIN `courses` c ON t.course_id = c.id
             LEFT JOIN `branches` b ON t.branch_id = b.id
             WHERE t.id = :id LIMIT 1'
        );
        $stmt->execute([':id' => $id]);
        $editTopper = $stmt->fetch() ?: null;

        if ($editTopper === null) {
            flash('error', 'Topper not found.');
            redirect(BASE_PATH . '/admin/toppers');
        }

        $toppers = $this->db->query(
            'SELECT t.*, c.name AS course_name, b.name AS branch_name
             FROM `toppers` t
             LEFT JOIN `courses` c ON t.course_id = c.id
             LEFT JOIN `branches` b ON t.branch_id = b.id
             ORDER BY t.sort_order ASC, t.created_at DESC'
        )->fetchAll() ?: [];

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

        $this->adminView('toppers', [
            'title'       => 'Edit Topper',
            'currentPage' => 'toppers',
            'toppers'     => $toppers,
            'courses'     => $courses,
            'branches'    => $branches,
            'editTopper'  => $editTopper,
            'showForm'    => true,
        ]);
    }

    /**
     * Store a new topper.
     */
    public function store(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $name      = sanitize($_POST['name'] ?? '');
        $courseId  = (int) ($_POST['course_id'] ?? 0);
        $marks     = sanitize($_POST['marks'] ?? '');
        $grade     = sanitize($_POST['grade'] ?? '');
        $batchYear = sanitize($_POST['batch_year'] ?? '');
        $branchId  = (int) ($_POST['branch_id'] ?? 0);
        $sortOrder = (int) ($_POST['sort_order'] ?? 0);
        // Default active=1 so toppers show on website immediately
        $active    = isset($_POST['active']) ? 1 : 1;

        if (empty($name) || $courseId <= 0) {
            flash('error', 'Student name and course are required.');
            redirect(BASE_PATH . '/admin/toppers');
        }

        // Handle optional photo upload
        $photoPath = $this->handleImageUpload('photo', 'toppers');

        try {
            $stmt = $this->db->prepare(
                'INSERT INTO `toppers` (`name`, `course_id`, `marks`, `grade`, `photo`, `batch_year`, `branch_id`, `sort_order`, `active`)
                 VALUES (:name, :course_id, :marks, :grade, :photo, :batch_year, :branch_id, :sort_order, :active)'
            );

            $stmt->execute([
                ':name'       => $name,
                ':course_id'  => $courseId,
                ':marks'      => $marks,
                ':grade'      => $grade,
                ':photo'      => $photoPath,
                ':batch_year' => empty($batchYear) ? null : $batchYear,
                ':branch_id'  => $branchId > 0 ? $branchId : null,
                ':sort_order' => $sortOrder,
                ':active'     => $active,
            ]);

            flash('success', 'Topper added successfully.');
        } catch (\Throwable $e) {
            error_log('Topper create error: ' . $e->getMessage());
            if ($photoPath !== null) {
                $this->deleteImageFile($photoPath);
            }
            flash('error', 'Failed to add topper: ' . $e->getMessage());
        }

        redirect(BASE_PATH . '/admin/toppers');
    }

    /**
     * Update an existing topper.
     */
    public function update(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

        $stmt = $this->db->prepare('SELECT * FROM `toppers` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $topper = $stmt->fetch() ?: null;

        if ($topper === null) {
            flash('error', 'Topper not found.');
            redirect(BASE_PATH . '/admin/toppers');
        }

        $name      = sanitize($_POST['name'] ?? '');
        $courseId  = (int) ($_POST['course_id'] ?? 0);
        $marks     = sanitize($_POST['marks'] ?? '');
        $grade     = sanitize($_POST['grade'] ?? '');
        $batchYear = sanitize($_POST['batch_year'] ?? '');
        $branchId  = (int) ($_POST['branch_id'] ?? 0);
        $sortOrder = (int) ($_POST['sort_order'] ?? 0);
        // Default active=1 so toppers show on website immediately
        $active    = isset($_POST['active']) ? 1 : 1;

        if (empty($name) || $courseId <= 0) {
            flash('error', 'Student name and course are required.');
            redirect(BASE_PATH . '/admin/toppers/' . $id . '/edit');
        }

        // Handle optional photo replacement
        $photoPath = $this->handleImageUpload('photo', 'toppers');
        if ($photoPath !== null) {
            $this->deleteImageFile($topper['photo'] ?? null);
        } else {
            $photoPath = $topper['photo'];
        }

        $stmt = $this->db->prepare(
            'UPDATE `toppers` SET `name` = :name, `course_id` = :course_id, `marks` = :marks,
             `grade` = :grade, `photo` = :photo, `batch_year` = :batch_year,
             `branch_id` = :branch_id, `sort_order` = :sort_order, `active` = :active
             WHERE `id` = :id'
        );

        $stmt->execute([
            ':name'       => $name,
            ':course_id'  => $courseId,
            ':marks'      => $marks,
            ':grade'      => $grade,
            ':photo'      => $photoPath,
            ':batch_year' => empty($batchYear) ? null : $batchYear,
            ':branch_id'  => $branchId > 0 ? $branchId : null,
            ':sort_order' => $sortOrder,
            ':active'     => $active,
            ':id'         => $id,
        ]);

        flash('success', 'Topper updated successfully.');
        redirect(BASE_PATH . '/admin/toppers');
    }

    /**
     * Toggle the active status of a topper.
     */
    public function toggle(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

        $stmt = $this->db->prepare('SELECT `active` FROM `toppers` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $item = $stmt->fetch() ?: null;

        if ($item === null) {
            flash('error', 'Topper not found.');
            redirect(BASE_PATH . '/admin/toppers');
        }

        $newStatus = ($item['active'] ?? 0) == 1 ? 0 : 1;

        $stmt = $this->db->prepare('UPDATE `toppers` SET `active` = :active WHERE `id` = :id');
        $stmt->execute([':active' => $newStatus, ':id' => $id]);

        flash('success', $newStatus ? 'Topper activated.' : 'Topper deactivated.');
        redirect(BASE_PATH . '/admin/toppers');
    }

    /**
     * Delete a topper.
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

        $stmt = $this->db->prepare('SELECT * FROM `toppers` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $topper = $stmt->fetch() ?: null;

        if ($topper !== null) {
            $this->deleteImageFile($topper['photo'] ?? null);
        }

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

        if ($stmt->rowCount() > 0) {
            flash('success', 'Topper deleted successfully.');
        } else {
            flash('warning', 'Topper not found or already deleted.');
        }
        redirect(BASE_PATH . '/admin/toppers');
    }
}
