<?php

namespace App\Models;

use CodeIgniter\Model;

class FootballSettingModel extends Model
{
    protected $table = 'football_settings';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'timezone',
        'current_season',
        'season_ends_at',
        'last_reference_sync_at',
        'last_fixtures_sync_at',
        'fixtures_cache_from',
        'fixtures_cache_to',
        'updated_at',
    ];
    protected $useTimestamps = false;

    public function getSettings(): array
    {
        $row = $this->first();
        if ($row === null) {
            return [
                'timezone' => 'Africa/Nairobi',
                'current_season' => 2025,
                'season_ends_at' => '2026-05-30',
                'last_reference_sync_at' => null,
                'last_fixtures_sync_at' => null,
                'fixtures_cache_from' => null,
                'fixtures_cache_to' => null,
            ];
        }

        return $row;
    }

    public function updateSettings(array $data): bool
    {
        $row = $this->first();
        $data['updated_at'] = date('Y-m-d H:i:s');
        $data = $this->filterExistingColumns($data);

        if ($row === null) {
            return (bool) $this->insert($data);
        }

        return $this->update($row['id'], $data);
    }

    /**
     * Skip fields not yet migrated (avoids SQL errors on older schemas).
     */
    protected function filterExistingColumns(array $data): array
    {
        $db = \Config\Database::connect();
        if (!$db->tableExists('football_settings')) {
            return $data;
        }

        $fields = $db->getFieldNames('football_settings');

        return array_intersect_key($data, array_flip($fields));
    }

    public function currentSeason(): int
    {
        $settings = $this->getSettings();

        return (int) ($settings['current_season'] ?? 2025);
    }

    public function timezone(): string
    {
        $settings = $this->getSettings();

        return $settings['timezone'] ?? 'Africa/Nairobi';
    }
}
