<?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\DB;
use Illuminate\Support\Facades\Log;

class ClientStatus extends Model
{
    use HasFactory;

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

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

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

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

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

    public function client()
    {
        return $this->belongsTo(Client::class, 'fk_client', 'id')->select(
            'id',
            DB::raw("CONCAT(firstname, ' ', lastname, ' ', secondlastname) as fullname"),
            'curp',
            'fk_city',
            'colony',
            'address',
            'phonenumber',
            'fk_client_status',
            'fk_endorsement_status',
            'has_employee'
        );
    }

    public function status()
    {
        return $this->belongsTo(Status::class, 'fk_status', 'id')->select('id', 'fk_status_type', 'statusname', 'classname');
    }

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