<?php

namespace App\Controllers\Guru;

use App\Controllers\BaseController;
use App\Models\TeacherModel;
use App\Models\TeachingAssignmentModel;
use App\Models\BkAssignmentModel;
use App\Models\AcademicPeriodModel;
use App\Models\StudentAcademicHistoryModel;
use App\Models\ClassroomModel;

class Kelas extends BaseController
{
    protected $teacherModel;
    protected $teachingAssignmentModel;
    protected $bkAssignmentModel;
    protected $periodModel;
    protected $studentHistoryModel;
    protected $classroomModel;

    public function __construct()
    {
        $this->teacherModel           = new TeacherModel();
        $this->teachingAssignmentModel = new TeachingAssignmentModel();
        $this->bkAssignmentModel      = new BkAssignmentModel();
        $this->periodModel            = new AcademicPeriodModel();
        $this->studentHistoryModel    = new StudentAcademicHistoryModel();
        $this->classroomModel         = new ClassroomModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        if (session()->get('user_role') !== 'guru') {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak!');
        }
        return null;
    }

    private function getTeacher()
    {
        return $this->teacherModel->where('user_id', session()->get('user_id'))->first();
    }

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

        $teacher = $this->getTeacher();
        if (!$teacher) {
            return redirect()->to('/dashboard')->with('error', 'Data guru tidak ditemukan!');
        }

        $activePeriod = $this->periodModel->getActive();
        if (!$activePeriod) {
            return view('guru/kelas/index', [
                'title'        => 'Kelas Saya',
                'activePeriod' => null,
                'subjects'     => [],
                'bkClasses'    => [],
            ]);
        }

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

        // === Kelas mengajar — kelompok per mapel ===
        $assignments = $this->teachingAssignmentModel
            ->select('teaching_assignments.classroom_id, teaching_assignments.subject_id,
                      school_subjects.name as subject_name,
                      classrooms.name as classroom_name,
                      grades.name as grade_name, grades.order as grade_order')
            ->join('school_subjects', 'school_subjects.id = teaching_assignments.subject_id')
            ->join('classrooms', 'classrooms.id = teaching_assignments.classroom_id')
            ->join('grades', 'grades.id = classrooms.grade_id')
            ->where('teaching_assignments.teacher_id', $teacher['id'])
            ->where('teaching_assignments.academic_period_id', $activePeriod['id'])
            ->orderBy('grades.order', 'ASC')
            ->orderBy('classrooms.name', 'ASC')
            ->findAll();

        // Kelompokkan per mapel
        $subjects = [];
        foreach ($assignments as $a) {
            $sid = $a['subject_id'];
            if (!isset($subjects[$sid])) {
                $subjects[$sid] = [
                    'subject_id'   => $sid,
                    'subject_name' => $a['subject_name'],
                    'classrooms'   => [],
                ];
            }

            // Hitung jumlah siswa di kelas ini periode ini
            $studentCount = $db->table('student_academic_histories')
                ->where('classroom_id', $a['classroom_id'])
                ->where('academic_period_id', $activePeriod['id'])
                ->countAllResults();

            $subjects[$sid]['classrooms'][] = [
                'classroom_id'   => $a['classroom_id'],
                'classroom_name' => $a['classroom_name'],
                'grade_name'     => $a['grade_name'],
                'student_count'  => $studentCount,
            ];
        }

        // === Kelas BK ===
        $bkAssignments = $this->bkAssignmentModel
            ->select('bk_assignments.classroom_id,
                      classrooms.name as classroom_name,
                      grades.name as grade_name')
            ->join('classrooms', 'classrooms.id = bk_assignments.classroom_id')
            ->join('grades', 'grades.id = classrooms.grade_id')
            ->where('bk_assignments.teacher_id', $teacher['id'])
            ->where('bk_assignments.academic_period_id', $activePeriod['id'])
            ->orderBy('grades.order', 'ASC')
            ->orderBy('classrooms.name', 'ASC')
            ->findAll();

        $bkClasses = [];
        foreach ($bkAssignments as $bk) {
            $studentCount = $db->table('student_academic_histories')
                ->where('classroom_id', $bk['classroom_id'])
                ->where('academic_period_id', $activePeriod['id'])
                ->countAllResults();

            $bkClasses[] = [
                'classroom_id'   => $bk['classroom_id'],
                'classroom_name' => $bk['classroom_name'],
                'grade_name'     => $bk['grade_name'],
                'student_count'  => $studentCount,
            ];
        }

        // === Data Jadwal Guru (Dinamis Lokal vs aSc) ===
        $db = \Config\Database::connect();
        $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
        $scheduleSource = $sourceRow['setting_value'] ?? 'local';

        $scheduleData    = [];
        $scheduleDays    = [];
        $schedulePeriods = [];
        $activeImport    = null;
        $ascTeacher      = null;

        if ($scheduleSource === 'asc') {
            $ascImportModel   = new \App\Models\AscImportModel();
            $ascTeacherModel  = new \App\Models\AscTeacherModel();
            $ascScheduleModel = new \App\Models\AscScheduleModel();

            $activeImport  = $ascImportModel->getActive();
            if ($activeImport) {
                $ascTeacher = $ascTeacherModel->where('import_id', $activeImport['id'])
                                               ->where('teacher_id', $teacher['id'])
                                               ->first();
                if ($ascTeacher) {
                    $scheduleData    = $ascScheduleModel->getByTeacher($activeImport['id'], $ascTeacher['asc_id']);
                    $scheduleDays    = $ascScheduleModel->getDayList($activeImport['id']);
                    $schedulePeriods = $ascScheduleModel->getPeriodList($activeImport['id']);
                }
            }
        } else {
            // Jalur Lokal (Generator Asli Aplikasi)
            $scheduleModel = new \App\Models\ScheduleModel();
            $publishedSchedule = $scheduleModel->where('academic_period_id', $activePeriod['id'])
                                                ->where('status', 'published')
                                                ->where('type', $scheduleSource)
                                                ->first();
            
            if ($publishedSchedule) {
                // Samakan interface $activeImport untuk header info
                $activeImport = [
                    'name' => $publishedSchedule['name']
                ];
                
                // Samakan interface $ascTeacher untuk default color
                $ascTeacher = [
                    'color' => '#3b71ca'
                ];

                // 1. Ambil hari-hari aktif
                $dayNames = ['', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
                $activeDays = array_map('intval', explode(',', $publishedSchedule['active_days']));
                foreach ($activeDays as $dNum) {
                    $scheduleDays[] = [
                        'day_number' => $dNum,
                        'day_name'   => $dayNames[$dNum] ?? ''
                    ];
                }

                // 2. Ambil timeslot KBM (atau semua slot aktif jika jadwal manual)
                $timeslotModel = new \App\Models\ScheduleTimeslotModel();
                $builder = $timeslotModel
                    ->whereIn('day', $activeDays)
                    ->where('is_active', 1);

                if ($publishedSchedule['type'] !== 'manual') {
                    $builder->where('slot_type', 'kbm');
                }

                $timeslotsRaw = $builder->orderBy('slot_number', 'ASC')->findAll();

                // Hitung batas jam kustom
                $customHours = $publishedSchedule['custom_hours'] ? json_decode($publishedSchedule['custom_hours'], true) : [];
                $maxSlotNumber = 0;
                $filteredRaw = [];
                foreach ($timeslotsRaw as $slot) {
                    $day = (int)$slot['day'];
                    $slotNum = (int)$slot['slot_number'];
                    if (isset($customHours[$day])) {
                        if ($slotNum > $customHours[$day]) {
                            continue;
                        }
                    }
                    if ($slotNum > $maxSlotNumber) {
                        $maxSlotNumber = $slotNum;
                    }
                    $filteredRaw[] = $slot;
                }

                $schedulePeriods = [];
                for ($i = 1; $i <= $maxSlotNumber; $i++) {
                    $startTime = '00:00';
                    $endTime = '00:00';
                    foreach ($filteredRaw as $slot) {
                        if ((int)$slot['slot_number'] === $i) {
                            $startTime = $slot['start_time'];
                            $endTime = $slot['end_time'];
                            break;
                        }
                    }
                    $schedulePeriods[] = [
                        'period_number' => $i,
                        'start_time'    => $startTime,
                        'end_time'      => $endTime
                    ];
                }

                // 3. Ambil data dari schedule_entries
                $entries = $db->table('schedule_entries se')
                    ->select([
                        'se.day as day_number',
                        'se.slot_number as period_number',
                        'c.name as class_name',
                        'c.name as display_class_name',
                        'ss.name as subject_name',
                        'ss.name as display_name',
                        'ss.code as subject_code',
                        'ss.code as display_code',
                    ])
                    ->join('classrooms c', 'c.id = se.classroom_id', 'left')
                    ->join('school_subjects ss', 'ss.id = se.school_subject_id', 'left')
                    ->where('se.schedule_id', $publishedSchedule['id'])
                    ->where('se.teacher_id', $teacher['id'])
                    ->get()->getResultArray();

                // Format ke array matrix: [day][period]
                foreach ($entries as $row) {
                    $d = (int)$row['day_number'];
                    $p = (int)$row['period_number'];
                    $scheduleData[$d][$p] = $row;
                }
            }
        }

        return view('guru/kelas/index', [
            'title'           => 'Kelas dan Jadwal Saya',
            'teacher'         => $teacher,
            'activePeriod'    => $activePeriod,
            'subjects'        => array_values($subjects),
            'bkClasses'       => $bkClasses,
            // Dynamic Schedule data
            'activeImport'    => $activeImport,
            'ascTeacher'      => $ascTeacher,
            'scheduleData'    => $scheduleData,
            'scheduleDays'    => $scheduleDays,
            'schedulePeriods' => $schedulePeriods,
            'customHours'     => $customHours ?? [],
        ]);
    }
}