<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class Country extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',           // NEW
        'code',
        'iso_code',       // NEW
        'iso2',           // NEW
        'dial_code',
        'currency',
        'currency_code',  // NEW
        'currency_symbol',
        'flag_url',       // NEW
        'order',
        'is_default',
        'status',
    ];

    protected $casts = [
        'is_default' => 'boolean',
        'order' => 'integer',
    ];

    // Relations
    public function translations()
    {
        return $this->hasMany(CountryTranslation::class);
    }

    public function locales()
    {
        return $this->hasMany(Locale::class);
    }

    public function stores()
    {
        return $this->belongsToMany(Store::class, 'country_store')
            ->using(CountryStore::class)
            ->withPivot(['user_id', 'status', 'is_featured', 'order'])
            ->withTimestamps();
    }

    public function occasions()
    {
        return $this->belongsToMany(Occasion::class, 'country_occasion');
    }

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

    public function currentUsers()
    {
        return $this->hasMany(User::class, 'current_country_id');
    }

    public function countryStores()
    {
        return $this->hasMany(CountryStore::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeDefault($query)
    {
        return $query->where('is_default', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('order')->orderBy('id');
    }

    public function scopeByCode($query, $code)
    {
        return $query->where('code', $code);
    }

    public function scopeByIsoCode($query, $isoCode)
    {
        return $query->where('iso_code', $isoCode);
    }

    // Accessors
    public function getIsActiveAttribute()
    {
        return $this->status === 'active';
    }

    public function getFlagEmojiAttribute()
    {
        if (!$this->iso2) return '';

        $offset = 127397;
        return mb_chr($offset + ord($this->iso2[0])) . mb_chr($offset + ord($this->iso2[1]));
    }

    // Helper Methods
    public function getTranslation($languageId)
    {
        return $this->translations()->where('language_id', $languageId)->first();
    }

    public function getName($languageId = null)
    {
        if ($languageId) {
            $translation = $this->getTranslation($languageId);
            return $translation ? $translation->name : $this->name;
        }
        return $this->name ?? $this->code;
    }

    /**
     * Fetch country data from REST Countries API
     */
    public static function fetchCountryData($isoCode)
    {
        try {
            $response = Http::timeout(10)->get("https://restcountries.com/v3.1/alpha/{$isoCode}");

            if ($response->successful() && !empty($response->json())) {
                $data = $response->json()[0];

                return [
                    'name' => $data['name']['common'] ?? null,
                    'iso_code' => $data['cca3'] ?? strtoupper($isoCode),
                    'iso2' => $data['cca2'] ?? null,
                    'code' => $data['cca2'] ?? null, // نفس الـ iso2 للتوافق
                    'flag_url' => $data['flags']['png'] ?? null,
                    'dial_code' => isset($data['idd']['root']) && isset($data['idd']['suffixes'][0])
                        ? $data['idd']['root'] . $data['idd']['suffixes'][0]
                        : null,
                    'currency_code' => isset($data['currencies'])
                        ? array_keys($data['currencies'])[0]
                        : null,
                    'currency' => isset($data['currencies'])
                        ? array_keys($data['currencies'])[0]
                        : null, // نفس الـ currency_code للتوافق
                    'currency_symbol' => isset($data['currencies'])
                        ? $data['currencies'][array_keys($data['currencies'])[0]]['symbol'] ?? null
                        : null,
                ];
            }
        } catch (\Exception $e) {
            Log::warning("Failed to fetch country data for {$isoCode}: " . $e->getMessage());
        }

        return null;
    }

    /**
     * Create country with API data
     */
    public static function createWithApiData(array $formData)
    {
        $countryData = null;

        // Try to fetch from API if ISO code provided
        if (!empty($formData['iso_code'])) {
            $countryData = self::fetchCountryData($formData['iso_code']);
        }

        // Merge form data with API data (form data takes priority)
        $data = array_merge($countryData ?? [], $formData);

        return self::create($data);
    }

    /**
     * Update flag URL from API
     */
    public function updateFlagFromApi()
    {
        if ($this->iso_code) {
            $apiData = self::fetchCountryData($this->iso_code);
            if ($apiData && isset($apiData['flag_url'])) {
                $this->update(['flag_url' => $apiData['flag_url']]);
                return true;
            }
        }
        return false;
    }



    public function settings()
    {
        return $this->hasMany(Setting::class);
    }

    public function getSeoSettings()
    {
        return $this->settings()->where('group', 'seo')->get();
    }

    public function hasSeoSettings()
    {
        return $this->settings()->where('group', 'seo')->exists();
    }
}
