<?php

namespace Drupal\materio_expo\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Egulias\EmailValidator\EmailValidator;

/**
 * Class GetEmail.
 */
class GetEmail extends FormBase {

 /**
   * The email validator.
   *
   * @var \Egulias\EmailValidator\EmailValidator
   */
  protected $emailValidator;

  /**
   * Constructs 
   *
   * @param \Egulias\EmailValidator\EmailValidator $email_validator
   *   The email validator.
   */
  public function __construct(EmailValidator $email_validator) {
    $this->emailValidator = $email_validator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('email.validator'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'get_email';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $ref = null) {
    
    // check if email cookie is already present
    // $session = \Drupal::request()->getSession();
    // $alreadysetemail = $session->get('materio_expo_email');
    $alreadysetemail = \Drupal::request()->cookies->get('materio_expo_email', false);
    if($alreadysetemail){
      // https://x-team.com/blog/drupal-goto/
      $url = Url::fromRoute('materio_expo.qr_controller_getfile', ['ref'=>$ref], ['absolute' => TRUE]);
      return new RedirectResponse($url->toString());
    }else{
      $form['heading'] = [
        '#type' => 'html_tag',
        '#tag' => 'h3',
        '#value' => $this->t("Thank you for stopping by at matériO's bOOth."),
        '#weight' => '0',
      ];

      $form['welcome'] = [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this->t("In order to visualize the information of the exhibited materials, could you indicate your e-mail address?"),
        '#weight' => '1',
      ];

      $form['email'] = [
        '#type' => 'email',
        // '#title' => $this->t('Email'),
        '#attributes' => [
          'placeholder' => $this->t('Email')
        ],
        '#weight' => '2',
      ];
      
      $form['ref'] = [
        '#type' => 'hidden',
        '#value' => $ref
      ];
      
      $form['actions'] = [
        '#type' => 'container',
        '#weight' => '3',
      ];

      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t("Go!")
      ];

      return $form;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $values = $form_state->getValues();
    if (!$this->emailValidator->isValid($values['email'])) {
      $form_state->setErrorByName('email',
        $this->t('%email is an invalid email address.', [
          '%email' => $values['email'],
        ])
      );
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    //* send form submission by email
    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'materio_expo';
    $key = 'expo_getmail_submitted';
    $to = \Drupal::config('system.site')->get('mail');
    $params['email'] = $values['email'];
    $params['message'] = $values['email'];
    $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $send = true;

    $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
    if ($result['result'] !== true) {
      $logger = \Drupal::logger('flag_lists');
      $logger->error('There was a problem sending your message.' . $values['mail']);
    }

    //* record email as session variable
    // https://drupal.stackexchange.com/questions/197576/storing-data-session-for-anonymous-user
    $session = \Drupal::request()->getSession();
    $session->set('materio_expo_email', true);

    //* redirect to getfile controller
    $ref = $values['ref'];
    $form_state->setRedirect('materio_expo.qr_controller_setcookie', ['ref'=>$ref]);

  }

}
