<?php

namespace App\Controllers\Admin;

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

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

    public function __construct()
    {
        $this->studentModel   = new StudentModel();
        $this->historyModel   = new StudentAcademicHistoryModel();
        $this->periodModel    = new AcademicPeriodModel();
        $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! Aktifkan periode terlebih dahulu.');
        }

        $data = [
            'title'        => 'Assign Kelas',
            'activePeriod' => $activePeriod,
            'unassigned'   => $this->getUnassignedStudents($activePeriod['id']),
            'classrooms'   => $this->classroomModel->getAllWithRelations(),
        ];

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

    // AJAX: ambil siswa dalam kelas tertentu
    public function students()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

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

        $students = $this->getStudentsInClassroom($classroomId, $periodId);

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

    // Assign siswa ke kelas
    public function assign()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $studentIds  = $this->request->getPost('student_ids');
        $classroomId = $this->request->getPost('classroom_id');
        $periodId    = $this->request->getPost('period_id');

        if (empty($studentIds) || !$classroomId || !$periodId) {
            return $this->response->setJSON([
                'success'    => false,
                'message'    => 'Data tidak lengkap!',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $success = 0;
        foreach ($studentIds as $studentId) {
            $existing = $this->historyModel
                ->where('student_id', $studentId)
                ->where('academic_period_id', $periodId)
                ->first();

            if (!$existing) {
                $this->historyModel->insert([
                    'student_id'         => $studentId,
                    'academic_period_id' => $periodId,
                    'classroom_id'       => $classroomId,
                    'status'             => 'Aktif',
                ]);
                $success++;
            }
        }

        $classroom = $this->classroomModel->find($classroomId);

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

    // Pindah kelas
    public function move()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $historyId   = $this->request->getPost('history_id');
        $classroomId = $this->request->getPost('classroom_id');

        if (!$historyId || !$classroomId) {
            return $this->response->setJSON([
                'success'    => false,
                'message'    => 'Data tidak lengkap!',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $history = $this->historyModel->find($historyId);
        if (!$history) {
            return $this->response->setJSON([
                'success'    => false,
                'message'    => 'Data tidak ditemukan!',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $this->historyModel->update($historyId, [
            'classroom_id' => $classroomId,
        ]);

        $newClassroom = $this->classroomModel->find($classroomId);
        $student      = $this->studentModel->find($history['student_id']);

        return $this->response->setJSON([
            'success'    => true,
            'message'    => $student['full_name'] . ' berhasil dipindah ke kelas ' . $newClassroom['name'],
            'csrf_token' => csrf_hash(),
        ]);
    }

    // ── Private helpers ──────────────────────────────────────────

    private function getUnassignedStudents($periodId)
    {
        $db = \Config\Database::connect();

        $assignedIds = $db->table('student_academic_histories')
            ->select('student_id')
            ->where('academic_period_id', $periodId)
            ->get()
            ->getResultArray();

        $assignedIds = array_column($assignedIds, 'student_id');

        $builder = $db->table('students')
            ->select('id, nis, full_name, gender')
            ->where('deleted_at', null)
            ->where('status', 'Aktif')
            ->orderBy('full_name', 'ASC');

        if (!empty($assignedIds)) {
            $builder->whereNotIn('id', $assignedIds);
        }

        return $builder->get()->getResultArray();
    }

    private function getStudentsInClassroom($classroomId, $periodId)
    {
        $db = \Config\Database::connect();

        return $db->table('student_academic_histories')
            ->select('student_academic_histories.id as history_id, students.id, students.nis, 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)
            ->orderBy('students.full_name', 'ASC')
            ->get()
            ->getResultArray();
    }
}