<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Country extends Model
{
    use HasFactory, SoftDeletes;

    // 1. Map the custom timestamp columns
    const CREATED_AT = 'created_at_utc';
    const UPDATED_AT = 'updated_at_utc';
    const DELETED_AT = 'deleted_at_utc';

    // 2. Define the table
    protected $table = 'countries';

    // 3. Cast boolean and JSON fields automatically
    protected $casts = [
        'is_active' => 'boolean',
        'emergency_numbers' => 'array',
        'mobile_number_length_min' => 'integer',
        'mobile_number_length_max' => 'integer',
        'currency_id' => 'integer',
        'default_timezone_id' => 'integer',
        'default_language_id' => 'integer',
    ];

    // 4. Only allow these fields to be mass assigned
    protected $fillable = [
        'code',
        'code_alpha3',
        'numeric_code',
        'name_en',
        'name_native',
        'official_name_en',
        'official_name_native',
        'capital_en',
        'capital_native',
        'region_en',
        'subregion_en',
        'phone_code',
        'mobile_number_format',
        'mobile_number_length_min',
        'mobile_number_length_max',
        'national_number_prefix',
        'international_format_regex',
        'domestic_format_regex',
        'emergency_numbers',
        'currency_id',
        'default_timezone_id',
        'default_language_id',
        'is_active',
        'status',
    ];

    // 5. Scope to get only active countries
    public function scopeActive($query)
    {
        return $query->where('is_active', 1)
                     ->where('status', 'active');
    }

    // 6. Relationship: Country belongs to a Currency
    public function currency()
    {
        return $this->belongsTo(Currency::class, 'currency_id');
    }

    // 7. Relationship: Country belongs to a Timezone
    public function defaultTimezone()
    {
        return $this->belongsTo(Timezone::class, 'default_timezone_id');
    }

    // 8. Relationship: Country belongs to a Language
    public function defaultLanguage()
    {
        return $this->belongsTo(Language::class, 'default_language_id');
    }
}