<?php

namespace App\Models;

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

class Course extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'description',
        'slug',
        'image',
        'level',
        'status',
        'duration_weeks',
        'price',
        'teacher_id',
        'max_students',
        'start_date',
        'end_date',
        'tags',
    ];

    protected $casts = [
        'tags' => 'array',
        'price' => 'decimal:2',
        'start_date' => 'date',
        'end_date' => 'date',
    ];

    // Auto-generate slug
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($course) {
            if (empty($course->slug)) {
                $course->slug = Str::slug($course->title);
            }
        });
    }

    // Relationships
    public function teacher()
    {
        return $this->belongsTo(User::class, 'teacher_id');
    }

    public function sessions()
    {
        return $this->hasMany(CourseSession::class)->orderBy('session_number');
    }

    public function enrollments()
    {
        return $this->hasMany(Enrollment::class);
    }

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

    public function students()
    {
        return $this->belongsToMany(User::class, 'enrollments')->withPivot('status', 'progress', 'enrolled_at', 'completed_at');
    }

    // Helper methods
    public function getEnrolledStudentsCount()
    {
        return $this->enrollments()->where('status', 'enrolled')->count();
    }

    public function isPublished()
    {
        return $this->status === 'published';
    }

    public function getProgressPercentage($userId)
    {
        $enrollment = $this->enrollments()->where('user_id', $userId)->first();
        return $enrollment ? $enrollment->progress : 0;
    }
}
