<?php

namespace App\Models;

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

class Province extends Model
{
    use HasFactory;

    protected $primaryKey = 'province_id';

    protected $fillable = [
        'country_id',
        'province_code',
        'province_name',
        'is_active'
    ];

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

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

    /**
     * Get the cities for the province.
     */
    public function cities()
    {
        return $this->hasMany(City::class, 'province_id', 'province_id');
    }

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

    /**
     * Scope by country
     */
    public function scopeByCountry($query, $countryId)
    {
        return $query->where('country_id', $countryId);
    }

    /**
     * Find province by code and country
     */
    public static function findByCode($code, $countryId = null)
    {
        $query = static::where('province_code', $code);

        if ($countryId) {
            $query->where('country_id', $countryId);
        }

        return $query->first();
    }
}
