<?php

namespace App\Models\Post;

use App\Models\System\Settings\Location\Province;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Translatable\HasTranslations;

class PostBranch extends Model
{
    use HasFactory;
    use HasTranslations;

    /**
     * Table name
     */
    protected $table = 'post_branches';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'province_id',
        'name',
        'address',
        'description',
    ];

    /**
     * @var array<string>
     */
    public $translatable = [
        'name',
        'address',
        'description',
    ];

    /**
     * Related Province
     */
    public function province(): BelongsTo
    {
        return $this->belongsTo(Province::class);
    }

    /**
     * Scope to filter
     *
     * @param  Builder  $query
     * @param  string  $value
     * @return Builder $query
     */
    public function scopeByRegion($query, $value): Builder
    {
        return $value
                ? $query->whereIn('province_id', fn ($builder) => $builder->select('id')->from('provinces')->where('region', $value))
                : $query;
    }
}
