<?php

namespace App\Modules\Dashboard\Models;

use CodeIgniter\Model;

/**
 * Pengaturan presensi terpusat: jam masuk & jam pulang sekolah.
 * Satu row saja (id=1).
 */
class SchoolPresenceSettingsModel extends Model
{
    protected $table            = 'school_presence_settings';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $allowedFields    = [
        'time_masuk_start',
        'time_masuk_end',
        'time_pulang_start',
        'time_pulang_end',
    ];
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    protected $validationRules = [
        'time_masuk_start'  => 'permit_empty|valid_date[H:i:s]',
        'time_masuk_end'    => 'permit_empty|valid_date[H:i:s]',
        'time_pulang_start' => 'permit_empty|valid_date[H:i:s]',
        'time_pulang_end'   => 'permit_empty|valid_date[H:i:s]',
    ];

    /** ID row default */
    public const DEFAULT_ID = 1;

    /**
     * Ambil satu row pengaturan (id=1). Jika belum ada, return default.
     */
    public function getSettings(): array
    {
        $row = $this->find(self::DEFAULT_ID);
        if ($row && is_object($row)) {
            $row = (array) $row;
        }
        if (empty($row)) {
            return [
                'time_masuk_start'  => '06:30:00',
                'time_masuk_end'    => '07:00:00',
                'time_pulang_start' => '14:00:00',
                'time_pulang_end'   => '14:30:00',
            ];
        }
        return [
            'time_masuk_start'  => $row['time_masuk_start'] ?? '06:30:00',
            'time_masuk_end'    => $row['time_masuk_end'] ?? '07:00:00',
            'time_pulang_start' => $row['time_pulang_start'] ?? '14:00:00',
            'time_pulang_end'   => $row['time_pulang_end'] ?? '14:30:00',
        ];
    }

    /**
     * Simpan pengaturan (upsert id=1).
     */
    public function saveSettings(array $data): bool
    {
        $row = $this->find(self::DEFAULT_ID);
        $payload = [
            'time_masuk_start'  => $data['time_masuk_start'] ?? null,
            'time_masuk_end'    => $data['time_masuk_end'] ?? null,
            'time_pulang_start' => $data['time_pulang_start'] ?? null,
            'time_pulang_end'   => $data['time_pulang_end'] ?? null,
        ];
        if ($row) {
            return $this->update(self::DEFAULT_ID, $payload);
        }
        $payload['id'] = self::DEFAULT_ID;
        return $this->insert($payload) !== false;
    }
}
