<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Enrollment extends Model
{
    protected $guarded = [];

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

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

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

    public function syncProgress(): void
    {
        $total = $this->course->lessons()->count();

        if ($total === 0) {
            return;
        }

        $done = $this->user->completedLessons()
            ->whereIn('lessons.id', $this->course->lessons()->pluck('lessons.id'))
            ->count();

        $this->progress = (int) round($done / $total * 100);

        if ($this->progress >= 100 && ! $this->completed_at) {
            $this->status = 'completed';
            $this->completed_at = now();
        }

        $this->save();
    }
}
