<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Enrollment extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'course_id',
        'status',
        'progress',
        'completed_sessions',
        'enrolled_at',
        'completed_at',
    ];

    protected $casts = [
        'completed_sessions' => 'array',
        'enrolled_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    // Relationships
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function course()
    {
        return $this->belongsTo(Course::class);
    }

    // Helper methods
    public function markSessionCompleted($sessionId)
    {
        $completedSessions = $this->completed_sessions ?? [];
        if (!in_array($sessionId, $completedSessions)) {
            $completedSessions[] = $sessionId;
            $this->completed_sessions = $completedSessions;

            // Update progress
            $totalSessions = $this->course->sessions()->count();
            $this->progress = $totalSessions > 0 ? (count($completedSessions) / $totalSessions) * 100 : 0;

            // Mark as completed if all sessions are done
            if ($this->progress >= 100) {
                $this->status = 'completed';
                $this->completed_at = now();
            }

            $this->save();
        }
    }

    public function isCompleted()
    {
        return $this->status === 'completed';
    }
}
