<?php

namespace Webuccino\Install\Http\Forms;

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

class ProfileForm
{
    protected $errors = [];

    public $attributes;

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

        if (!Validator::email($attributes['email'])) {
            $this->errors['email'] = 'Please Enter a Unique and valid email address';
        }

        if (!Validator::not_exists($attributes['email'], 'Users', 'Email')) {
            $this->errors['email'] = 'Please Enter a Unique and valid email address';
        }

        //username validations

        if (!Validator::string($attributes['username'])) {
            $this->errors['username'] = 'Please Enter a Unique and valid Username';
        }

        if (!Validator::not_exists($attributes['username'], 'Users', 'user_name')) {
            $this->errors['username'] = 'Please Enter a Unique and valid Username';
        }

        //password validations

        if (!Validator::complex($attributes['password'])) {
            $this->errors['password'] = 'Please enter a valid password. A valid password should have at least one uppercase letter, at least one lowercase letter, at least one digit, and it should be between 8 and 16 characters in length.';
        }

        if (!Validator::equal($attributes['password'], $attributes['confirmpassword'])) {
            $this->errors['confirmpassword'] = 'The confirmed password does not match the password.';
        }

        //security questions validations

        if (!Validator::numeric($attributes['security_question'])) {
            $this->errors['security_question'] = 'Choose valid Security Question';
        }

        //security answers validations


        if (!Validator::string($attributes['security_answer'])) {
            $this->errors['security_answer'] = 'Answer to security question can\'t be empty';
        }
    }

    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;
    }
}
