<?php

namespace App\Models\Courses;

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



class CourseEnrollment extends Model
{
    protected $fillable = [
        'user_id', 'course_id', 'price_paid', 'payment_method',
        'transaction_id', 'completed_at'
    ];

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

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

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

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

    public function review()
    {
        return $this->hasOne(CourseReview::class, 'enrollment_id');
    }

    public function hasReview()
    {
        return $this->review()->exists();
    }

    public function getProgressPercentage()
    {
        $totalLessons = $this->course->total_lessons;
        
        if ($totalLessons == 0) {
            return 0;
        }
        
        $completedLessons = $this->progress()->where('is_completed', true)->count();
        
        return round(($completedLessons / $totalLessons) * 100);
    }

    public function markAsCompleted()
    {
        if ($this->getProgressPercentage() == 100 && !$this->completed_at) {
            $this->completed_at = now();
            $this->save();
            
            return true;
        }
        
        return false;
    }
}