<?php

namespace App\Models\Courses;

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


class CourseProgress extends Model
{
    protected $fillable = [
        'enrollment_id', 'lesson_id', 'is_completed',
        'progress_percentage', 'last_accessed_at', 'completed_at'
    ];

    protected $casts = [
        'is_completed' => 'boolean',
        'last_accessed_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    public function enrollment()
    {
        return $this->belongsTo(CourseEnrollment::class);
    }

    public function lesson()
    {
        return $this->belongsTo(CourseLesson::class);
    }

    public function markAsCompleted()
    {
        if (!$this->is_completed) {
            $this->is_completed = true;
            $this->progress_percentage = 100;
            $this->completed_at = now();
            $this->save();
            
            // Check if course is completed
            $this->enrollment->markAsCompleted();
            
            return true;
        }
        
        return false;
    }

    public function updateLastAccessed()
    {
        $this->last_accessed_at = now();
        $this->save();
    }
}