<?php

namespace Drupal\materio_expo\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
// use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;

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

  /**
   * {@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');
    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['email'] = [
        '#type' => 'email',
        // '#title' => $this->t('Email'),
        '#attributes' => [
          'placeholder' => $this->t('Email')
        ],
        '#weight' => '0',
      ];
      
      $form['ref'] = [
        '#type' => 'hidden',
        '#value' => $ref
      ];
  
      $form['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t("Submit"),
      ];
      return $form;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@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['mail'] = $values['mail'];
    $params['message'] = $values['mail'];
    $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_getfile', ['ref'=>$ref]);

  }

}
