<?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 RequestClient extends Model
{
    use HasFactory;

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

    protected $fillable = [
        'fk_site',
        'fk_office',
        'firstname',
        'lastname',
        'secondlastname',
        'curp',
        'fk_city',
        'colony',
        'address',
        'phonenumber',
        'has_employee',
        'visible',
        'available',
        'fk_usercreator',
        'created_at',
        'fk_userupdater',
        'updated_at',
        'is_active'
    ];

    protected $casts = [
        'fk_site' => 'integer',
        'fk_office' => 'integer',
        'firstname' => 'string',
        'lastname' => 'string',
        'secondlastname' => 'string',
        'curp' => 'string',
        'fk_city' => 'integer',
        'colony' => 'string',
        'address' => 'string',
        'phonenumber' => 'string',
        'has_employee' => 'boolean',
        '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 ($client) {
            Log::channel('requestclient')->info('Request client updated', [
                'id' => $client->id,
                'fk_userupdater' => $client->fk_userupdater,
                'updated_at' => Carbon::now(),
                'changes' => $client->getChanges()
            ]);
        });
    }

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

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

    public function fullname()
    {
        return $this->firstname . ' ' . $this->lastname . ' ' . $this->secondlastname;
    }

    public function city()
    {
        return $this->belongsTo(City::class, 'fk_city', 'id')->select('id', 'cityname');
    }

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