<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Ajax\CssCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Url;
use Drupal\redirect\Entity\Redirect;

class AjaxForm extends FormBase {

  public $response;

  public function getFormId() {
    return 'mymodule_ajax_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => 'Name',
      '#prefix' => '',
      '#suffix' => '<div class="name-validation-message"></div>',
    );

    $form['email'] = array(
      '#type' => 'email',
      '#title' => 'Email',
      '#prefix' => '',
      '#suffix' => '<div class="email-validation-message"></div>',
    );

    $form['url'] = array(
      '#type' => 'textfield',
      '#title' => 'URL',
      '#prefix' => '',
      '#suffix' => '<div class="url-validation-message"></div>',
      '#states' => array(
        'visible' => array(
          ':input[name="site"]' => ['value' => 'hasSite'],
        ),
      ),
    );

    $form['site'] = array(
      '#type' => 'radios',
      '#description' => t('Select'),
      '#attributes' => [
        'name' => 'site'
      ],
      '#default_value' => 'noSite',
      '#options' => array(
        'hasSite' => t('У меня есть сайт'),
        'noSite' => t('У меня нету сайта'),
      )
    );

    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Click',
      '#ajax' => [
        'callback' => '::alert',
        'event' => 'click',
      ],
    );
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    $this->response = new AjaxResponse();

    $url = $form_state->getValue('url');
    $email = $form_state->getValue('email');
    $site = $form_state->getValue('site');
    $name = $form_state->getValue('name');

    if (empty($name)) {
      $form['errorsCustom']['name'] = 'name';
    }
    if (!$this->checkEmail($email)) {
      $form['errorsCustom']['email'] = 'email';
    }
    if ($site == 'hasSite') {
      if (!$this->checkUrl($url) or empty($url)) {
        $form['errorsCustom']['url'] = 'url';
      }
    }
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $query = \Drupal::database()->insert('AAA_custom_table');
    $query->fields([
      'name' => $form_state->getValue('name'),
      'email' => $form_state->getValue('email'),
      'url' => $form_state->getValue('url'),
    ]);
    $query->execute();
  }

  public function checkUrl($url) {
    $regexp = '/^(https|http):\/\//';
    $checkHttp = (bool)preg_match($regexp, $url);
    if ($checkHttp) {
      $url[4] == 's' ? $httpOrHttps = 8 : $httpOrHttps = 7;
      $checkHttp ? $url = substr($url, $httpOrHttps) : '';
    }

    $regexp = '/^www./';
    $checkWww = ((bool)preg_match($regexp, $url));
    if ($checkWww) {
      $url = substr($url, 4);
    }

    $regexp = '/^([a-z0-9]*.[rр][uф])/';
    $checkUrl = (bool)preg_match($regexp, $url);

    $url = explode('.',$url);
    $url = $url[0] . '.' . $url[1];
    if ($checkUrl) {
      return true;
    } else {
      return false;
    }
  }

  public function checkEmail($email) {
    $email_valid = filter_var($email, FILTER_VALIDATE_EMAIL);
    if ($email_valid and !empty($email)) {
      return true;
    } else {
      return false;
    }
  }

  public function alert(array &$form, FormStateInterface $form_state) {
    $uid = \Drupal::currentUser()->id();
    if ($uid) {
      $user = \Drupal::entityTypeManager()->getStorage('user')->load($uid);
      $name = $user->field_name->getValue();
      $surname = $user->field_surname->getValue();
      !empty($surname) ? $name = $name[0]['value'] . " " . $surname[0]['value'] : $name = $name[0]['value'];
    } else {
      $name = 'анонимный пользователь';
    }

    $config = config_pages_config('model_window');
    $field_title = $config->get('field_header')->getValue();
    $field_content = $config->get('field_content')->getValue();

    if (empty($field_title[0]['value'])) {
      $title = 'Сообщение';
    } else {
      $title = $field_title[0]['value'];
    }

    if (empty($field_content[0]['value'])) {
      $msg = "Привет, $name";
    } else {
      $msg = $field_content[0]['value'];
    }

    $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $content['#context']['content'] = $msg;
    $content['#theme'] = 'mymodule_example_first';

    $response = $this->response;

    if (empty($form['errorsCustom'])) {
      $commandRedirect = new RedirectCommand('/home');
      /*$response = new AjaxResponse();*/
      $response->addCommand(new OpenModalDialogCommand($title, $content, ['width' => '400', 'height' => '400']));
      $response->addCommand($commandRedirect);
    } else {
      $this->clearRedField('name');
      $this->clearRedField('email');
      $this->clearRedField('url');
      foreach ($form['errorsCustom'] as $key => $value) {
        $this->redFiled($key);
      }
    }

    return $response;
  }

  public function redFiled($key) {
    $response = $this->response;
    $response->addCommand(new HtmlCommand(".$key-validation-message", "Введен не корректный $key"));
    $response->addCommand(new CssCommand(".$key-validation-message", ['color' => 'red']));
    $response->addCommand(new CssCommand("#edit-$key", ['border' => '1px solid red']));

  }

  public function clearRedField($key) {
    $response = $this->response;
    $response->addCommand(new HtmlCommand(".$key-validation-message", ''));
    $response->addCommand(new CssCommand("#edit-$key", ['border' => '']));
  }
}
