<?php

namespace App\Models;

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

class CourseSession extends Model
{
    use HasFactory;

    protected $fillable = [
        'course_id',
        'title',
        'description',
        'session_number',
        'content',
        'materials',
        'assignments',
        'is_published',
        'duration_minutes',
    ];

    protected $casts = [
        'materials' => 'array',
        'assignments' => 'array',
        'is_published' => 'boolean',
    ];

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

    /**
     * Get all media files for this session
     */
    public function mediaFiles()
    {
        return $this->morphMany(MediaFile::class, 'uploadable');
    }

    // Helper methods
    public function getSessionName()
    {
        return "SESI {$this->session_number}";
    }

    public function isCompleted($userId)
    {
        $enrollment = $this->course->enrollments()->where('user_id', $userId)->first();
        if (!$enrollment) {
            return false;
        }

        $completedSessions = $enrollment->completed_sessions ?? [];
        return in_array($this->id, $completedSessions);
    }
}
