<?php

namespace App\Domain\Training\Models;

use App\Domain\Financial\Models\Invoice;
use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Domain\Training\Enums\EnrollmentStatus;
use App\Domain\Training\Enums\PaymentStatus;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Enrollment extends Model
{
    use BelongsToAcademy, HasUuid, Auditable;

    protected $fillable = [
        'academy_id', 'participant_id', 'training_group_id', 'training_program_id',
        'enrollment_date', 'start_date', 'end_date',
        'status', 'enrolled_by', 'invoice_id',
        'payment_status', 'sessions_attended', 'sessions_total',
        'attendance_percentage', 'completion_percentage',
        'withdrawal_date', 'withdrawal_reason', 'transferred_to_id',
        'notes', 'metadata',
    ];

    protected $casts = [
        'status' => EnrollmentStatus::class,
        'payment_status' => PaymentStatus::class,
        'enrollment_date' => 'date',
        'start_date' => 'date',
        'end_date' => 'date',
        'withdrawal_date' => 'date',
        'sessions_attended' => 'integer',
        'sessions_total' => 'integer',
        'attendance_percentage' => 'decimal:2',
        'completion_percentage' => 'decimal:2',
        'metadata' => 'array',
    ];

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

    public function group(): BelongsTo
    {
        return $this->belongsTo(TrainingGroup::class, 'training_group_id');
    }

    public function program(): BelongsTo
    {
        return $this->belongsTo(TrainingProgram::class, 'training_program_id');
    }

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

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

    public function transferredTo(): BelongsTo
    {
        return $this->belongsTo(TrainingGroup::class, 'transferred_to_id');
    }

    public function scopeActive($query)
    {
        return $query->where('status', EnrollmentStatus::Active);
    }
}
