<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class HealthTreatment extends Model
{
    use SoftDeletes;

    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $casts = [
        'attachments' => 'array',
        'started_at' => 'datetime',
        'ended_at' => 'datetime',
        'next_visit_at' => 'date',
        'weight' => 'decimal:3',
        'progress_percent' => 'integer',
    ];

    public const STATUS_UNDER_TREATMENT = 'under_treatment';

    public const STATUS_UNDER_OBSERVATION = 'under_observation';

    public const STATUS_REMOVED = 'removed';

    public const STATUS_COMPLETED = 'completed';

    public static function statusOptions(): array
    {
        return [
            self::STATUS_UNDER_TREATMENT => 'تحت درمان',
            self::STATUS_UNDER_OBSERVATION => 'تحت نظر',
            self::STATUS_REMOVED => 'حذف شده',
            self::STATUS_COMPLETED => 'تکمیل شده',
        ];
    }

    public function project(): BelongsTo
    {
        return $this->belongsTo(Project::class);
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function producer(): BelongsTo
    {
        return $this->belongsTo(Producer::class);
    }

    public function initialReport(): BelongsTo
    {
        return $this->belongsTo(Report::class, 'initial_report_id');
    }

    public function updates(): HasMany
    {
        return $this->hasMany(HealthTreatmentUpdate::class)->latest('report_at');
    }

    public function createdBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function scopeActive($query)
    {
        return $query->whereIn('status', [
            self::STATUS_UNDER_TREATMENT,
            self::STATUS_UNDER_OBSERVATION,
        ]);
    }

    public function isActive(): bool
    {
        return in_array($this->status, [self::STATUS_UNDER_TREATMENT, self::STATUS_UNDER_OBSERVATION], true);
    }
}
