<?php

namespace App\Models;

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

class Claim extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'member_id',
        'diagnosis_id',
        'total_claim',
        'currency',
        'plan_id',
        'benefit_id',
        'status',
        'requested_at',
        'requested_by',
        'received_at',
        'received_by',
        'approved_at',
        'approved_by',
        'declined',
        'declined_by',
        'paid_at',
        'paid_by',
    ];

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

    public static $status = [
        'draft' => 'Draft',
        'requested' => 'Requested',
        'received' => 'Received',
        'approved' => 'Approved',
        'paid' => 'Paid',
        'declined' => 'Declined'
    ];
    
    protected static function boot()
    {
        parent::boot();

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

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

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

    public function diagnosis()
    {
        return $this->belongsTo(Icd::class, 'diagnosis_id');
    }

    public function plan()
    {
        return $this->belongsTo(Plan::class, 'plan_id');
    }

    public function benefit()
    {
        return $this->belongsTo(Benefit::class, 'benefit_id');
    }

    public function scopeUsed($query, $startDate, $endDate)
    {
        return $query
                ->whereIn('status', ['approved', 'paid'])
                ->whereBetween('requested_at', [$startDate, $endDate]);
    }
    
}
