<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\StudentModel;
use App\Models\StudentAcademicHistoryModel;
use App\Models\AcademicPeriodModel;
use App\Models\AcademicYearModel;
use App\Models\ClassroomModel;
use App\Models\GradeModel;

class PromoteClass extends BaseController
{
    protected $studentModel;
    protected $historyModel;
    protected $periodModel;
    protected $yearModel;
    protected $classroomModel;
    protected $gradeModel;

    public function __construct()
    {
        $this->studentModel   = new StudentModel();
        $this->historyModel   = new StudentAcademicHistoryModel();
        $this->periodModel    = new AcademicPeriodModel();
        $this->yearModel      = new AcademicYearModel();
        $this->classroomModel = new ClassroomModel();
        $this->gradeModel     = new GradeModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $activePeriod = $this->periodModel->getActive();

        if (!$activePeriod) {
            return redirect()->to('/dashboard')
                ->with('error', 'Belum ada periode aktif!');
        }

        // Auto-detect tahun ajaran berikutnya dari nama TA aktif
        // Misal: "2025/2026" → cari TA yang dimulai dengan "2026"
        $activeYear = $this->yearModel->getActive();
        $nextYear   = null;
        $nextYearExpected = null;

        if ($activeYear) {
            // Ambil tahun akhir dari nama TA aktif (e.g. "2025/2026" → 2026)
            $parts = explode('/', $activeYear['name']);
            if (count($parts) === 2) {
                $endYear = trim($parts[1]);
                $nextYearExpected = $endYear . '/' . ($endYear + 1);

                // Cari TA berikutnya di DB (yang namanya dimulai dengan tahun itu)
                $allYears = $this->yearModel->where('deleted_at', null)->orderBy('name', 'ASC')->findAll();
                foreach ($allYears as $yr) {
                    if (strpos($yr['name'], $endYear . '/') === 0 && $yr['id'] != $activeYear['id']) {
                        $nextYear = $yr;
                        break;
                    }
                }
            }
        }

        $data = [
            'title'             => 'Kenaikan Kelas',
            'activePeriod'      => $activePeriod,
            'activeYear'        => $activeYear,
            'nextYear'          => $nextYear,           // null jika belum dibuat
            'nextYearExpected'  => $nextYearExpected,   // nama TA yang diharapkan, misal "2026/2027"
            'grades'            => $this->gradeModel->orderBy('order', 'ASC')->findAll(),
            // Kelas asal: dari TA aktif
            'classrooms'        => $this->classroomModel->getAllWithRelations(),
        ];

        return view('promote_class/index', $data);
    }

    // AJAX — ambil siswa di kelas tertentu pada periode aktif
    public function getStudents()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $classroomId  = $this->request->getGet('classroom_id');
        $periodId     = $this->request->getGet('period_id');
        $targetYearId = $this->request->getGet('target_year_id');

        if (!$classroomId || !$periodId) {
            return $this->response->setJSON([
                'success'  => false,
                'students' => [],
            ]);
        }

        $db = \Config\Database::connect();

        // Cari semua periode dalam TA tujuan (jika ada) untuk mengecualikan siswa yang sudah dipromosikan
        $targetPeriodIds = [];
        if ($targetYearId) {
            $periods = $db->table('academic_periods')
                ->select('id')
                ->where('academic_year_id', $targetYearId)
                ->where('deleted_at', null)
                ->get()
                ->getResultArray();
            $targetPeriodIds = array_column($periods, 'id');
        }

        $builder = $db->table('student_academic_histories')
            ->select('
                student_academic_histories.id as history_id,
                students.id,
                students.nis,
                students.nisn,
                students.full_name,
                students.gender
            ')
            ->join('students', 'students.id = student_academic_histories.student_id')
            ->where('student_academic_histories.classroom_id', $classroomId)
            ->where('student_academic_histories.academic_period_id', $periodId)
            ->where('students.deleted_at', null)
            ->where('students.status', 'Aktif');

        if (!empty($targetPeriodIds)) {
            // Subquery untuk mendapatkan ID siswa yang sudah terdaftar di TA tujuan
            $subQuery = $db->table('student_academic_histories')
                ->select('student_id')
                ->whereIn('academic_period_id', $targetPeriodIds);

            $builder->whereNotIn('students.id', $subQuery);
        }

        $students = $builder->orderBy('students.full_name', 'ASC')
            ->get()
            ->getResultArray();

        return $this->response->setJSON([
            'success'  => true,
            'students' => $students,
        ]);
    }

    // AJAX — ambil kelas berdasarkan tahun ajaran tujuan
    public function getClassroomsByYear()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $yearId = $this->request->getGet('year_id');

        if (!$yearId) {
            return $this->response->setJSON([
                'success'    => false,
                'classrooms' => [],
                'has_classrooms' => false,
            ]);
        }

        $classrooms = $this->classroomModel->getAllWithRelations($yearId);

        return $this->response->setJSON([
            'success'        => true,
            'classrooms'     => $classrooms,
            'has_classrooms' => !empty($classrooms),
        ]);
    }

    // AJAX — ambil siswa di kelas tujuan
    public function getTargetStudents()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $classroomId = $this->request->getGet('classroom_id');
        $yearId      = $this->request->getGet('year_id');

        if (!$classroomId || !$yearId) {
            return $this->response->setJSON([
                'success'  => false,
                'students' => [],
            ]);
        }

        // Cari semua periode dalam TA tujuan
        $db = \Config\Database::connect();
        $periodIds = $db->table('academic_periods')
            ->select('id')
            ->where('academic_year_id', $yearId)
            ->where('deleted_at', null)
            ->get()
            ->getResultArray();

        $periodIds = array_column($periodIds, 'id');

        if (empty($periodIds)) {
            return $this->response->setJSON(['success' => true, 'students' => []]);
        }

        $students = $db->table('student_academic_histories')
            ->select('students.nis, students.nisn, students.full_name, students.gender')
            ->join('students', 'students.id = student_academic_histories.student_id')
            ->where('student_academic_histories.classroom_id', $classroomId)
            ->whereIn('student_academic_histories.academic_period_id', $periodIds)
            ->where('students.deleted_at', null)
            ->orderBy('students.full_name', 'ASC')
            ->get()
            ->getResultArray();

        return $this->response->setJSON([
            'success'  => true,
            'students' => $students,
        ]);
    }

    // AJAX — proses naikkan kelas
    public function promote()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $historyIds        = $this->request->getPost('history_ids');
        $targetClassroomId = $this->request->getPost('classroom_id');
        $targetYearId      = $this->request->getPost('target_year_id');

        if (empty($historyIds) || !$targetClassroomId || !$targetYearId) {
            return $this->response->setJSON([
                'success'    => false,
                'message'    => 'Pilih siswa, tahun ajaran tujuan, dan kelas tujuan terlebih dahulu!',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $classroom = $this->classroomModel->find($targetClassroomId);
        if (!$classroom) {
            return $this->response->setJSON([
                'success'    => false,
                'message'    => 'Kelas tujuan tidak ditemukan!',
                'csrf_token' => csrf_hash(),
            ]);
        }

        // Cari periode Semester 1 dari TA tujuan (periode pertama)
        $db = \Config\Database::connect();
        $targetPeriod = $db->table('academic_periods')
            ->where('academic_year_id', $targetYearId)
            ->where('deleted_at', null)
            ->orderBy('semester', 'ASC')   // Semester 1 dulu
            ->orderBy('id', 'ASC')
            ->get()
            ->getRowArray();

        if (!$targetPeriod) {
            return $this->response->setJSON([
                'success'    => false,
                'message'    => 'Tahun ajaran tujuan belum memiliki periode (semester). Buat periode terlebih dahulu!',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $count = 0;
        foreach ($historyIds as $historyId) {
            $history = $this->historyModel->find($historyId);
            if (!$history) continue;

            // Cek apakah siswa sudah ada di periode tujuan
            $existing = $this->historyModel
                ->where('student_id', $history['student_id'])
                ->where('academic_period_id', $targetPeriod['id'])
                ->first();

            if ($existing) continue; // Skip jika sudah ada

            // Insert record baru di periode Sem 1 TA tujuan
            $this->historyModel->insert([
                'student_id'         => $history['student_id'],
                'academic_period_id' => $targetPeriod['id'],
                'classroom_id'       => $targetClassroomId,
                'status'             => 'Aktif',
            ]);

            $count++;
        }

        return $this->response->setJSON([
            'success'    => true,
            'message'    => $count . ' siswa berhasil dinaikkan ke kelas ' . $classroom['name'],
            'csrf_token' => csrf_hash(),
        ]);
    }

}