<?php

namespace App\Controllers\Admin;

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

class MoveClass extends BaseController
{
    protected $historyModel;
    protected $periodModel;
    protected $classroomModel;
    protected $gradeModel;

    public function __construct()
    {
        $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!');
        }

        $data = [
            'title'        => 'Pindah Kelas',
            'activePeriod' => $activePeriod,
            'grades'       => $this->gradeModel->orderBy('order', 'ASC')->findAll(),
            'classrooms'   => $this->classroomModel->getAllWithRelations(),
        ];

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

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

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

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

        $db = \Config\Database::connect();
        $students = $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')
            ->orderBy('students.full_name', 'ASC')
            ->get()
            ->getResultArray();

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

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

        $historyIds  = $this->request->getPost('history_ids');
        $classroomId = $this->request->getPost('classroom_id');

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

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

        // Get histories of selected students
        $histories = $this->historyModel->whereIn('id', $historyIds)->findAll();
        if (empty($histories)) {
            return $this->response->setJSON([
                'success'    => false,
                'message'    => 'Data siswa tidak ditemukan!',
                'csrf_token' => csrf_hash(),
            ]);
        }

        $count = 0;
        foreach ($historyIds as $historyId) {
            $this->historyModel->update($historyId, [
                'classroom_id' => $classroomId,
            ]);
            $count++;
        }

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