<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Country extends Model
{
    use HasFactory;
    protected $table = 'tbl_country';

    protected $primaryKey = 'id';

    protected $fillable = [
        'code',
        'abbreviation',
        'name',
        'nationality',
        'language',
        'coin',
        'coin_code',
        'idtimezone',
        'status',
    ];

    protected $hidden = [
        'created_at',
        'updated_at'
    ];

    public function timeZone(): HasOne
    {
        return $this->hasOne(TimeZone::class, 'id', 'idtimezone');
    }

    # Query scopes
    public function scopeActiveForID($query, $id)
    {
        return $query->where('id', $id)->where('status', 1);
    }

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

    # Filtros
    public function scopeCountryFilters($query)
    {
        #Filtro de Buscador
        $query->when(
            request('search'),
            fn ($query) => $query->where('code', 'LIKE', '%' . request('search') . '%')
                ->orWhere('name', 'LIKE', '%' . request('search') . '%')
        );

        #Filtro de codigo
        $query->when(
            request('code'),
            fn ($query) => $query->where('code', 'LIKE', '%' . request('code') . '%')
        );

        #Filtro de abreviacion
        $query->when(
            request('abbreviation'),
            fn ($query) => $query->where('abbreviation', 'LIKE', '%' . request('abbreviation') . '%')
        );

        #Filtro de timezone
        $query->when(
            request('idtimezone'),
            fn ($query) => $query->where('idtimezone', request('idtimezone'))
        );

        #Filtro de estados
        $query->when(
            request('status'),
            fn ($query) => $query->where('status', request('status'))
        )->when(
            !request('status'),
            fn ($query) => $query->where('status', 1)
        );

    }
}
