<?php

namespace App\Models\Application;

use App\Models\Administration\Office;
use App\Models\Administration\Site;
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 Brand extends Model
{
    use HasFactory;

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

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

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

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

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

    public function site()
    {
        return $this->belongsTo(Site::class, 'fk_site', 'id');
    }

    public function office()
    {
        return $this->belongsTo(Office::class, 'fk_office', 'id');
    }

    public function models()
    {
        return $this->hasMany(GuaranteeModel::class, 'fk_brand', 'id')->select('id', 'fk_brand', 'modelname')->where('is_active', true);
    }

    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');
    }
}
