<?php

namespace App\Models;

use CodeIgniter\Model;

class ScheduleValidatorModel extends Model
{
    protected $db;

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

    /**
     * Hitung total slot KBM tersedia untuk schedule tertentu
     */
    public function getTotalSlotsCapacity(int $scheduleId): array
    {
        $schedule = $this->db->table('schedules')
            ->select('active_days')
            ->where('id', $scheduleId)
            ->get()
            ->getRowArray();

        if (!$schedule) {
            return ['total_slots' => 0, 'active_days' => [], 'slots_per_day' => []];
        }

        $activeDays = array_map('intval', explode(',', $schedule['active_days']));
        
        $kbmSlots = $this->db->table('schedule_timeslots')
            ->select('day, COUNT(*) as total')
            ->where('slot_type', 'kbm')
            ->where('is_active', 1)
            ->whereIn('day', $activeDays)
            ->groupBy('day')
            ->get()
            ->getResultArray();

        $slotsPerDay = [];
        foreach ($kbmSlots as $slot) {
            $slotsPerDay[$slot['day']] = (int)$slot['total'];
        }

        $totalClassrooms = $this->db->table('classrooms')
            ->where('deleted_at', null)
            ->countAllResults();

        // HITUNG TOTAL SLOT DENGAN AMAN
        $totalSlots = 0;
        $totalSlotsPerDay = array_sum($slotsPerDay);
        if ($totalSlotsPerDay > 0 && $totalClassrooms > 0) {
            $totalSlots = $totalSlotsPerDay * $totalClassrooms;
        }

        return [
            'total_slots'      => $totalSlots,
            'total_classrooms' => $totalClassrooms,
            'active_days'      => $activeDays,
            'slots_per_day'    => $slotsPerDay,
        ];
    }

    /**
     * Hitung total beban mengajar untuk periode tertentu
     */
    public function getTotalLoad(int $yearId, int $periodId): array
    {
        $loads = $this->db->table('schedule_loads')
            ->select('
                schedule_loads.*,
                teachers.name as teacher_name,
                teachers.nip,
                school_subjects.name as subject_name,
                classrooms.name as classroom_name,
                grades.name as grade_name,
                grades.order as grade_order
            ')
            ->join('teachers', 'teachers.id = schedule_loads.teacher_id')
            ->join('school_subjects', 'school_subjects.id = schedule_loads.school_subject_id')
            ->join('classrooms', 'classrooms.id = schedule_loads.classroom_id')
            ->join('grades', 'grades.id = classrooms.grade_id', 'left')
            ->where('schedule_loads.academic_year_id', $yearId)
            ->where('schedule_loads.academic_period_id', $periodId)
            ->get()
            ->getResultArray();

        $totalHours = 0;
        $perTeacher = [];
        $perClassroom = [];

        foreach ($loads as $load) {
            $hours = (int)$load['hours_per_week'];
            $totalHours += $hours;

            $tid = $load['teacher_id'];
            if (!isset($perTeacher[$tid])) {
                $perTeacher[$tid] = [
                    'teacher_id'   => $tid,
                    'teacher_name' => $load['teacher_name'],
                    'nip'          => $load['nip'],
                    'total_hours'  => 0,
                    'subjects'     => [],
                ];
            }
            $perTeacher[$tid]['total_hours'] += $hours;
            $perTeacher[$tid]['subjects'][] = $load['subject_name'] . ' (' . $hours . ' jam)';

            $cid = $load['classroom_id'];
            $className = $load['grade_name'] . ' ' . $load['classroom_name'];
            if (!isset($perClassroom[$cid])) {
                $perClassroom[$cid] = [
                    'classroom_id'   => $cid,
                    'classroom_name' => $className,
                    'grade_order'    => (int)$load['grade_order'],
                    'total_hours'    => 0,
                ];
            }
            $perClassroom[$cid]['total_hours'] += $hours;
        }

        usort($perClassroom, fn($a, $b) => $a['grade_order'] <=> $b['grade_order']);

        return [
            'total_hours'   => $totalHours,
            'total_loads'   => count($loads),
            'per_teacher'   => array_values($perTeacher),
            'per_classroom' => $perClassroom,
        ];
    }

    /**
     * Cek kelayakan per guru (max jam per hari vs ketersediaan)
     */
    public function getTeacherFeasibility(int $yearId, int $periodId, array $activeDays): array
    {
        $loads = $this->db->table('schedule_loads')
            ->select('
                teacher_id,
                teachers.name as teacher_name,
                teachers.nip,
                SUM(hours_per_week) as total_hours
            ')
            ->join('teachers', 'teachers.id = schedule_loads.teacher_id')
            ->where('academic_year_id', $yearId)
            ->where('academic_period_id', $periodId)
            ->groupBy('teacher_id')
            ->get()
            ->getResultArray();

        $settings = $this->db->table('schedule_teacher_settings')
            ->select('teacher_id, max_hours_per_day')
            ->get()
            ->getResultArray();
        
        $maxHoursMap = [];
        foreach ($settings as $s) {
            $maxHoursMap[$s['teacher_id']] = (int)$s['max_hours_per_day'];
        }

        $totalDays = count($activeDays);
        if ($totalDays == 0) $totalDays = 5;
        
        $results = [];

        foreach ($loads as $load) {
            $tid = $load['teacher_id'];
            $totalHours = (int)$load['total_hours'];
            
            // Ambil max per day dari setting guru, default 6
            $effectiveMaxPerDay = $maxHoursMap[$tid] ?? 6;
            if ($effectiveMaxPerDay <= 0) $effectiveMaxPerDay = 6;
            
            $minDaysNeeded = ceil($totalHours / $effectiveMaxPerDay);
            
            // Estimasi hari tersedia (asumsi semua hari aktif)
            $estimatedAvailableDays = $totalDays;
            
            $isFeasible = $minDaysNeeded <= $estimatedAvailableDays;
            
            $results[] = [
                'teacher_id'            => $tid,
                'teacher_name'          => $load['teacher_name'],
                'nip'                   => $load['nip'],
                'total_hours'           => $totalHours,
                'max_per_day'           => $effectiveMaxPerDay,
                'min_days_needed'       => $minDaysNeeded,
                'available_days'        => $estimatedAvailableDays,
                'is_feasible'           => $isFeasible,
                'warning'               => $isFeasible ? null : "Butuh minimal {$minDaysNeeded} hari, hanya {$estimatedAvailableDays} hari tersedia",
            ];
        }

        return $results;
    }

    public function getImpossibleLoads(int $yearId, int $periodId, array $activeDays): array
    {
        // max_per_day sudah dihapus, method ini tidak diperlukan lagi
        // Tapi tetap return array kosong agar tidak error
        return [];
    }
}