<?php

namespace App\Models\Application;

use App\Models\Administration\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class City extends Model
{
    use HasFactory;

    protected $table = 'ct_cities';
    public $timestamps = false;

    protected $fillable = [
        'id',
        'cityname',
        'visible',
        'available',
        'fk_usercreator',
        'created_at',
        'fk_userupdater',
        'updated_at',
        'is_active'
    ];

    protected $casts = [
        'id' => 'integer',
        'visible' => 'boolean',
        'available' => 'boolean',
        'fk_usercreator' => 'integer',
        'created_at' => 'timestamp',
        'fk_userupdater' => 'integer',
        'updated_at' => 'timestamp',
        'is_active' => 'boolean',
    ];

    protected $hidden = [
        'fk_usercreator',
        'fk_userupdater',
        'is_active',
    ];

    public static function booted()
    {
        static::updated(function ($city) {
            Log::channel('city')->info('City Updated', [
                'id' => $city->id,
                'fk_userupdater' => $city->fk_userupdater,
                'updated_at' => Carbon::now(),
                'changes' => $city->getChanges()
            ]);
        });
    }

    public function zones()
    {
        return $this->hasMany(Zone::class, 'fk_city', 'id')->select('id', 'fk_site', 'fk_office', 'fk_city', 'zonename', 'fk_executive');
    }

    public function user_creator()
    {
        return $this->hasOne(User::class, 'id', 'fk_usercreator')->select('id', 'username');
    }

    public function user_updater()
    {
        return $this->hasOne(User::class, 'id', 'fk_userupdater')->select('id', 'username');
    }
}
