<?php

namespace Drupal\ajax_form\Form;

use Drupal\Core\Ajax\AjaxResponse;
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;

class AjaxForm extends FormBase {

  public function getFormId() {
    return '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',
      '#attributes' => [
        'name' => 'site'
      ],
      '#default_value' => 'noSite',
      '#options' => array(
        'hasSite' => t('У меня есть сайт'),
        'noSite' => t('У меня нету сайта'),
      ),
      '#ajax' => [
        'callback' => '::clearField',
        'event' => 'change',
      ]
    );

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

  public function clearField(&$form, $form_state) {
    $response = new AjaxResponse();
    if (empty($form['custom_errors']['url'])) {
      $this->clearRedField('url', $response);
    }
    return $response;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    $url = $form_state->getValue('url');
    $email = $form_state->getValue('email');
    $site = $form_state->getValue('site');
    $name = $form_state->getValue('name');

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

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

  public function checkUrl($url, $value = null) {
    $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);
    }

    if ($value = 1) {
      return $url;
    }

    $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) {
    $response = new AjaxResponse();
    $uid = \Drupal::currentUser()->id();
    if ($uid) {
      $user = \Drupal::entityTypeManager()->getStorage('user')->load($uid);
      $name = $user->get('field_name')->getValue();
      $surname = $user->get('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['#content'] = $msg;
    $content['#theme'] = 'mymodule_example_first';

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

  public function redFiled($key, $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) {
    $response->addCommand(new HtmlCommand(".$key-validation-message", ''));
    $response->addCommand(new CssCommand("#edit-$key", ['border' => '']));
  }
}
