<?php

namespace App\Modules\Workflow;

use App\Models\ValidationModel;
use App\Modules\Workflow\WorkflowAction;

class WorkflowEvent extends ValidationModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'workflow_events';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['model', 'event', 'filters', 'active'];

    /**
     * Setter for the filters attribute. It automatically encodes the value passed
     * as a json array to be stored in the database.
     *
     * @param $value - an array that will be converted to JSON
     *
     * @return null
     */
    public function setFiltersAttribute($value)
    {
        $this->attributes['filters'] = json_encode($value);
    }

    /**
     * Getter for the filters attribute. It converts a JSON string fetched from the database
     * to an stdClass object.
     *
     * @return stdClass
     */
    public function getFiltersAttribute()
    {
        return json_decode($this->attributes['filters']);
    }

    /**
     * Returns all the actions that this event has linked to.
     *
     * @return Illuminate\Support\Collection
     */
    public function actions()
    {
        return $this->hasMany(WorkflowAction::class);
    }

    public function active_actions()
    {
        return $this->hasMany(WorkflowAction::class)->condition(1);
    }

    public function inactive_actions()
    {
        return $this->hasMany(WorkflowAction::class)->condition(0);
    }
}
