<?php

namespace App\Models;

use CodeIgniter\Model;

class CalendarCategoryModel extends Model
{
    protected $table            = 'calendar_categories';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'name', 'code', 'color', 'is_libur', 'sort_order'
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules = [
        'name'  => 'required|min_length[3]|max_length[100]',
        'code'  => 'required|max_length[10]',
        'color' => 'required|max_length[10]',
    ];

    public function getActive()
    {
        return $this->where('deleted_at', null)
                    ->orderBy('sort_order', 'ASC')
                    ->findAll();
    }

    /**
     * Cek apakah kategori masih dipakai oleh kegiatan
     */
    public function isUsed($id): bool
    {
        $count = $this->db->table('calendar_events')
                    ->where('category_id', $id)
                    ->where('deleted_at', null)
                    ->countAllResults();

        return $count > 0;
    }
}
