<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class PengajuanDetail extends Model
{
    use HasFactory;

    protected $table = 'pengajuan_details'; 

    protected $fillable = [
        'pengajuan_ukt_id',
        'kriteria_id',
        'kriteria',
        'sub_kriteria_id',
        'subkriteria_text',
        'file_dokumen',
        'verified',
        'verified_by',
        'verified_at',
        'rejection_reason'
    ];

    protected $casts = [
        'verified' => 'boolean',
        'verified_at' => 'datetime', 
    ];
    protected $appends = ['file_url', 'display_kriteria', 'display_subkriteria', 'file_exists'];

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

    public function kriteria()
    {
        return $this->belongsTo(Kriteria::class, 'kriteria_id');
    }

   public function subKriteria()
    {
        return $this->belongsTo(SubKriteria::class, 'sub_kriteria_id');
    }

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

    public function getIsVerifiedAttribute()
    {
        return $this->verified && !is_null($this->verified_at);
    }

    /**
     * Cek ketersediaan file
     */
    public function getFileUrlAttribute()
    {
    if (!$this->file_dokumen) {
        return null;
    }

    // Handle both storage paths
    $filePath = str_replace('public/', '', $this->file_dokumen);
    
    if (Storage::disk('public')->exists($filePath)) {
        return Storage::disk('public')->url($filePath);
    }

    return null;
    }

    public function getFileExistsAttribute()
    {
        if (!$this->file_dokumen) {
            return false;
        }

        $filePath = str_replace('public/', '', $this->file_dokumen);
        return Storage::disk('public')->exists($filePath);
    }
    
}