<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class HasilPenilaian extends Model
{
   protected $table = 'hasil_penilaian';
    protected $fillable = [
        'pengajuan_id',
        'nilai_preferensi',
        'rekomendasi_ukt',
        'keterangan',
        'processed_by',
        'ukt_penyesuaian',
        'status_penyesuaian'
    ];

    protected $appends = ['ukt_formatted', 'budget_formatted']; // Menambahkan accessor formatted

    public function pengajuan()
    {
        return $this->belongsTo(PengajuanUkt::class, 'pengajuan_id');
    }

    public function processor()
    {
        return $this->belongsTo(User::class, 'processed_by');
    }

    public function scopeTopRanking($query, $limit = 50)
    {
        return $query->orderBy('nilai_preferensi', 'desc')
            ->limit($limit);
    }

    public function getUktFormattedAttribute()
{
    return 'Rp' . number_format($this->ukt_penyesuaian, 0, ',', '.');
}

public function scopeForForm($query, $formId)
{
    return $query->whereHas('pengajuan', function($q) use ($formId) {
        $q->where('status_form_id', $formId);
    });
}

 public static function updateBudget($amount)
    {
        if (!is_numeric($amount)) {
            throw new \InvalidArgumentException('Budget harus berupa angka');
        }

        return self::query()->update(['keterangan' => $amount]);
    }

    // Method to get current budget (from keterangan column)
    public static function getCurrentBudget()
    {
        $record = self::first();
        return $record && !empty($record->keterangan) ? (float)$record->keterangan : 0;
    }

    // Accessor for formatted budget display
    public function getBudgetFormattedAttribute()
    {
        return 'Rp' . number_format($this->keterangan, 0, ',', '.');
    }

    // Virtual budget attribute for compatibility
    public function getBudgetAttribute()
    {
        return $this->keterangan;
    }

    public function setBudgetAttribute($value)
    {
        $this->attributes['keterangan'] = $value;
    }}