<?php

namespace App\Modules\Academic\Models;

use App\Modules\Academic\Entities\LessonSlot;
use CodeIgniter\Model;

/**
 * Lesson Slot Model
 */
class LessonSlotModel extends Model
{
    protected $table            = 'lesson_slots';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = LessonSlot::class;
    protected $allowedFields    = [
        'slot_number',
        'start_time',
        'end_time',
        'is_active',
    ];

    protected $useTimestamps = false;

    protected $validationRules = [
        'slot_number' => 'required|integer|greater_than[0]|is_unique[lesson_slots.slot_number,id,{id}]',
        'start_time'  => 'required|valid_date[H:i:s]',
        'end_time'    => 'required|valid_date[H:i:s]',
        'is_active'   => 'permit_empty|in_list[0,1]',
    ];

    protected $validationMessages = [
        'end_time' => [
            'required' => 'End time is required.',
        ],
    ];

    protected function getSlotStartBeforeEndRule(): array
    {
        return [
            'end_time' => 'required|valid_date[H:i:s]|greater_than_field[start_time]',
        ];
    }

    /**
     * Validate that start_time < end_time (custom rule or after validation).
     */
    public function validateStartBeforeEnd(array $data): bool
    {
        $start = $data['start_time'] ?? '';
        $end   = $data['end_time'] ?? '';
        if ($start === '' || $end === '') {
            return true;
        }
        return strtotime($start) < strtotime($end);
    }

    /**
     * Override insert to check start < end.
     */
    public function insert($data = null, bool $returnID = true)
    {
        if (is_array($data) && !$this->validateStartBeforeEnd($data)) {
            $this->errors['end_time'] = 'End time must be after start time.';
            return false;
        }
        return parent::insert($data, $returnID);
    }

    /**
     * Override update to check start < end (merge with existing when partial).
     */
    public function update($id = null, $data = null): bool
    {
        if (is_array($data) && (array_key_exists('start_time', $data) || array_key_exists('end_time', $data))) {
            $existing = $this->find($id);
            $exStart  = $existing && is_object($existing) ? $existing->start_time : ($existing['start_time'] ?? '');
            $exEnd    = $existing && is_object($existing) ? $existing->end_time : ($existing['end_time'] ?? '');
            $merged   = [
                'start_time' => $data['start_time'] ?? $exStart,
                'end_time'   => $data['end_time'] ?? $exEnd,
            ];
            if (!$this->validateStartBeforeEnd($merged)) {
                $this->errors['end_time'] = 'End time must be after start time.';
                return false;
            }
        }
        return parent::update($id, $data);
    }
}
