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

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

    protected $fillable = [
        'id',
        'fk_loan_request',
        'fk_client_request',
        'fk_client',
        'fk_model',
        'description',
        'serialnumber',
        'available',
        'fk_usercreator',
        'created_at',
        'fk_userupdater',
        'update_at',
        'is_active'
    ];

    protected $casts = [
        'id' => 'integer',
        'fk_loan_request' => 'integer',
        'fk_client_request' => 'integer',
        'fk_client' => 'integer',
        'fk_model' => 'integer',
        'description' => 'string',
        'serialnumber' => 'string',
        'available' => 'boolean',
        'fk_usercreator' => 'integer',
        'created_at' => 'timestamp',
        'fk_userupdater' => 'integer',
        'update_at' => 'timestamp',
        'is_active' => 'boolean',
    ];


    protected $hidden = [
        'fk_loan_request',
        'fk_client_request',
        'fk_client',
        'fk_model',
        'fk_usercreator',
        'fk_userupdater',
        'is_active'
    ];

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

    public function request_loan()
    {
        return $this->belongsTo(RequestLoan::class, 'fk_loan_request');
    }

    public function request_client()
    {
        return $this->belongsTo(RequestClient::class, 'fk_client_request');
    }

    public function client()
    {
        return $this->belongsTo(Client::class, 'fk_client');
    }

    public function model()
    {
        return $this->belongsTo(Model::class, 'fk_model');
    }

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