<?php

namespace Webuccino\Install\Http\Forms;

use Webuccino\Install\Core\Validator;
use Webuccino\Install\Core\ValidationException;

class EmailForm
{
    protected $errors = [];

    public $attributes;

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;

        if (!Validator::string($attributes['timezone'])) {
            $this->errors['timezone'] = 'Please select a time zone. This time zone will be utilized throughout the system, particularly in any scheduled processes.';
        }

        if (!Validator::string($attributes['email'])) {
            $this->errors['email'] = 'Please enter a valid email in the "From Email" field. All emails sent from Smart Report Maker will have this email address as the "From" and "Reply To" address.';
        }

        if (!Validator::email($attributes['email'])) {
            $this->errors['email'] = 'Please enter a valid email in the "From Email" field. All emails sent from Smart Report Maker will have this email address as the "From" and "Reply To" address.';
        }

        if (!Validator::string($attributes['name'])) {
            $this->errors['name'] = 'Please enter a valid text in the "From Name" field. This name provides a recognizable sender identity to your recipients. For example, you can use your company name.';
        }

        if (!Validator::min($attributes['mail-signature'])) {
            $this->errors['mail-signature'] = 'Please enter a valid signature in the "Mail signature" field. This text will be included at the end of all email notifications sent by the system.';
        }

        if (!Validator::max($attributes['mail-signature'], 255)) {
            $this->errors['mail-signature'] = 'Mail signature should be 255 characters or less';
        }

    }

    public static function validate($attributes)
    {
        $instance = new static($attributes);

        return $instance->failed() ? $instance->throw() : $instance;
    }

    public function throw()
    {
        ValidationException::throw($this->errors(), $this->attributes);
    }

    public function failed()
    {
        return count($this->errors);
    }

    public function errors()
    {
        return $this->errors;
    }

    public function error($field, $message)
    {
        $this->errors[$field] = $message;

        return $this;
    }

}
