<?php

namespace App\Models;

use App\Events\ClaimReceived;
use App\Events\ClaimRequested;
use App\Traits\Blameable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Altek\Accountant\Contracts\Recordable;
use Str;

class RequestLog extends Model
{
    use HasFactory, SoftDeletes, Blameable;

    // protected static $code_prefix_hospital = 'CRQ-H';
    // protected static $code_prefix_client = 'CRQ-R';

    public $fillable = [
        'uuid',
        'submission_date',
        'discharge_date',
        'member_id',
        'payment_type',
        'service_code',
        'type_of_member',
        'total_cob',
        'policy_id',
        'final_log',
        'status',
        'status_final_log',
        'source',
        'claim_id',
        'organization_id',
        'keterangan',
        'hak_kamar_pasien',
        'penempatan_kamar',
        'catatan',
        'import_system',
        'diagnosis',
        'code',
        'reason',
        'reason_final',
        'approved_by',
        'approved_at',
        'approved_final_log_by',
        'approved_final_log_at',
        'created_final_at',
        'created_final_by',
    ];

    protected $hidden = [
        // 'created_at',
        'updated_at',
        'deleted_at',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    public $doc_headers_to_field_map = [
        "Record Mode" => "record_mode",
        "Date Addmission" => "submission_date",
        "Date Discharge" => "discharge_date",
        "Member ID Peserta" => "member_id",
        "Service" => "service",
        "Type of Member" => "type_of_member",
        "Provider Code" => "organization_id",
        "End Of Claim Numbers" => "code",
        "Diagnosis" => "diagnosis",
        "Tgl Billing dari RS" => "approved_final_log_at",
        "Total Billing" => "total_billing",
        "Benefit Item" => "benefit_id",
        "Amount Approval" => "amount_approval",
        "Amount Not Approval" => "amount_not_approval",
        "Total COB" => "total_cob",
        "Keterangan IGL" => "keterangan",
        "Catatan FGL" => "catatan",
        "QC 1" => "status_final_log",
        "Ingestion Code" => "ingestion_code", 
        "Ingestion Status" => "ingestion_status",

    ];

    public static $listing_doc_headers = [
        "Record Mode",
        "Date Addmission",
        "Date Discharge",
        "Member ID Peserta",
        "Service",
        "Type of Member",
        "Provider Code",
        "End Of Claim Numbers",
        "Diagnosis",
        "Tgl Billing dari RS",
        "Total Billing",
        "Benefit Item",
        "Amount Approval",
        "Amount Not Approval",
        "Total COB",
        "Keterangan IGL",
        "Catatan FGL",
        "QC 1",
        "Ingestion Code",
        "Ingestion Status",
    ];

    public static $listing_data_doc_headers = [
        "ID REQUEST LOG",
        "CODE",
        "NAME",
        "DATE OF SUBMISSION",
        "SERVICE TYPE",
        "CLAIM METHOD",
        "STATUS",
    ];


    public static $status = [
        'draft' => 'Draft',
        'requested' => 'Requested',
        'approved' => 'Approved',
        'declined' => 'Declined'
    ];

    public static $payment_types = [
        'cashless' => 'Cashless',
        'reimbursement' => 'Reimbursement'
    ];

    public $appends = [
        'payment_type_name'
    ];

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

        static::creating(function ($model) {
            try {
                $model->uuid = (string) Str::orderedUuid(); // generate uuid
                // $model->code = self::getNextCode();
            } catch (\Exception $e) {
                abort(500, $e->getMessage());
            }
        });

        static::created(function ($model) {
            // try {
            //     if (!empty($model->status) && $model->status == 'requested') {
            //         $model->histories()->create([
            //             'title' => 'New Claim Requested',
            //             'description' => "Claim Requested for Member : {$model->member->member_id} - ({$model->member->full_name})",
            //             'type' => 'info'
            //         ]);
            //     }
            // } catch (\Exception $e) {
            //     abort(500, $e->getMessage());
            // }
        });

        static::updated(function ($model) {
            if ($model->hasChanges(['status'])) {

                // if ($model->status == 'requested') {
                //     $model->histories()->create([
                //         'title' => 'New Claim Requested',
                //         'description' => "Claim Requested for Member : {$model->member->member_id} - ({$model->member->full_name})",
                //         'type' => 'info'
                //     ]);
                // }

                // if ($model->status == 'received') {
                //     ClaimReceived::dispatch($model);
                // }

                // if ($model->status == 'approved') {
                //     ClaimApproved::dispatch($model);
                // }

                // if ($model->status == 'postpone') {
                //     ClaimPostpone::dispatch($model);
                // }

                // if ($model->status == 'paid') {
                //     ClaimPaid::dispatch($model);
                // }

                // if ($model->status == 'declined') {
                //     ClaimDeclined::dispatch($model);
                // }
            }
        });
    }

    // public static function getNextCode()
    // {
    //     $last_number = self::withTrashed()->max('code');
    //     $next_number = empty($last_number) ? 1 : ((int) explode('-', $last_number)[1] + 1);

    //     return self::makeCode($next_number);
    // }

    // public static function makeCode($next_number)
    // {
    //     return (string) self::$code_prefix .'-'. str_pad($next_number, 5, 0, STR_PAD_LEFT);
    // }

    public function claim()
    {
        return $this->belongsTo(Claim::class, 'claim_id');
    }

    public function claims()
    {
        return $this->hasMany(Claim::class, 'claim_request_id');
    }

    public function files()
    {
        return $this->morphMany(File::class, 'fileable');
    }

    public function claimResults()
    {
        return $this->files()->where('type', 'claim-result')->whereNull('deleted_at');
    }

    public function claimConditions()
    {
        return $this->files()->where('type', 'claim-kondisi')->whereNull('deleted_at');
    }

    public function claimDiagnosis()
    {
        return $this->files()->where('type', 'claim-diagnosis')->whereNull('deleted_at');
    }

    public function generatedDocuments()
    {
        return $this->morphMany(GeneratedDocument::class, 'generated_documentable');
    }

    public function histories()
    {
        return $this->morphMany(ClaimHistory::class, 'historiable');
    }

    public function organization()
    {
        return $this->belongsTo(Organization::class, 'organization_id');
    }

    public function member()
    {
        return $this->belongsTo(Member::class, 'member_id', 'id');
    }

    public function service()
    {
        return $this->belongsTo(Service::class, 'service_code', 'code');
    }

    public function requestLogBenefits()
    {
        return $this->hasMany(RequestLogBenefit::class, 'request_log_id');
    }

    public function requestLogDailyMonitorings()
    {
        return $this->hasMany(RequestLogDailyMonitoring::class, 'request_log_id');
    }

    public function getPaymentTypeNameAttribute()
    {
        return self::$payment_types[$this->payment_type] ?? $this->payment_type;
    }

    public function getStatusAttribute($value)
    {
        return self::$payment_types[$value] ?? $value;
    }
}
