<?php

namespace App\Models;

use CodeIgniter\Model;

class ScheduleTeacherSettingModel extends Model
{
    protected $table      = 'schedule_teacher_settings';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'teacher_id', 'max_hours_per_day', 'notes',
    ];

    protected $useTimestamps = true;

    // Default global max hours per day (bisa diubah via settings)
    public const DEFAULT_MAX_HOURS = 6;

    // -------------------------------------------------------
    // Ambil setting satu guru
    // -------------------------------------------------------
    public function getByTeacher(int $teacherId): array
    {
        $row = $this->where('teacher_id', $teacherId)->first();
        if (!$row) {
            return [
                'id'                => null,
                'teacher_id'        => $teacherId,
                'max_hours_per_day' => null, // null = pakai global
                'notes'             => null,
            ];
        }
        return $row;
    }

    // -------------------------------------------------------
    // Simpan atau update (upsert)
    // -------------------------------------------------------
    public function saveForTeacher(int $teacherId, ?int $maxHours, ?string $notes): void
    {
        $existing = $this->where('teacher_id', $teacherId)->first();

        $data = [
            'teacher_id'        => $teacherId,
            'max_hours_per_day' => $maxHours, // null = pakai global
            'notes'             => $notes,
        ];

        if ($existing) {
            $this->update($existing['id'], $data);
        } else {
            $this->insert($data);
        }
    }

    // -------------------------------------------------------
    // Ambil effective max hours (pakai global kalau null)
    // -------------------------------------------------------
    public function getEffectiveMax(int $teacherId): int
    {
        $row = $this->where('teacher_id', $teacherId)->first();
        
        // Jika ada setting per guru dan nilainya > 0, pakai itu
        if ($row && $row['max_hours_per_day'] !== null && (int)$row['max_hours_per_day'] > 0) {
            return (int)$row['max_hours_per_day'];
        }
        
        // Jika tidak, ambil dari setting global
        return $this->getGlobalMaxHours();
    }

    // -------------------------------------------------------
    // Ambil semua settings (untuk generator)
    // return: [ teacher_id => max_hours, ... ]
    // -------------------------------------------------------
    public function getAllEffective(): array
    {
        $rows = $this->findAll();
        $globalDefault = $this->getGlobalMaxHours();
        
        $map = [];
        foreach ($rows as $row) {
            $map[$row['teacher_id']] = $row['max_hours_per_day'] ?? $globalDefault;
        }
        return $map;
    }

    // -------------------------------------------------------
    // GET / SET GLOBAL MAX HOURS (dari tabel settings)
    // -------------------------------------------------------
    
    /**
     * Ambil global max hours per day dari tabel settings
     * Default: 6 jika belum ada
     */
    public function getGlobalMaxHours(): int
    {
        $db = \Config\Database::connect();
        $result = $db->table('settings')
            ->select('setting_value')
            ->where('setting_key', 'schedule_max_hours_per_day')
            ->get()
            ->getRowArray();
        
        if ($result && !empty($result['setting_value'])) {
            return (int)$result['setting_value'];
        }
        
        return self::DEFAULT_MAX_HOURS;
    }

    /**
     * Simpan global max hours per day
     */
    public function setGlobalMaxHours(int $value): bool
    {
        $db = \Config\Database::connect();
        
        // Cek apakah sudah ada
        $exists = $db->table('settings')
            ->where('setting_key', 'schedule_max_hours_per_day')
            ->get()
            ->getRowArray();
        
        if ($exists) {
            return $db->table('settings')
                ->where('setting_key', 'schedule_max_hours_per_day')
                ->update(['setting_value' => $value]);
        } else {
            return $db->table('settings')->insert([
                'setting_key'   => 'schedule_max_hours_per_day',
                'setting_value' => $value,
                'setting_group' => 'schedule',
                'created_at'    => date('Y-m-d H:i:s'),
                'updated_at'    => date('Y-m-d H:i:s'),
            ]);
        }
    }

    // -------------------------------------------------------
    // GET SUMMARY untuk halaman index
    // -------------------------------------------------------
    public function getSummaryWithGlobal(): array
    {
        $globalDefault = $this->getGlobalMaxHours();
        
        $teachers = $this->db->table('teachers')
            ->select('id, name, nip')
            ->orderBy('name')
            ->get()
            ->getResultArray();
        
        $settings = $this->findAll();
        $settingMap = [];
        foreach ($settings as $s) {
            $settingMap[$s['teacher_id']] = $s;
        }
        
        $results = [];
        foreach ($teachers as $teacher) {
            $tid = $teacher['id'];
            $setting = $settingMap[$tid] ?? null;
            
            $results[] = [
                'teacher_id'        => $tid,
                'teacher_name'      => $teacher['name'],
                'nip'               => $teacher['nip'],
                'max_hours_per_day' => $setting ? (int)$setting['max_hours_per_day'] : null,
                'effective_max'     => $setting && $setting['max_hours_per_day'] ? (int)$setting['max_hours_per_day'] : $globalDefault,
                'notes'             => $setting['notes'] ?? null,
                'is_custom'         => $setting && $setting['max_hours_per_day'] !== null,
            ];
        }
        
        return [
            'global_default' => $globalDefault,
            'teachers'       => $results,
        ];
    }
}