<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ScheduleLoadModel;

class ScheduleLoad extends BaseController
{
    protected ScheduleLoadModel $model;
    protected \CodeIgniter\Database\BaseConnection $db;

    public function __construct()
    {
        $this->model = new ScheduleLoadModel();
        $this->db    = \Config\Database::connect();
    }

    private function getActivePeriod(): array
    {
        $year   = $this->db->table('academic_years')->where('is_active', 1)->get()->getRowArray();
        $period = $this->db->table('academic_periods')->where('is_active', 1)->get()->getRowArray();
        return [$year, $period];
    }

    // ----------------------------------------------------------
    // INDEX — dengan group checkbox per grade
    // ----------------------------------------------------------
    public function index(): string
    {
        [$year, $period] = $this->getActivePeriod();
        
        // Avatar colors untuk tampilan guru
        $avatarColors = [
            ['bg'=>'#E6F1FB','color'=>'#0C447C'],
            ['bg'=>'#EEEDFE','color'=>'#3C3489'],
            ['bg'=>'#E1F5EE','color'=>'#085041'],
            ['bg'=>'#FAEEDA','color'=>'#633806'],
            ['bg'=>'#FBEAF0','color'=>'#72243E'],
            ['bg'=>'#EAF3DE','color'=>'#27500A'],
            ['bg'=>'#FAECE7','color'=>'#712B13'],
        ];
        
        $subjects = $this->db->table('school_subjects')
            ->select('id, name, code')
            ->where('is_active', 1)
            ->orderBy('sort_order', 'ASC')
            ->orderBy('name', 'ASC')
            ->get()->getResultArray();
        
        // Ambil target jam per mapel
        $subjectTargets = [];
        $targets = $this->db->table('subject_target_hours')
            ->select('subject_id, grade_id, target_hours')
            ->get()
            ->getResultArray();
        
        foreach ($targets as $t) {
            $subjectTargets[$t['subject_id']][$t['grade_id']] = $t['target_hours'];
        }
        
        // Ambil kelas yang dikelompokkan per grade
        $classroomsByGrade = $this->db->table('classrooms c')
            ->select('c.id, c.name, g.id as grade_id, g.name as grade_name, g.order as grade_order, m.name as major_name')
            ->join('grades g', 'g.id = c.grade_id', 'left')
            ->join('majors m', 'm.id = c.major_id', 'left')
            ->where('c.deleted_at', null)
            ->orderBy('g.order', 'ASC')
            ->orderBy('g.name', 'ASC')
            ->orderBy('c.name', 'ASC')
            ->get()->getResultArray();
        
        $groupedClassrooms = [];
        foreach ($classroomsByGrade as $class) {
            $gradeId = $class['grade_id'] ?? 0;
            if (!isset($groupedClassrooms[$gradeId])) {
                $groupedClassrooms[$gradeId] = [
                    'grade_id' => $gradeId,
                    'grade_name' => $class['grade_name'] ?? 'Tanpa Kelas',
                    'grade_order' => $class['grade_order'] ?? 999,
                    'classrooms' => [],
                ];
            }
            $groupedClassrooms[$gradeId]['classrooms'][] = $class;
        }
        usort($groupedClassrooms, fn($a, $b) => $a['grade_order'] <=> $b['grade_order']);
        
        // Data beban yang sudah ada
        $teachers = $this->db->table('teachers')
            ->select('id, name, nip')
            ->orderBy('name')
            ->get()->getResultArray();
        
        $loadsByTeacher = [];
        if ($year && $period) {
            $loads = $this->model->getWithRelations($year['id'], $period['id']);
            foreach ($loads as $load) {
                $loadsByTeacher[$load['teacher_id']][] = $load;
            }
        }
        
        return view('schedule_load/index', [
            'title'              => 'Beban Mengajar',
            'year'               => $year,
            'period'             => $period,
            'teachers'           => $teachers,
            'loadsByTeacher'     => $loadsByTeacher,
            'subjects'           => $subjects,
            'groupedClassrooms'  => $groupedClassrooms,
            'avatarColors'       => $avatarColors,        // ← TAMBAHKAN
            'subjectTargets'     => $subjectTargets,      // ← TAMBAHKAN
        ]);
    }

    // ----------------------------------------------------------
    // STORE — support multi kelas dengan split_config
    // ----------------------------------------------------------
    public function store()
    {
        [$year, $period] = $this->getActivePeriod();

        if (!$year || !$period) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => 'Tidak ada tahun ajaran atau periode aktif.']);
            }
            return redirect()->back()->with('error', 'Tidak ada tahun ajaran atau periode aktif.');
        }

        $rules = [
            'teacher_id'        => 'required|integer',
            'school_subject_id' => 'required|integer',
            'classroom_ids'     => 'required',
            'hours_per_week'    => 'required|integer|greater_than[0]|less_than[20]',
        ];

        if (!$this->validate($rules)) {
            $errors = implode('<br>', $this->validator->getErrors());
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $errors]);
            }
            return redirect()->back()->withInput()->with('error', $errors);
        }

        $teacherId    = (int)$this->request->getPost('teacher_id');
        $subjectId    = (int)$this->request->getPost('school_subject_id');
        $classroomIds = $this->request->getPost('classroom_ids') ?? [];
        $hoursPerWeek = (int)$this->request->getPost('hours_per_week');
        $splitConfig  = trim($this->request->getPost('split_config') ?? '');
        $splitOrder   = (int)$this->request->getPost('split_order') ?? 0;
        $notes        = $this->request->getPost('notes');

        // Validasi split_config
        $validation = $this->model->validateSplitConfig($hoursPerWeek, $splitConfig);
        if (!$validation['valid']) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $validation['message']]);
            }
            return redirect()->back()->withInput()->with('error', $validation['message']);
        }

        // Simpan split_config yang sudah divalidasi
        $validSplitConfig = implode(',', $validation['blocks']);

        $inserted = 0;
        $skipped  = 0;

        foreach ($classroomIds as $classroomId) {
            $classroomId = (int)$classroomId;
            if ($this->model->isDuplicate($teacherId, $subjectId, $classroomId, $year['id'], $period['id'])) {
                $skipped++;
                continue;
            }
            $this->model->insert([
                'academic_year_id'    => $year['id'],
                'academic_period_id'  => $period['id'],
                'teacher_id'          => $teacherId,
                'school_subject_id'   => $subjectId,
                'classroom_id'        => $classroomId,
                'hours_per_week'      => $hoursPerWeek,
                'split_config'        => $validSplitConfig,
                'split_order'         => $splitOrder,
                'notes'               => $notes,
            ]);
            $inserted++;
        }

        $message = "{$inserted} entri beban mengajar berhasil ditambahkan.";
        if ($skipped > 0) $message .= " {$skipped} entri dilewati (sudah ada).";

        if ($this->request->isAJAX()) {
            return $this->response->setJSON([
                'success'    => true,
                'message'    => $message,
                'inserted'   => $inserted,
                'skipped'    => $skipped,
                'csrf_token' => csrf_hash()
            ]);
        }

        return redirect()->to('/schedule-load')->with('success', $message);
    }

    // ----------------------------------------------------------
    // UPDATE
    // ----------------------------------------------------------
    public function update(int $id)
    {
        $load = $this->model->find($id);
        if (!$load) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => 'Data tidak ditemukan.']);
            }
            return redirect()->to('/schedule-load')->with('error', 'Data tidak ditemukan.');
        }

        $rules = [
            'hours_per_week' => 'required|integer|greater_than[0]|less_than[20]',
        ];

        if (!$this->validate($rules)) {
            $errors = implode('<br>', $this->validator->getErrors());
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $errors]);
            }
            return redirect()->back()->withInput()->with('error', $errors);
        }

        $hoursPerWeek = (int)$this->request->getPost('hours_per_week');
        $splitConfig  = trim($this->request->getPost('split_config') ?? '');
        $splitOrder   = (int)$this->request->getPost('split_order') ?? 0;
        $notes        = $this->request->getPost('notes');

        // Validasi split_config
        $validation = $this->model->validateSplitConfig($hoursPerWeek, $splitConfig);
        if (!$validation['valid']) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => $validation['message']]);
            }
            return redirect()->back()->withInput()->with('error', $validation['message']);
        }

        $validSplitConfig = implode(',', $validation['blocks']);

        $this->model->update($id, [
            'hours_per_week' => $hoursPerWeek,
            'split_config'   => $validSplitConfig,
            'split_order'    => $splitOrder,
            'notes'          => $notes,
        ]);

        if ($this->request->isAJAX()) {
            return $this->response->setJSON([
                'success'    => true,
                'message'    => 'Beban mengajar berhasil diperbarui.',
                'csrf_token' => csrf_hash()
            ]);
        }

        return redirect()->to('/schedule-load')->with('success', 'Beban mengajar berhasil diperbarui.');
    }

    // ----------------------------------------------------------
    // DELETE satu
    // ----------------------------------------------------------
    public function delete(int $id)
    {
        $load = $this->model->find($id);
        if (!$load) {
            return redirect()->to('/schedule-load')->with('error', 'Data tidak ditemukan.');
        }

        // Clean up teaching assignments if local source
        $db = \Config\Database::connect();
        $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
        $scheduleSource = $sourceRow['setting_value'] ?? 'local';
        if ($scheduleSource === 'local' || $scheduleSource === 'manual') {
            $db->table('teaching_assignments')
                ->where('classroom_id', $load['classroom_id'])
                ->where('subject_id', $load['school_subject_id'])
                ->where('teacher_id', $load['teacher_id'])
                ->where('academic_period_id', $load['academic_period_id'])
                ->delete();
        }

        $this->model->delete($id);
        return redirect()->to('/schedule-load')->with('success', 'Beban mengajar berhasil dihapus.');
    }

    // ----------------------------------------------------------
    // DELETE ALL — hapus semua beban periode aktif
    // ----------------------------------------------------------
    public function deleteAll()
    {
        [$year, $period] = $this->getActivePeriod();
        
        if (!$year || !$period) {
            return redirect()->to('/schedule-load')->with('error', 'Tidak ada tahun ajaran atau periode aktif.');
        }

        $count = $this->model->where('academic_year_id', $year['id'])
                             ->where('academic_period_id', $period['id'])
                             ->countAllResults();

        if ($count === 0) {
            return redirect()->to('/schedule-load')->with('warning', 'Tidak ada beban mengajar untuk periode ini.');
        }

        // Clean up teaching assignments if local source
        $db = \Config\Database::connect();
        $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
        $scheduleSource = $sourceRow['setting_value'] ?? 'local';
        if ($scheduleSource === 'local' || $scheduleSource === 'manual') {
            $db->table('teaching_assignments')
                ->where('academic_period_id', $period['id'])
                ->delete();
        }

        $this->model->deleteAllByPeriod($year['id'], $period['id']);

        return redirect()->to('/schedule-load')->with('success', "{$count} entri beban mengajar berhasil dihapus semua.");
    }

    // ----------------------------------------------------------
    // DELETE ALL BY TEACHER — hapus semua beban untuk satu guru
    // ----------------------------------------------------------
    public function deleteAllByTeacher(int $teacherId)
    {
        if (!$this->request->isAJAX()) {
            return redirect()->to('/schedule-load');
        }
        
        [$year, $period] = $this->getActivePeriod();
        
        if (!$year || !$period) {
            return $this->response->setJSON([
                'success' => false, 
                'message' => 'Tidak ada tahun ajaran atau periode aktif.',
                'csrf_token' => csrf_hash()
            ]);
        }
        
        $count = $this->model->where('academic_year_id', $year['id'])
                             ->where('academic_period_id', $period['id'])
                             ->where('teacher_id', $teacherId)
                             ->countAllResults();
        
        if ($count === 0) {
            return $this->response->setJSON([
                'success' => false, 
                'message' => 'Tidak ada beban mengajar untuk guru ini.',
                'csrf_token' => csrf_hash()
            ]);
        }

        // Clean up teaching assignments if local source
        $db = \Config\Database::connect();
        $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
        $scheduleSource = $sourceRow['setting_value'] ?? 'local';
        if ($scheduleSource === 'local' || $scheduleSource === 'manual') {
            $db->table('teaching_assignments')
                ->where('teacher_id', $teacherId)
                ->where('academic_period_id', $period['id'])
                ->delete();
        }
        
        $this->model->deleteAllByTeacher($year['id'], $period['id'], $teacherId);
        
        return $this->response->setJSON([
            'success' => true, 
            'message' => "{$count} entri beban mengajar untuk guru ini berhasil dihapus semua.",
            'count' => $count,
            'csrf_token' => csrf_hash()
        ]);
    }

    // ----------------------------------------------------------
    // DELETE AJAX
    // ----------------------------------------------------------
    public function deleteAjax(int $id)
    {
        if (!$this->request->isAJAX()) {
            return $this->response->setJSON(['success' => false, 'message' => 'Invalid request']);
        }
        
        $load = $this->model->find($id);
        if (!$load) {
            return $this->response->setJSON(['success' => false, 'message' => 'Data tidak ditemukan.']);
        }

        // Clean up teaching assignments if local source
        $db = \Config\Database::connect();
        $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
        $scheduleSource = $sourceRow['setting_value'] ?? 'local';
        if ($scheduleSource === 'local' || $scheduleSource === 'manual') {
            $db->table('teaching_assignments')
                ->where('classroom_id', $load['classroom_id'])
                ->where('subject_id', $load['school_subject_id'])
                ->where('teacher_id', $load['teacher_id'])
                ->where('academic_period_id', $load['academic_period_id'])
                ->delete();
        }

        $this->model->delete($id);
        return $this->response->setJSON([
            'success' => true, 
            'message' => 'Beban mengajar berhasil dihapus.',
            'csrf_token' => csrf_hash()
        ]);
    }

    // ----------------------------------------------------------
    // DELETE BULK (AJAX)
    // ----------------------------------------------------------
    public function deleteBulk()
    {
        if (!$this->request->isAJAX()) {
            return $this->response->setJSON(['success' => false, 'message' => 'Invalid request']);
        }

        $json = $this->request->getJSON(true);
        $ids = $json['ids'] ?? [];

        if (empty($ids)) {
            return $this->response->setJSON([
                'success' => false,
                'message' => 'Tidak ada beban mengajar yang dipilih.',
                'csrf_token' => csrf_hash()
            ]);
        }

        // Fetch them first to clean up teaching assignments
        $db = \Config\Database::connect();
        $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
        $scheduleSource = $sourceRow['setting_value'] ?? 'local';

        $loads = $this->model->whereIn('id', $ids)->findAll();

        if ($scheduleSource === 'local' || $scheduleSource === 'manual') {
            foreach ($loads as $load) {
                $db->table('teaching_assignments')
                    ->where('classroom_id', $load['classroom_id'])
                    ->where('subject_id', $load['school_subject_id'])
                    ->where('teacher_id', $load['teacher_id'])
                    ->where('academic_period_id', $load['academic_period_id'])
                    ->delete();
            }
        }

        $this->model->whereIn('id', $ids)->delete();

        return $this->response->setJSON([
            'success' => true,
            'message' => count($ids) . ' beban mengajar berhasil dihapus.',
            'csrf_token' => csrf_hash()
        ]);
    }

    // ----------------------------------------------------------
    // GET SUBJECTS BY TEACHER (AJAX)
    // ----------------------------------------------------------
    public function getSubjectsByTeacher()
    {
        if (!$this->request->isAJAX()) {
            return $this->response->setJSON([]);
        }

        $teacherId = (int)$this->request->getGet('teacher_id');
        
        $subjects = $this->db->table('teaching_assignments ta')
            ->select('ss.id, ss.name, ss.code')
            ->join('school_subjects ss', 'ss.id = ta.subject_id')
            ->where('ta.teacher_id', $teacherId)
            ->where('ss.is_active', 1)
            ->groupBy('ss.id')
            ->orderBy('ss.name')
            ->get()
            ->getResultArray();

        return $this->response->setJSON($subjects);
    }

    // ----------------------------------------------------------
    // GET SUGGEST SPLIT (AJAX) — untuk tombol saran otomatis
    // ----------------------------------------------------------
    public function getSuggestSplit()
    {
        if (!$this->request->isAJAX()) {
            return $this->response->setJSON(['success' => false]);
        }

        $totalJam = (int)$this->request->getGet('total_jam');
        if ($totalJam <= 0) {
            return $this->response->setJSON(['success' => false]);
        }

        $suggests = [];
        if ($totalJam <= 3) {
            $suggests[] = (string)$totalJam;
        } else if ($totalJam === 4) {
            $suggests = ['2,2', '3,1', '4'];
        } else if ($totalJam === 5) {
            $suggests = ['3,2', '2,2,1', '5'];
        } else if ($totalJam === 6) {
            $suggests = ['3,3', '2,2,2', '4,2'];
        } else if ($totalJam === 7) {
            $suggests = ['3,2,2', '3,3,1', '3,4'];
        } else if ($totalJam === 8) {
            $suggests = ['3,3,2', '4,4', '3,3,1,1'];
        } else if ($totalJam === 9) {
            $suggests = ['3,3,3', '3,3,2,1'];
        } else {
            $default = $this->model->suggestSplit($totalJam);
            $suggests = [$default, (string)$totalJam];
        }
        
        return $this->response->setJSON([
            'success' => true,
            'split' => $suggests
        ]);
    }

    // ------------------------------------------------------------------
// GET TARGET INFO (untuk ditampilkan di form)
// ------------------------------------------------------------------
public function getTargetInfo(int $subjectId)
{
    if (!$this->request->isAJAX()) {
        return $this->response->setJSON(['success' => false]);
    }
 
    // Target per grade dari tabel subject_target_hours
    $targets = $this->db->table('subject_target_hours')
        ->select('grade_id, target_hours')
        ->where('subject_id', $subjectId)
        ->get()
        ->getResultArray();
 
    $targetMap = []; // [grade_id => target_hours]
    foreach ($targets as $t) {
        $targetMap[$t['grade_id']] = (int)$t['target_hours'];
    }
 
    [$year, $period] = $this->getActivePeriod();
    if (!$year || !$period) {
        return $this->response->setJSON([
            'success'       => true,
            'vii'           => $targetMap[1] ?? 0,
            'viii'          => $targetMap[2] ?? 0,
            'ix'            => $targetMap[3] ?? 0,
            'filled_by_grade' => [],
        ]);
    }
 
    // Hitung jam yang sudah terisi + daftar guru per grade
    // JOIN classrooms → grades untuk tahu grade_id tiap kelas
    $loads = $this->db->table('schedule_loads sl')
        ->select('sl.hours_per_week, sl.teacher_id, c.grade_id, t.name as teacher_name, c.name as classroom_name')
        ->join('classrooms c', 'c.id = sl.classroom_id')
        ->join('teachers t',   't.id = sl.teacher_id')
        ->where('sl.school_subject_id', $subjectId)
        ->where('sl.academic_year_id',  $year['id'])
        ->where('sl.academic_period_id', $period['id'])
        ->get()
        ->getResultArray();
 
    $filledByGrade = []; // [grade_id => ['filled' => int, 'teachers' => [name,...]]]
    foreach ($loads as $load) {
        $gid = $load['grade_id'];
        if (!isset($filledByGrade[$gid])) {
            $filledByGrade[$gid] = ['filled' => 0, 'teachers' => []];
        }
        $filledByGrade[$gid]['filled'] += (int)$load['hours_per_week'];
        // Tambah nama guru jika belum ada
        $label = $load['teacher_name'] . ' (' . $load['classroom_name'] . ')';
        if (!in_array($label, $filledByGrade[$gid]['teachers'])) {
            $filledByGrade[$gid]['teachers'][] = $label;
        }
    }
 
    return $this->response->setJSON([
        'success'         => true,
        'vii'             => $targetMap[1] ?? 0,
        'viii'            => $targetMap[2] ?? 0,
        'ix'              => $targetMap[3] ?? 0,
        'filled_by_grade' => $filledByGrade,
    ]);
}

// ------------------------------------------------------------------
// VALIDATE TARGET (cek sebelum menyimpan)
// ------------------------------------------------------------------
public function validateTarget()
{
    if (!$this->request->isAJAX()) {
        return $this->response->setJSON(['success' => false, 'valid' => true]);
    }
    
    $json = $this->request->getJSON(true);
    $subjectId = (int)$json['subject_id'];
    $gradeId = (int)$json['grade_id'];
    $hours = (int)$json['hours'];
    $teacherId = (int)$json['teacher_id'];
    
    // Ambil target dari master
    $target = $this->db->table('subject_target_hours')
        ->where('subject_id', $subjectId)
        ->where('grade_id', $gradeId)
        ->get()
        ->getRowArray();
    
    if (!$target) {
        return $this->response->setJSON(['valid' => true]);
    }
    
    // Hitung jam yang sudah terisi
    $filled = $this->db->table('schedule_loads sl')
        ->select('SUM(sl.hours_per_week) as total')
        ->join('classrooms c', 'c.id = sl.classroom_id')
        ->where('sl.school_subject_id', $subjectId)
        ->where('c.grade_id', $gradeId)
        ->where('sl.academic_year_id', $this->getActiveYearId())
        ->where('sl.academic_period_id', $this->getActivePeriodId())
        ->get()
        ->getRowArray();
    
    $totalFilled = (int)($filled['total'] ?? 0);
    
    if ($totalFilled + $hours > $target['target_hours']) {
        // Ambil nama mapel dan tingkat
        $subject = $this->db->table('school_subjects')->where('id', $subjectId)->get()->getRowArray();
        $grade = $this->db->table('grades')->where('id', $gradeId)->get()->getRowArray();
        
        // Ambil daftar guru yang sudah mengajar
        $teachers = $this->db->table('schedule_loads sl')
            ->select('t.name as teacher_name, c.name as classroom_name, sl.hours_per_week')
            ->join('teachers t', 't.id = sl.teacher_id')
            ->join('classrooms c', 'c.id = sl.classroom_id')
            ->where('sl.school_subject_id', $subjectId)
            ->where('c.grade_id', $gradeId)
            ->where('sl.academic_year_id', $this->getActiveYearId())
            ->where('sl.academic_period_id', $this->getActivePeriodId())
            ->get()
            ->getResultArray();
        
        $teacherList = '';
        foreach ($teachers as $t) {
            $teacherList .= "<li>{$t['teacher_name']} - {$t['classroom_name']} ({$t['hours_per_week']} jam)</li>";
        }
        
        return $this->response->setJSON([
            'valid' => false,
            'message' => "
                <strong>⚠️ GAGAL MENAMBAHKAN BEBAN MENGAJAR</strong><br><br>
                <strong>Mapel:</strong> {$subject['name']}<br>
                <strong>Tingkat:</strong> {$grade['name']}<br>
                <strong>Target:</strong> {$target['target_hours']} jam/minggu<br>
                <strong>Sudah terisi:</strong> {$totalFilled} jam/minggu<br>
                <strong>Penambahan:</strong> {$hours} jam<br><br>
                <strong>Daftar guru yang sudah mengajar:</strong><br>
                <ul>{$teacherList}</ul>
                <span class='text-danger'>Total akan menjadi " . ($totalFilled + $hours) . " jam (melebihi target)!</span>
            "
        ]);
    }
    
    return $this->response->setJSON(['valid' => true]);
}

// ------------------------------------------------------------------
// GET REKAP (untuk tab 3)
// ------------------------------------------------------------------
public function getRekap()
{
    if (!$this->request->isAJAX()) {
        return redirect()->to('/schedule-load');
    }
 
    [$year, $period] = $this->getActivePeriod();
    if (!$year || !$period) {
        return $this->response->setJSON(['success' => false, 'message' => 'Tidak ada tahun ajaran atau periode aktif']);
    }
 
    // ── Kapasitas slot KBM per minggu per kelas ──
    $activeSchedule = $this->db->table('schedules')
        ->where('academic_year_id',  $year['id'])
        ->where('academic_period_id', $period['id'])
        ->get()->getRowArray();
 
    $activeDays = $activeSchedule
        ? explode(',', $activeSchedule['active_days'])
        : ['1','2','3','4','5'];
 
    $totalKbmSlots = 0;
    foreach ($activeDays as $day) {
        $totalKbmSlots += $this->db->table('schedule_timeslots')
            ->where('day', (int)$day)
            ->where('slot_type', 'kbm')
            ->where('is_active', 1)
            ->countAllResults();
    }
    $capacityPerClass = $totalKbmSlots;
 
    // ── Semua kelas ──
    $classrooms = $this->db->table('classrooms c')
        ->select('c.id, c.name, g.name as grade_name, g.order as grade_order')
        ->join('grades g', 'g.id = c.grade_id', 'left')
        ->where('c.deleted_at', null)
        ->orderBy('g.order')->orderBy('c.name')
        ->get()->getResultArray();
 
    // ── Hitung jam terisi per kelas ──
    $loads = $this->model
        ->select('classroom_id, hours_per_week')
        ->where('academic_year_id',  $year['id'])
        ->where('academic_period_id', $period['id'])
        ->findAll();
 
    $hoursByClass = [];
    foreach ($loads as $l) {
        $hoursByClass[$l['classroom_id']] = ($hoursByClass[$l['classroom_id']] ?? 0) + (int)$l['hours_per_week'];
    }
 
    $classroomData = [];
    foreach ($classrooms as $cls) {
        $classroomData[] = [
            'id'          => $cls['id'],
            'name'        => $cls['grade_name'] . ' ' . $cls['name'],
            'total_hours' => $hoursByClass[$cls['id']] ?? 0,
            'capacity'    => $capacityPerClass,
        ];
    }
 
    // ── Target belum terpenuhi ──
    $warnings = [];
    $allTargets = $this->db->table('subject_target_hours sth')
        ->select('sth.subject_id, sth.grade_id, sth.target_hours, ss.name as subject_name, g.name as grade_name')
        ->join('school_subjects ss', 'ss.id = sth.subject_id')
        ->join('grades g',           'g.id  = sth.grade_id')
        ->get()->getResultArray();
 
    foreach ($allTargets as $tgt) {
        if ($tgt['target_hours'] == 0) continue;
        $row = $this->db->table('schedule_loads sl')
            ->select('SUM(sl.hours_per_week) as total')
            ->join('classrooms c', 'c.id = sl.classroom_id')
            ->where('sl.school_subject_id', $tgt['subject_id'])
            ->where('c.grade_id',           $tgt['grade_id'])
            ->where('sl.academic_year_id',  $year['id'])
            ->where('sl.academic_period_id', $period['id'])
            ->get()->getRowArray();
 
        $filled = (int)($row['total'] ?? 0);
        if ($filled < $tgt['target_hours']) {
            $warnings[] = [
                'subject' => $tgt['subject_name'],
                'grade'   => $tgt['grade_name'],
                'target'  => $tgt['target_hours'],
                'filled'  => $filled,
            ];
        }
    }
 
    $detail = $this->db->table('schedule_loads sl')
        ->select('sl.id, sl.teacher_id, c.name as classroom_name, g.name as grade_name, g.order as grade_order, ss.name as subject_name, t.name as teacher_name, sl.hours_per_week, sl.split_config')
        ->join('classrooms c',     'c.id = sl.classroom_id')
        ->join('grades g',         'g.id = c.grade_id', 'left')
        ->join('school_subjects ss','ss.id = sl.school_subject_id')
        ->join('teachers t',       't.id = sl.teacher_id')
        ->where('sl.academic_year_id',  $year['id'])
        ->where('sl.academic_period_id', $period['id'])
        ->orderBy('g.order')->orderBy('c.name')->orderBy('ss.name')
        ->get()->getResultArray();
 
    // Tambah label kelas lengkap
    foreach ($detail as &$d) {
        $d['classroom_name'] = $d['grade_name'] . ' ' . $d['classroom_name'];
    }
 
    return $this->response->setJSON([
        'success'              => true,
        'classrooms'           => $classroomData,
        'warnings'             => $warnings,
        'capacity_per_class'   => $capacityPerClass,
        'detail_by_classroom'  => $detail,
    ]);
}

private function getActiveYearId()
{
    $year = $this->db->table('academic_years')->where('is_active', 1)->get()->getRowArray();
    return $year ? $year['id'] : 0;
}

private function getActivePeriodId()
{
    $period = $this->db->table('academic_periods')->where('is_active', 1)->get()->getRowArray();
    return $period ? $period['id'] : 0;
}
// ------------------------------------------------------------------
// SAVE TARGET JTM
// ------------------------------------------------------------------
public function saveTarget()
{
    if (!$this->request->isAJAX()) {
        return $this->response->setJSON(['success' => false]);
    }
    
    $json = $this->request->getJSON(true);
    $subjectId = (int)$json['subject_id'];
    $targets = [
        1 => (int)($json['vii'] ?? 0),
        2 => (int)($json['viii'] ?? 0),
        3 => (int)($json['ix'] ?? 0),
    ];
    
    foreach ($targets as $gradeId => $targetHours) {
        $existing = $this->db->table('subject_target_hours')
            ->where('subject_id', $subjectId)
            ->where('grade_id', $gradeId)
            ->get()
            ->getRowArray();
        
        if ($existing) {
            $this->db->table('subject_target_hours')
                ->where('id', $existing['id'])
                ->update(['target_hours' => $targetHours]);
        } else {
            $this->db->table('subject_target_hours')->insert([
                'subject_id' => $subjectId,
                'grade_id' => $gradeId,
                'target_hours' => $targetHours,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
        }
    }
    
    return $this->response->setJSON(['success' => true]);
}
}