<?php

namespace App\Models;

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

class ScheduledTask extends Model
{
    use HasFactory;
    use SoftDeletes;
    protected $primaryKey = 'id';
    protected $connection = 'mysql';

    protected $fillable = [
        'title',
        'subject',
        'body',
        'frequency',
        'begin_date',
        'end_date',
        'sending_time',
        'sending_weekly_day',
        'sending_monthly_day',
        'month_last_day',
        'last_sending_datetime',
        'last_status',
        'next_sending_date',
        'send_to_admins',
        'retry_count',
        'recieved_users',
        'worked_now',
        'created_by',
        'edited_by',
        'deleted_by',
    ];

    protected $casts = [
        'recieved_users' => 'array',
    ];


    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $prefix = config('srm_config.installer.table_prefix', 'srm_');
        $this->table = "{$prefix}scheduled_tasks";
    }

    public static function tableName()
    {
        return with(new static())->getTable();
    }

    public function taskHistory()
    {
        return $this->hasMany(ScheduledTaskHistory::class, 'task_id');
    }

    public function groups()
    {
        return $this->hasMany(ScheduledTaskGroup::class, 'task_id');
    }


    public function resources()
    {
        return $this->hasMany(ScheduledTaskResource::class, 'task_id');
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by')->withDefault(function () {
            return [];
        });
    }

    public function editedBy()
    {
        return $this->belongsTo(User::class, 'edited_by')->withDefault(function () {
            return [];
        });
    }

}
