<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

final class Country extends Model
{
    use HasFactory;

    protected $fillable = [
        'iso',
        'iso2',
        'iso3',
        'numeric_code',
        'name',
        'native',
        'phone',
        'continent',
        'capital',
        'currency',
        'languages',
        'name_common',
        'name_official',
        'region',
        'subregion',
        'flag_svg_url',
        'flag_png_url',
        'flag_emoji',
        'active',
        'sort_order',
        'is_featured',
    ];

    protected function casts(): array
    {
        return [
            'active' => 'boolean',
            'is_featured' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

    public function users(): HasMany
    {
        return $this->hasMany(User::class);
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('active', true);
    }

    public function scopeOrdered(Builder $query): Builder
    {
        return $query
            ->orderByDesc('is_featured')
            ->orderBy('sort_order')
            ->orderBy('name_common');
    }

    public function getFlagCssClassAttribute(): ?string
    {
        $iso2 = strtoupper((string) $this->iso2);

        if (! preg_match('/^[A-Z]{2}$/', $iso2)) {
            return null;
        }

        return 'fi fi-'.strtolower($iso2);
    }

    public function getLocalFlagPathAttribute(): ?string
    {
        $iso2 = strtoupper((string) $this->iso2);

        if (! preg_match('/^[A-Z]{2}$/', $iso2)) {
            return null;
        }

        return rtrim((string) \config('cdn.files_url', ''), '/').'/images/flags/shiny/24/'.rawurlencode($iso2).'.png';
    }
}
