<?php

namespace App\Models;

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

class City extends Model
{
    use HasFactory;

    protected $primaryKey = 'city_id';

    protected $fillable = [
        'province_id',
        'city_name',
        'is_active'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Get the province that owns the city.
     */
    public function province()
    {
        return $this->belongsTo(Province::class, 'province_id', 'province_id');
    }

    /**
     * Get the country through province.
     */
    public function country()
    {
        return $this->hasOneThrough(
            Country::class,
            Province::class,
            'province_id',
            'country_id',
            'province_id',
            'country_id'
        );
    }

    /**
     * Get addresses for this city
     */
    public function addresses()
    {
        return $this->hasMany(Address::class, 'city_id', 'city_id');
    }

    /**
     * Scope active cities
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope by province
     */
    public function scopeByProvince($query, $provinceId)
    {
        return $query->where('province_id', $provinceId);
    }

    /**
     * Search by city name
     */
    public function scopeSearch($query, $search)
    {
        return $query->where('city_name', 'like', "%{$search}%");
    }
}
