<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ClassSectionModel;
use App\Models\CompetitionClassWinnerModel;
use App\Models\CompetitionModel;
use App\Models\CompetitionWinnerModel;

class WinnersController extends BaseController
{
    public function competitionIndex()
    {
        $competitionModel = new CompetitionModel();
        $schoolYear = $this->currentSchoolYearName();

        if ($schoolYear !== '') {
            $competitionModel->where('school_year', $schoolYear);
        }

        $competitions = $competitionModel
            ->where('is_published', 1)
            ->orderBy('published_at', 'DESC')
            ->findAll();

        return view('winners/competitions/index', [
            'competitions' => $competitions,
            'schoolYear'   => $schoolYear,
        ]);
    }

    public function competitionShow($id)
    {
        $competitionModel = new CompetitionModel();
        $winnerModel      = new CompetitionWinnerModel();
        $classSectionModel = new ClassSectionModel();
        $classWinnerModel = new CompetitionClassWinnerModel();

        $schoolYear = $this->currentSchoolYearName();

        $competitionModel->where('is_published', 1);
        if ($schoolYear !== '') {
            $competitionModel->where('school_year', $schoolYear);
        }

        $competition = $competitionModel->find($id);
        if (!$competition) {
            return redirect()->to('/winners/competitions');
        }

        $winners = $winnerModel
            ->select('competition_winners.*, s.firstname, s.lastname, cs.class_section_name')
            ->join('students s', 's.id = competition_winners.student_id', 'left')
            ->join('classSection cs', 'cs.class_section_id = competition_winners.class_section_id', 'left')
            ->where('competition_id', $id)
            ->orderBy('competition_winners.class_section_id', 'ASC')
            ->orderBy('rank', 'ASC')
            ->findAll();

        $sectionMap = [];
        $classSections = $classSectionModel
            ->select('class_section_id, class_section_name')
            ->findAll();
        foreach ($classSections as $section) {
            $sid = (int) ($section['class_section_id'] ?? 0);
            if ($sid > 0) {
                $sectionMap[$sid] = $section['class_section_name'] ?? (string) $sid;
            }
        }

        $winnersByClass = [];
        foreach ($winners as $w) {
            $classId = (int) ($w['class_section_id'] ?? 0);
            $name = trim(($w['firstname'] ?? '') . ' ' . ($w['lastname'] ?? ''));
            $w['name'] = $name !== '' ? $name : ('Student #' . $w['student_id']);
            $winnersByClass[$classId][] = $w;
        }

        $questionCounts = [];
        $qRows = $classWinnerModel
            ->select('class_section_id, question_count')
            ->where('competition_id', $id)
            ->findAll();
        foreach ($qRows as $row) {
            $classId = (int) ($row['class_section_id'] ?? 0);
            if ($classId > 0 && $row['question_count'] !== null) {
                $questionCounts[$classId] = (int) $row['question_count'];
            }
        }

        return view('winners/competitions/show', [
            'competition'    => $competition,
            'winnersByClass' => $winnersByClass,
            'sectionMap'     => $sectionMap,
            'questionCounts' => $questionCounts,
            'schoolYear'     => $schoolYear,
        ]);
    }
}
