<?php

namespace App\Models;

use App\Enums\PlanItemStatus;
use App\Enums\TreatmentPlanStatus;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class TreatmentPlan extends Model
{
    use BelongsToTenant, HasFactory, SoftDeletes;

    protected $fillable = [
        'tenant_id', 'patient_id', 'dentist_id', 'title', 'status',
        'discount_amount', 'notes', 'created_by', 'completed_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => TreatmentPlanStatus::class,
            'completed_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(fn (TreatmentPlan $p) => $p->uuid ??= (string) Str::uuid());
    }

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

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

    public function items(): HasMany
    {
        return $this->hasMany(TreatmentPlanItem::class);
    }

    /** Gross total of all non-cancelled items (whole IQD). */
    public function totalGross(): int
    {
        return (int) $this->items
            ->reject(fn ($i) => $i->status === PlanItemStatus::Cancelled)
            ->sum('price');
    }

    public function totalNet(): int
    {
        return max(0, $this->totalGross() - $this->discount_amount);
    }

    public function progress(): array
    {
        $billable = $this->items->reject(fn ($i) => $i->status === PlanItemStatus::Cancelled);

        return [
            'done' => $billable->where('status', PlanItemStatus::Completed)->count(),
            'total' => $billable->count(),
        ];
    }
}
