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

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

    protected $fillable = [
        'id',
        'fk_loan_request',
        'renewpayment',
        'paperworkpayment',
        'otherpayment',
        'interesrate',
        'visible',
        'available',
        'fk_usercreator',
        'created_at',
        'fk_userupdater',
        'update_at',
        'is_active'
    ];

    protected $casts = [
        'id' => 'integer',
        'fk_loan_request' => 'integer',
        'renewpayment' => 'float',
        'paperworkpayment' => 'float',
        'otherpayment' => 'float',
        'interesrate' => 'float',
        'visible' => 'boolean',
        'available' => 'boolean',
        'fk_usercreator' => 'integer',
        'created_at' => 'timestamp',
        'fk_userupdater' => 'integer',
        'updated_at' => 'timestamp',
        'is_active' => 'boolean',
    ];

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

    public static function booted()
    {
        static::updated(function ($loan) {
            Log::channel('requestloandetails')->info('Request loan details 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 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');
    }
}
