<?php

namespace App\Controllers\Admin;

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

class HomeroomAssignment extends BaseController
{
    protected $homeroomModel;
    protected $teacherModel;
    protected $classroomModel;
    protected $periodModel;
    protected $gradeModel;

    public function __construct()
    {
        $this->homeroomModel = new HomeroomAssignmentModel();
        $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!');
        }

        $selectedPeriodId = $this->request->getGet('period_id') ?: $activePeriod['id'];
        $selectedPeriod = $this->periodModel->select('academic_periods.*, academic_years.name as year_name')
            ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
            ->where('academic_periods.id', $selectedPeriodId)
            ->first();

        if (!$selectedPeriod) {
            $selectedPeriod = $activePeriod;
            $selectedPeriodId = $activePeriod['id'];
        }

        // Ambil semua guru aktif
        $teachers = $this->teacherModel->where('is_active', 1)
                                        ->orderBy('name', 'ASC')
                                        ->findAll();
        
        // Ambil semua kelas beserta tingkatnya
        $classrooms = $this->classroomModel->getAllWithRelations();
        
        // Ambil assignment yang sudah ada untuk periode terpilih
        $assignments = $this->homeroomModel->where('academic_period_id', $selectedPeriodId)->findAll();
        
        // Map classroom_id => teacher_id
        $assignedMap = [];
        foreach ($assignments as $a) {
            $assignedMap[$a['classroom_id']] = $a['teacher_id'];
        }

        $data = [
            'title'            => 'Setting Wali Kelas',
            'activePeriod'     => $activePeriod,
            'selectedPeriod'   => $selectedPeriod,
            'teachers'         => $teachers,
            'classrooms'       => $classrooms,
            'assignedMap'      => $assignedMap,
            'periods'          => $this->periodModel->getAllWithYear(),
        ];

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

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

        $periodId = $this->request->getPost('academic_period_id');
        $waliKelasInput = $this->request->getPost('wali_kelas') ?? []; // Array: [classroom_id => teacher_id]

        if (!$periodId) {
            return redirect()->back()->with('error', 'Periode akademik tidak valid!');
        }

        $db = \Config\Database::connect();
        $db->transStart();

        // Ambil penugasan yang ada saat ini untuk periode ini
        $existing = $this->homeroomModel->where('academic_period_id', $periodId)->findAll();
        $existingMap = [];
        foreach ($existing as $e) {
            $existingMap[$e['classroom_id']] = $e;
        }

        $inserted = 0;
        $updated = 0;
        $deleted = 0;

        foreach ($waliKelasInput as $classroomId => $teacherId) {
            $hasExisting = isset($existingMap[$classroomId]);
            
            if (empty($teacherId)) {
                // Jika kosong, hapus jika ada sebelumnya
                if ($hasExisting) {
                    $this->homeroomModel->delete($existingMap[$classroomId]['id']);
                    $deleted++;
                }
            } else {
                if ($hasExisting) {
                    // Update jika guru berubah
                    if ($existingMap[$classroomId]['teacher_id'] != $teacherId) {
                        $this->homeroomModel->update($existingMap[$classroomId]['id'], [
                            'teacher_id' => $teacherId
                        ]);
                        $updated++;
                    }
                } else {
                    // Insert baru
                    $this->homeroomModel->insert([
                        'classroom_id' => $classroomId,
                        'teacher_id' => $teacherId,
                        'academic_period_id' => $periodId
                    ]);
                    $inserted++;
                }
            }
        }

        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->with('error', 'Gagal menyimpan konfigurasi Wali Kelas.');
        }

        return redirect()->to('/homeroom-assignment?period_id=' . $periodId)
            ->with('success', "Konfigurasi Wali Kelas berhasil disimpan. (Ditambah: {$inserted}, Diperbarui: {$updated}, Dihapus: {$deleted})");
    }
}
