<?php

namespace App\Models;

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

class IssueTask extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'issue_id', 'title', 'is_done', 'done_at', 'done_by',
        'assigned_to', 'due_date', 'order', 'overdue_notified_at',
        'uuid', 'client_updated_at',
    ];

    protected $casts = [
        'is_done' => 'boolean',
        'done_at' => 'datetime',
        'due_date' => 'date',
        'overdue_notified_at' => 'datetime',
    ];

    /** Tasks that are past their due date and not yet completed. */
    public function scopeOverdue($q)
    {
        return $q->where('is_done', false)
            ->whereNotNull('due_date')
            ->whereDate('due_date', '<', now()->toDateString());
    }

    public function issue()
    {
        return $this->belongsTo(Issue::class);
    }

    public function assignee()
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

    public function completer()
    {
        return $this->belongsTo(User::class, 'done_by');
    }

    public function media()
    {
        return $this->morphMany(Media::class, 'mediable');
    }

    /** Overdue = has a due date in the past and not yet done. */
    public function getIsOverdueAttribute(): bool
    {
        return ! $this->is_done && $this->due_date && $this->due_date->isPast();
    }
}
