<?php

namespace App\Models;

use CodeIgniter\Model;

class CalendarEventModel extends Model
{
    protected $table            = 'calendar_events';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = true;
    protected $allowedFields    = [
        'academic_year_id', 'academic_period_id', 'category_id',
        'title', 'start_date', 'end_date', 'description', 'created_by'
    ];

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

    protected $validationRules = [
        'academic_year_id' => 'required|numeric',
        'category_id'      => 'required|numeric',
        'title'            => 'required|min_length[3]|max_length[200]',
        'start_date'       => 'required|valid_date',
        'end_date'         => 'required|valid_date',
    ];

    /**
     * Ambil semua kegiatan dalam 1 tahun ajaran, lengkap dengan info kategori
     */
    public function getByYear($yearId)
    {
        if (empty($yearId)) {
            return [];
        }

        return $this->select('
                calendar_events.*,
                calendar_categories.name as category_name,
                calendar_categories.code as category_code,
                calendar_categories.color as color,
                calendar_categories.is_libur as is_libur
            ')
            ->join('calendar_categories', 'calendar_categories.id = calendar_events.category_id')
            ->where('calendar_events.academic_year_id', $yearId)
            ->where('calendar_events.deleted_at', null)
            ->orderBy('calendar_events.start_date', 'ASC')
            ->findAll();
    }

    /**
     * Ambil 1 kegiatan beserta info kategori
     */
    public function getDetail($id)
    {
        return $this->select('
                calendar_events.*,
                calendar_categories.name as category_name,
                calendar_categories.code as category_code,
                calendar_categories.color as color
            ')
            ->join('calendar_categories', 'calendar_categories.id = calendar_events.category_id')
            ->where('calendar_events.id', $id)
            ->first();
    }
}
