<?php

namespace Modules\Lpj\Models;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class LampiranDokumen extends Base
{
    protected $table = 'lampiran_dokumen';

    protected $fillable = ['permohonan_id', 'nama_file', 'path_file', 'keterangan','jenis_lampiran_id'];

    public function permohonan()
    {
        return $this->belongsTo(Permohonan::class);
    }

    /**
     * Upload lampiran dokumen for penilai or administrator
     *
     * @param int $permohonanId
     * @param array $fileData
     * @return LampiranDokumen|null
     */
    public static function uploadLampiran($fileData)
    {
        $user = Auth::user();

        if ($user && $user->hasAnyRole(['penilai', 'administrator', 'Penilai', 'admin','surveyor','pemohon-ao','pemohon-eo'])) {
            $file = $fileData['file'];
            $fileName = $fileData['nama_file'] ?? time() . '_' . $file->getClientOriginalName();
            $filePath = $file->storeAs('lampiran_dokumen', $fileName, 'public');

            return self::create([
                'permohonan_id' => $fileData['permohonan_id'] ?? null,
                'jenis_lampiran_id' => $fileData['jenis_lampiran_id'] ?? null,
                'nama_file'     => $fileName,
                'path_file'     => $filePath,
                'keterangan'    => $fileData['keterangan'] ?? null,
            ]);
        }

        return null;
    }

    /**
     * Delete lampiran dokumen
     *
     * @return bool
     */
    public function deleteLampiran()
    {
        $user = Auth::user();

        if ($user && ($user->hasRole('penilai') || $user->hasRole('administrator'))) {
            // Delete the file from storage
            Storage::disk('public')->delete($this->path_file);

            // Delete the database record
            return $this->delete();
        }

        return false;
    }

    public function jenisLampiran()
    {
        return $this->belongsTo(JenisLampiran::class);
    }
}
