<?php

    namespace Modules\Lpj\Models;

    use Illuminate\Support\Facades\Storage;
    use Modules\Lpj\Database\Factories\PermohonanFactory;
    use Modules\Lpj\Services\PermohonanHistoryService;
    use Modules\Usermanagement\Models\User;

    class Permohonan extends Base
    {
        protected $table    = 'permohonan';
        protected $fillable = [
            'id',
            'nomor_registrasi',
            'tanggal_permohonan',
            'user_id',
            'branch_id',
            'tujuan_penilaian_id',
            'debiture_id',
            'keterangan',
            'dokumen',
            'jenis_fasilitas_kredit_id',
            'nilai_plafond_id',
            'status',
            'authorized_at',
            'authorized_status',
            'authorized_by',
            // andy add
            'registrasi_catatan',
            'registrasi_by',
            'registrasi_at',
            'jenis_penilaian_id',
            'region_id',
            // andy add
            'status_bayar',
            'nilai_njop',
            // andy add
            'registrasi_catatan',
            'registrasi_by',
            'registrasi_at',
            'region_id',
            'sla',
            // andy add
            'approve_keterangan_bayar',
            'approve_bayar_by',
            'approve_bayar_at',

            'approval_eo',
            'approval_eo_at',
            'approval_dd',
            'approval_dd_at',
            'approval_so',
            'approval_so_at',
            'tanggal_paparan'
        ];

        protected $dates = [
            'tanggal_permohonan',
            'authorized_at',
            'created_at',
            'updated_at',
            'registrasi_at',
            'approve_bayar_at',
            'approval_eo_at',
            'approval_dd_at',
            'approval_so_at',
        ];

        protected static function boot()
        {
            parent::boot();

            static::creating(function ($permohonan) {
                static::handleFileUpload($permohonan);
            });

            static::updating(function ($permohonan) {
                static::handleFileUpload($permohonan);
            });

            static::created(function ($permohonan) {
                static::createHistory($permohonan, 'created');
            });

            static::updated(function ($permohonan) {
                static::createHistory($permohonan, 'updated');
            });
        }

        protected static function handleFileUpload($permohonan)
        {
            if (request()->hasFile('attachment')) {
                $file     = request()->file('attachment');
                $fileName = time() . '_' . $file->getClientOriginalName();
                $filePath = $file->storeAs('permohonan_attachments', $fileName, 'public');

                $permohonan->dokumen = $filePath;
            }
        }

        protected static function createHistory($permohonan, $action)
        {
            $historyService = app(PermohonanHistoryService::class);

            $keterangan = request()->input('keterangan', '');
            if (request()->filled('registrasi_catatan')) {
                if (!empty($keterangan)) {
                    $keterangan .= "\n";
                }
                $keterangan .= request()->input('registrasi_catatan');
            }

            $status        = $permohonan->status;
            $beforeRequest = $action === 'updated' ? $permohonan->getOriginal() : [];
            $afterRequest  = $permohonan->toArray();

            $file = null;
            if (request()->hasFile('attachment')) {
                $file     = request()->file('attachment');
                $fileName = time() . '_' . $file->getClientOriginalName();
                $filePath = $file->storeAs('permohonan_attachments', $fileName, 'public');

                $file = $filePath;
            }

            $historyService->createHistory(
                $permohonan,
                $status,
                $keterangan,
                $beforeRequest,
                $afterRequest,
                $file,
            );
        }

        public function user()
        {
            return $this->belongsTo(User::class);
        }

        public function branch()
        {
            return $this->belongsTo(Branch::class);
        }

        public function tujuanPenilaian()
        {
            return $this->belongsTo(TujuanPenilaian::class);
        }

        public function debiture()
        {
            return $this->belongsTo(Debiture::class);
        }

        public function documents()
        {
            return $this->hasMany(DokumenJaminan::class);
        }

        public function nilaiPlafond()
        {
            return $this->belongsTo(NilaiPlafond::class);
        }

        public function jenisFasilitasKredit()
        {
            return $this->belongsTo(JenisFasilitasKredit::class);
        }

        public function jenisPenilaian()
        {
            return $this->belongsTo(JenisPenilaian::class);
        }

        public function penilaian()
        {
            return $this->belongsTo(Penilaian::class, 'nomor_registrasi', 'nomor_registrasi');
        }

        public function penilai()
        {
            return $this->belongsTo(Penilai::class, 'id', 'permohonan_id');
        }

        public function penawaranTender()
        {
            return $this->belongsTo(PenawaranTender::class, 'nomor_registrasi', 'nomor_registrasi');
        }

        public function region()
        {
            return $this->belongsTo(Regions::class, 'region_id');
        }

        public function penawaran()
        {
            return $this->belongsTo(PenawaranTender::class, 'nomor_registrasi', 'nomor_registrasi');
        }

        public function histories()
        {
            return $this->hasMany(PermohonanHistory::class, 'permohonan_id', 'id')->orderBy('created_at', 'desc');
        }

        public function dokumenjaminan()
        {
            return $this->hasMany(DokumenJaminan::class);
        }

        public function pembatalan()
        {
            return $this->hasMany(PermohonanPembatalan::class);
        }

        public function approveBayar()
        {
            return $this->belongsTo(User::class, 'approve_bayar_by', 'id');
        }

        public function approveEo()
        {
            return $this->belongsTo(User::class, 'approval_eo', 'id');
        }

        public function approveDd()
        {
            return $this->belongsTo(User::class, 'approval_dd', 'id');
        }

        public function approveSo()
        {
            return $this->belongsTo(User::class, 'approval_so', 'id');
        }

        public function authorization()
        {
            return $this->belongsTo(Authorization::class, 'id', 'permohonan_id');
        }

        public function lampiranDokumen()
        {
            return $this->hasMany(LampiranDokumen::class);
        }

        public function laporanExternal()
        {
            return $this->belongsTo(LaporanExternal::class,'id','permohonan_id');
        }


        public function laporan()
        {
            return $this->belongsTo(Laporan::class,'id','permohonan_id');
        }

        public function inspeksi(){
            return $this->belongsTo(Inspeksi::class, 'permohonan_id');
        }

        // Add this relationship
        public function noc()
        {
            return $this->hasOne(Noc::class, 'permohonan_id');
        }

    }
