<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;

class ValidationModel extends Model
{
    /**
     * A list of error messages, returned once the
     * validation is run.
     *
     * @var  array
     */
    public $errors;

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [];

    /**
     * Array of custom validation messages.
     *
     * @var  array
     */
    protected static $messages = [];

    /**
     * Insert the validation checks on the model.
     * The model only gets created if the validation checks pass.
     *
     * @var void
     */
    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (! $model->isValid()) {
                return false;
            }
        });

        static::updating(function ($model) {
            if (! $model->isValid()) {
                return false;
            }
        });
    }

    /**
     * Determines if the current model is valid.
     *
     * @return bool
     */
    public function isValid()
    {
        // Get a copy of the original rules
        $rules = static::$rules;

        $id = (isset($this->attributes['id'])) ? $this->attributes['id'] : 0;
        foreach (static::$rules as $key => &$value) {
            $value = str_replace('$id', $id, $value);
        }

        $validator = Validator::make($this->attributes, static::$rules, static::$messages);

        // Revert the rules back to the original state
        static::$rules = $rules;

        if ($validator->passes()) {
            return true;
        }

        $this->errors = $validator->messages();

        return false;
    }
}
