<?php

namespace Modules\ClinicCore\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * A patient's purchased treatment course. Holds N session slots; progress is
 * derived from how many sessions are 'completed'.
 */
class ClcPatientTreatmentPlan extends Model
{
    protected $table = 'clc_patient_treatment_plans';
    protected $guarded = ['id'];

    protected $casts = [
        'total_sessions' => 'integer',
        'price'          => 'decimal:2',
        'started_at'     => 'date',
    ];

    protected $appends = ['used_sessions', 'progress_pct'];

    public function patient()
    {
        return $this->belongsTo(ClcPatient::class, 'clc_patient_id');
    }

    public function package()
    {
        return $this->belongsTo(ClcTreatmentPackage::class, 'package_id');
    }

    public function sessions()
    {
        return $this->hasMany(ClcTreatmentSession::class, 'plan_id')->orderBy('session_no');
    }

    /** Completed sessions count (uses loaded relation when available). */
    public function getUsedSessionsAttribute(): int
    {
        if ($this->relationLoaded('sessions')) {
            return $this->sessions->where('status', 'completed')->count();
        }
        return $this->sessions()->where('status', 'completed')->count();
    }

    public function getProgressPctAttribute(): int
    {
        $total = max(1, (int) $this->total_sessions);
        return (int) round($this->used_sessions / $total * 100);
    }

    /** Recompute status from session completion. */
    public function refreshStatus(): void
    {
        if ($this->status === 'cancelled') return;
        $this->status = $this->used_sessions >= $this->total_sessions ? 'completed' : 'active';
        $this->save();
    }
}
