<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\BkAssignmentModel;
use App\Models\TeacherModel;
use App\Models\ClassroomModel;
use App\Models\AcademicPeriodModel;
use App\Models\GradeModel;

class BkAssignment extends BaseController
{
    protected $bkModel;
    protected $teacherModel;
    protected $classroomModel;
    protected $periodModel;
    protected $gradeModel;

    public function __construct()
    {
        $this->bkModel       = new BkAssignmentModel();
        $this->teacherModel  = new TeacherModel();
        $this->classroomModel = new ClassroomModel();
        $this->periodModel   = new AcademicPeriodModel();
        $this->gradeModel    = new GradeModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin'])) {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak!');
        }
        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 akademik aktif!');
        }

        // Ambil semua guru aktif
        $teachers = $this->teacherModel->where('is_active', 1)
                                        ->orderBy('name', 'ASC')
                                        ->findAll();
        
        // Ambil semua kelas beserta tingkatnya
        $classrooms = $this->classroomModel->getAllWithRelations();
        
        // Group kelas berdasarkan tingkat
        $groupedClassrooms = [];
        foreach ($classrooms as $c) {
            $gradeName = $c['grade_name'];
            if (!isset($groupedClassrooms[$gradeName])) {
                $groupedClassrooms[$gradeName] = [];
            }
            $groupedClassrooms[$gradeName][] = $c;
        }
        
        // Ambil assignment yang sudah ada
        $assignments = $this->bkModel->getAllWithRelations($activePeriod['id']);
        
        // Map untuk cek kelas sudah diassign siapa
        $assignedMap = [];
        foreach ($assignments as $a) {
            $assignedMap[$a['classroom_id']] = [
                'teacher_id'   => $a['teacher_id'],
                'teacher_name' => $a['teacher_name']
            ];
        }

        $data = [
            'title'              => 'Setting Guru BK',
            'activePeriod'       => $activePeriod,
            'teachers'           => $teachers,
            'groupedClassrooms'  => $groupedClassrooms,
            'assignments'        => $assignments,
            'assignedMap'        => $assignedMap,
            'periods'            => $this->periodModel->getAllWithYear(),
        ];

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

    // AJAX: Ambil assignment per guru
    public function getByTeacher()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacherId = $this->request->getGet('teacher_id');
        $periodId  = $this->request->getGet('period_id');

        if (!$teacherId || !$periodId) {
            return $this->response->setJSON([]);
        }

        $assignments = $this->bkModel->where('teacher_id', $teacherId)
                                      ->where('academic_period_id', $periodId)
                                      ->findAll();
        
        $classroomIds = array_column($assignments, 'classroom_id');
        
        return $this->response->setJSON([
            'classroom_ids' => $classroomIds
        ]);
    }

    // Simpan assignment
    public function save()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacherId   = $this->request->getPost('teacher_id');
        $classroomIds = $this->request->getPost('classroom_ids') ?? [];
        $periodId    = $this->request->getPost('academic_period_id');

        if (!$teacherId) {
            return redirect()->back()
                ->with('error', 'Pilih guru terlebih dahulu!');
        }

        $teacher = $this->teacherModel->find($teacherId);
        if (!$teacher) {
            return redirect()->back()
                ->with('error', 'Guru tidak ditemukan!');
        }

        $success = $this->bkModel->saveAssignments($teacherId, $classroomIds, $periodId);

        return redirect()->to('/bk-assignment')
            ->with('success', "Berhasil menyimpan {$success} kelas untuk guru {$teacher['name']}");
    }

    // Hapus assignment
    public function delete($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $this->bkModel->delete($id);

        return redirect()->to('/bk-assignment')
            ->with('success', 'Assignment berhasil dihapus!');
    }
}