<?php

namespace App\Models;

use CodeIgniter\Model;

class ScheduleTimeslotModel extends Model
{
    protected $table      = 'schedule_timeslots';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'day', 'slot_number', 'label', 'start_time', 'end_time',
        'slot_type', 'is_active',
    ];

    protected $useTimestamps = true;

    // -------------------------------------------------------
    // Daftar jenis slot
    // -------------------------------------------------------
    public static function slotTypes(): array
    {
        return [
            'kbm'        => ['label' => 'KBM',               'badge' => 'bg-success-subtle text-success',   'icon' => 'bi-book'],
            'istirahat'  => ['label' => 'Istirahat',          'badge' => 'bg-warning text-dark',             'icon' => 'bi-cup-hot'],
            'upacara'    => ['label' => 'Upacara',            'badge' => 'bg-danger-subtle text-danger',     'icon' => 'bi-flag'],
            'keagamaan'  => ['label' => 'Kegiatan Keagamaan', 'badge' => 'bg-purple-subtle text-purple',    'icon' => 'bi-moon-stars'],
            'lainnya'    => ['label' => 'Lainnya',            'badge' => 'bg-secondary-subtle text-secondary','icon' => 'bi-three-dots'],
        ];
    }

    // -------------------------------------------------------
    // Nama hari dalam Bahasa Indonesia
    // -------------------------------------------------------
    public static function dayName(int $day): string
    {
        return ['', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'][$day] ?? '-';
    }

    // -------------------------------------------------------
    // Ambil semua slot, dikelompokkan per hari
    // -------------------------------------------------------
    public function getGroupedByDay(): array
    {
        $rows = $this->orderBy('day')->orderBy('slot_number')->findAll();
        $grouped = [];
        foreach ($rows as $row) {
            $grouped[$row['day']][] = $row;
        }
        return $grouped;
    }

    // -------------------------------------------------------
    // Ambil slot KBM aktif saja (untuk dropdown di modul lain)
    // -------------------------------------------------------
    public function getActiveKbmSlots(): array
    {
        return $this->where('slot_type', 'kbm')
                    ->where('is_active', 1)
                    ->orderBy('day')
                    ->orderBy('slot_number')
                    ->findAll();
    }

    // -------------------------------------------------------
    // Cek duplikat (day + slot_number), kecuali id tertentu
    // -------------------------------------------------------
    public function isDuplicate(int $day, int $slotNumber, ?int $excludeId = null): bool
    {
        $builder = $this->where('day', $day)->where('slot_number', $slotNumber);
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }
        return $builder->countAllResults() > 0;
    }
}