<?php

namespace App\Models;

use CodeIgniter\Model;

class ScheduleAvailabilityModel extends Model
{
    protected $table      = 'schedule_availability';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'teacher_id', 'day', 'slot_number', 'reason',
    ];

    protected $useTimestamps = true;

    // -------------------------------------------------------
    // Ambil semua unavailability satu guru
    // Return: [ day => [ slot_number => true, ... ], ... ]
    // -------------------------------------------------------
    public function getBlockedMap(int $teacherId): array
    {
        $rows = $this->where('teacher_id', $teacherId)->findAll();
        $map  = [];
        foreach ($rows as $row) {
            $map[$row['day']][$row['slot_number']] = true;
        }
        return $map;
    }

    // -------------------------------------------------------
    // Simpan grid (replace semua milik guru ini)
    // $blocked = [ ['day'=>1,'slot_number'=>2], ... ]
    // -------------------------------------------------------
    public function saveGrid(int $teacherId, array $blocked): void
    {
        // Hapus semua dulu
        $this->where('teacher_id', $teacherId)->delete();

        // Insert yang baru
        if (!empty($blocked)) {
            $inserts = array_map(fn($b) => [
                'teacher_id'  => $teacherId,
                'day'         => $b['day'],
                'slot_number' => $b['slot_number'],
                'reason'      => $b['reason'] ?? null,
            ], $blocked);
            $this->insertBatch($inserts);
        }
    }

    // -------------------------------------------------------
    // Ambil semua guru beserta jumlah blokir-nya (untuk list)
    // -------------------------------------------------------
    public function getSummaryByTeacher(): array
    {
        return $this->db->table('teachers t')
            ->select('t.id, t.name, t.nip, COUNT(sa.id) as total_blocked')
            ->join('schedule_availability sa', 'sa.teacher_id = t.id', 'left')
            ->groupBy('t.id')
            ->orderBy('t.name')
            ->get()->getResultArray();
    }

    // -------------------------------------------------------
    // Untuk generator: ambil semua blocked sebagai flat array
    // -------------------------------------------------------
    public function getAllBlocked(): array
    {
        return $this->findAll();
    }
}