<?php

namespace App\Models;

use CodeIgniter\Model;

class FootballLeagueModel extends Model
{
    protected $table = 'football_leagues';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'api_league_id',
        'name',
        'country_name',
        'country_code',
        'type',
        'logo_url',
        'is_current',
        'coverage_json',
        'created_at',
        'updated_at',
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    public function forCountry(string $countryName, ?string $search = null): array
    {
        $builder = $this->where('country_name', $countryName)
            ->orderBy('name', 'ASC');

        if ($search !== null && strlen(trim($search)) >= 2) {
            $builder->like('name', trim($search));
        }

        return $builder->findAll();
    }

    public function findByApiLeagueId(int $apiLeagueId): ?array
    {
        return $this->where('api_league_id', $apiLeagueId)->first();
    }

    public function findLogoByLabel(string $label): ?string
    {
        $label = trim($label);
        if ($label === '') {
            return null;
        }

        $candidates = [$label];
        if (str_contains($label, ' - ')) {
            $candidates[] = trim(explode(' - ', $label, 2)[0]);
        }

        foreach ($candidates as $name) {
            if ($name === '') {
                continue;
            }
            $row = $this->where('name', $name)
                ->where('logo_url IS NOT NULL', null, false)
                ->where('logo_url !=', '')
                ->first();
            if (!empty($row['logo_url'])) {
                return $row['logo_url'];
            }
        }

        $search = $candidates[0];
        $row = $this->like('name', $search, 'both')
            ->where('logo_url IS NOT NULL', null, false)
            ->where('logo_url !=', '')
            ->orderBy('LENGTH(name)', 'ASC')
            ->first();

        return !empty($row['logo_url']) ? $row['logo_url'] : null;
    }
}
