<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\ScheduleAvailabilityModel;
use App\Models\ScheduleTimeslotModel;
use App\Models\ScheduleTeacherSettingModel;

class ScheduleAvailability extends BaseController
{
    protected ScheduleAvailabilityModel    $model;
    protected ScheduleTimeslotModel        $slotModel;
    protected ScheduleTeacherSettingModel  $settingModel;
    protected \CodeIgniter\Database\BaseConnection $db;

    public const DEFAULT_MAX_HOURS = 6;

    public function __construct()
    {
        $this->model        = new ScheduleAvailabilityModel();
        $this->slotModel    = new ScheduleTimeslotModel();
        $this->settingModel = new ScheduleTeacherSettingModel();
        $this->db           = \Config\Database::connect();
    }

    // ----------------------------------------------------------
    // INDEX — daftar semua guru
    // ----------------------------------------------------------
    public function index(): string
    {
        $summary = $this->model->getSummaryByTeacher();

        // Tambah info max_hours per guru
        $settings = $this->db->table('schedule_teacher_settings')
                             ->select('teacher_id, max_hours_per_day')
                             ->get()->getResultArray();
        $settingsMap = array_column($settings, 'max_hours_per_day', 'teacher_id');

        foreach ($summary as &$row) {
            $row['max_hours_per_day'] = $settingsMap[$row['id']] ?? null;
        }

        return view('schedule_availability/index', [
            'title'      => 'Ketersediaan Guru',
            'summary'    => $summary,
            'defaultMax' => self::DEFAULT_MAX_HOURS,
        ]);
    }

    // ----------------------------------------------------------
    // EDIT — tampil grid + tab batas jam
    // ----------------------------------------------------------
    public function edit(int $teacherId): string
    {
        $teacher = $this->db->table('teachers')
                            ->where('id', $teacherId)
                            ->get()->getRowArray();

        if (!$teacher) {
            return redirect()->to('/schedule-availability')
                ->with('error', 'Guru tidak ditemukan.');
        }

        $grouped     = $this->slotModel->getGroupedByDay();
        $blockedMap  = $this->model->getBlockedMap($teacherId);
        $setting     = $this->settingModel->getByTeacher($teacherId);

        return view('schedule_availability/edit', [
            'title'      => 'Ketersediaan — ' . $teacher['name'],
            'teacher'    => $teacher,
            'grouped'    => $grouped,
            'blockedMap' => $blockedMap,
            'setting'    => $setting,
            'defaultMax' => self::DEFAULT_MAX_HOURS,
        ]);
    }

    // ----------------------------------------------------------
    // SAVE SETTINGS — simpan batas jam/hari (AJAX, Tab 1)
    // ----------------------------------------------------------
    public function saveSettings(int $teacherId)
    {
        $teacher = $this->db->table('teachers')->where('id', $teacherId)->get()->getRowArray();
        if (!$teacher) {
            return $this->response->setJSON(['success' => false, 'message' => 'Guru tidak ditemukan.']);
        }

        $raw      = $this->request->getJSON(true);
        $maxHours = isset($raw['max_hours_per_day']) && $raw['max_hours_per_day'] !== ''
                    ? (int)$raw['max_hours_per_day']
                    : null;
        $notes    = $raw['notes'] ?? null;

        // Validasi
        if ($maxHours !== null && ($maxHours < 1 || $maxHours > 12)) {
            return $this->response->setJSON(['success' => false, 'message' => 'Batas jam harus antara 1–12.']);
        }

        $this->settingModel->saveForTeacher($teacherId, $maxHours, $notes);

        $effectiveMax = $maxHours ?? self::DEFAULT_MAX_HOURS;

        return $this->response->setJSON([
            'success'      => true,
            'message'      => 'Batas jam berhasil disimpan.',
            'effective_max' => $effectiveMax,
            'is_default'   => $maxHours === null,
        ]);
    }

    // ----------------------------------------------------------
    // SAVE GRID — simpan slot tidak tersedia (AJAX, Tab 2)
    // ----------------------------------------------------------
    public function save(int $teacherId)
    {
        $teacher = $this->db->table('teachers')->where('id', $teacherId)->get()->getRowArray();
        if (!$teacher) {
            return $this->response->setJSON(['success' => false, 'message' => 'Guru tidak ditemukan.']);
        }

        $raw     = $this->request->getJSON(true);
        $blocked = $raw['blocked'] ?? [];

        $clean = [];
        foreach ($blocked as $b) {
            $day  = (int)($b['day']         ?? 0);
            $slot = (int)($b['slot_number'] ?? 0);
            if ($day >= 1 && $day <= 6 && $slot >= 0) {
                $clean[] = ['day' => $day, 'slot_number' => $slot, 'reason' => $b['reason'] ?? null];
            }
        }

        $this->model->saveGrid($teacherId, $clean);

        return $this->response->setJSON([
            'success' => true,
            'message' => 'Ketersediaan slot berhasil disimpan.',
            'total'   => count($clean),
        ]);
    }

    // ----------------------------------------------------------
    // RESET — hapus semua blokir slot guru
    // ----------------------------------------------------------
    public function reset(int $teacherId)
    {
        $this->model->where('teacher_id', $teacherId)->delete();
        return $this->response->setJSON(['success' => true, 'message' => 'Semua blokir slot direset.']);
    }
}