<?php

namespace App\Models;

use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Course extends Model
{
    protected $fillable = [
        'title',
        'description',
        'category_id',
        'teacher_id',
        'status',
        'start_date',
        'expire_date',
    ];

    protected $casts = [
        'status' => 'string',
        'start_date' => 'date',
        'expire_date' => 'date',
    ];

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

    public function teacher(): BelongsTo
    {
        return $this->belongsTo(User::class, 'teacher_id');
    }

    public function enrollments(): HasMany
    {
        return $this->hasMany(CourseEnrollment::class);
    }

    public function assignments(): HasMany
    {
        return $this->hasMany(Assignment::class);
    }

    public function lectures(): HasMany
    {
        return $this->hasMany(Lecture::class);
    }

    public function analytics(): HasOne
    {
        return $this->hasOne(Analytics::class);
    }

    public function chats(): HasMany
    {
        return $this->hasMany(Chat::class);
    }

    public function isExpired(?CarbonInterface $date = null): bool
    {
        if (! $this->expire_date) {
            return false;
        }

        $compareDate = ($date ?? now())->copy()->startOfDay();

        return $this->expire_date->copy()->startOfDay()->lt($compareDate);
    }

    public function isWithinScheduledWindow(?CarbonInterface $date = null): bool
    {
        $compareDate = ($date ?? now())->copy()->startOfDay();

        if ($this->start_date && $this->start_date->copy()->startOfDay()->gt($compareDate)) {
            return false;
        }

        return ! $this->isExpired($compareDate);
    }


}
