<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class LmsAssignment extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'course_id',
        'title',
        'description',
        'instructions',
        'attachment_url',
        'due_date',
        'max_marks',
        'passing_marks',
        'allow_late_submission',
        'late_submission_penalty',
        'is_published',
    ];

    protected $casts = [
        'due_date' => 'datetime',
        'max_marks' => 'decimal:2',
        'passing_marks' => 'decimal:2',
        'allow_late_submission' => 'boolean',
        'late_submission_penalty' => 'decimal:2',
        'is_published' => 'boolean',
    ];

    // Relationships
    public function course()
    {
        return $this->belongsTo(LmsCourse::class, 'course_id');
    }

    public function submissions()
    {
        return $this->hasMany(LmsSubmission::class, 'assignment_id');
    }

    // Scopes
    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    public function scopeForCourse($query, $courseId)
    {
        return $query->where('course_id', $courseId);
    }

    public function scopeUpcoming($query)
    {
        return $query->where('due_date', '>', now());
    }

    public function scopeOverdue($query)
    {
        return $query->where('due_date', '<', now());
    }

    // Accessors
    public function getIsOverdueAttribute()
    {
        return $this->due_date < now();
    }

    public function getSubmissionCountAttribute()
    {
        return $this->submissions()->count();
    }
}
