<?php

namespace App\Models;

use CodeIgniter\Model;

class FootballTeamModel extends Model
{
    protected $table = 'football_teams';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'api_team_id',
        'name',
        'logo_url',
        'country_name',
        'created_at',
        'updated_at',
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    public function findByApiTeamId(int $apiTeamId): ?array
    {
        return $this->where('api_team_id', $apiTeamId)->first();
    }

    public function upsertFromApi(array $team, ?string $countryName = null): int
    {
        $apiTeamId = (int) ($team['id'] ?? 0);
        if ($apiTeamId <= 0) {
            return 0;
        }

        $existing = $this->findByApiTeamId($apiTeamId);
        $payload = [
            'api_team_id' => $apiTeamId,
            'name' => $team['name'] ?? '',
            'logo_url' => $team['logo'] ?? null,
            'country_name' => $countryName,
        ];

        if ($existing) {
            $this->update($existing['id'], $payload);

            return (int) $existing['id'];
        }

        $this->insert($payload);

        return (int) $this->getInsertID();
    }

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

        $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'];
        }

        $row = $this->like('name', $name, '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;
    }
}
