<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PatientPackage extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'patient_id',
        'package_id',
        'total_sessions',
        'remaining_sessions',
        'start_date',
        'end_date',
        'status',
    ];

    protected $casts = [
        'total_sessions' => 'integer',
        'remaining_sessions' => 'integer',
        'start_date' => 'date',
        'end_date' => 'date',
    ];

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

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

    public function consumeSession(): bool
    {
        if ($this->remaining_sessions > 0 && $this->status === 'active') {
            $this->remaining_sessions--;
            if ($this->remaining_sessions === 0) {
                $this->status = 'completed';
            }
            $this->save();
            return true;
        }
        return false;
    }
}
