<?php

namespace App\Models\Courses;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;




class CourseLesson extends Model
{
    protected $fillable = [
        'section_id', 'title', 'description', 'duration', 'video_url',
        'content', 'attachment', 'is_free', 'is_published', 'sort_order'
    ];

    protected $casts = [
        'is_free' => 'boolean',
        'is_published' => 'boolean',
    ];

    public function section()
    {
        return $this->belongsTo(CourseSection::class);
    }

    public function progress()
    {
        return $this->hasMany(CourseProgress::class, 'lesson_id');
    }

    public function questions()
    {
        return $this->hasMany(CourseQuestion::class, 'lesson_id');
    }

    public function getFormattedDuration()
    {
        $hours = floor($this->duration / 60);
        $minutes = $this->duration % 60;
        
        if ($hours > 0) {
            return $hours . 'h ' . $minutes . 'm';
        }
        
        return $minutes . 'm';
    }

    public function getCourse()
    {
        return $this->section->course;
    }

    public function isCompleted($userId)
    {
        $enrollment = CourseEnrollment::where('user_id', $userId)
            ->where('course_id', $this->section->course_id)
            ->first();
            
        if (!$enrollment) {
            return false;
        }
        
        return CourseProgress::where('enrollment_id', $enrollment->id)
            ->where('lesson_id', $this->id)
            ->where('is_completed', true)
            ->exists();
    }
}