<?php

namespace Drupal\oauth_server_sso\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\oauth_server_sso\MiniorangeOAuthServerSupport;
use Drupal\oauth_server_sso\Utilities;
use Drupal\Core\Datetime\DrupalDateTime;

class MoOAuthRequestSupport extends FormBase
{
    public function getFormId() {
        return 'oauth_server_sso_request_support';
    }
    public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
        $form['#prefix'] = '<div id="modal_support_form">';
        $form['#suffix'] = '</div>';
        $form['status_messages'] = [
            '#type' => 'status_messages',
            '#weight' => -10,
        ];
        $form['markup_library'] = array(
          '#attached' => array(
            'library' => array(
              "oauth_server_sso/oauth_server_sso.style_settings",
            )
          ),
        );

        $user_email = \Drupal::config('oauth_server_sso.settings')->get('oauth_server_sso_customer_admin_email');
        $phone = \Drupal::config('oauth_server_sso.settings')->get('oauth_server_sso_customer_admin_phone');

        $form['mo_oauth_support_email_address'] = array(
          '#type' => 'email',
          '#required' => true,
          '#title' => t('Email'),
          '#default_value' => $user_email,
          '#attributes' => array('placeholder' => t('Enter your email'),'style' => 'width:99%;height:30px;margin-bottom:1%;'),
        );
        $form['mo_oauth_customer_support_method'] = [
            '#type' => 'select',
            '#title' => t('What are you looking for'),
            '#attributes' => array('style' => 'width:99%;height:30px;margin-bottom:1%;'),
            '#options' => [
                'I need Technical Support' => t('I need Technical Support'),
                'I want to Schedule a Setup Call/Demo' => t('I want to Schedule a Setup Call/Demo'),
                'I have Sales enquiry' => t('I have Sales enquiry'),
                'I have a custom requirement' => t('I have a custom requirement'),
                'My reason is not listed here' => t('My reason is not listed here'),
            ],
        ];
        $timezone = array();
        foreach (Utilities::$zones as $key => $value){
          $timezone[$value] = $key;
        }
        $form['date_and_time'] = array(
            '#type' => 'container',
            '#states' => array(
                'visible' => array(
                    ':input[name = "mo_oauth_customer_support_method"]' => array('value' => 'I want to Schedule a Setup Call/Demo')),
                )
        );
        $form['date_and_time']['miniorange_oauth_client_timezone'] = array(
            '#type' => 'select',
            '#title' => t('Select Timezone'),
            '#options' => $timezone,
            '#default_value' => 'Etc/GMT',
        );
        $form['date_and_time']['miniorange_oauth_client_meeting_time'] = array (
            '#type' => 'datetime',
            '#title' => 'Date and Time',
            '#format' => '',
            '#default_value' => DrupalDateTime::createFromTimestamp(time()),
        );
        $form['mo_oauth_support_query'] = array(
          '#type' => 'textarea',
          '#required' => true,
          '#title' => t('Query'),
          '#attributes' => array('placeholder' => t('Describe your query here!'),'style' => 'width:99%;margin-bottom:1%;'),
        );
        $form['actions'] = array('#type' => 'actions');
        $form['actions']['send'] = [
          '#type' => 'submit',
          '#value' => $this->t('Submit'),
          '#attributes' => [
            'class' => [
              'use-ajax',
              'button--primary'
            ],
          ],
          '#ajax' => [
            'callback' => [$this, 'submitModalFormAjax'],
            'event' => 'click',
          ],
        ];
        $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
        return $form;
    }

    public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
        $response = new AjaxResponse();
        $form_values = $form_state->getValues();
        $email = $form_values['mo_oauth_support_email_address'];
        // If there are any form errors, AJAX replace the form.
        if ( $form_state->hasAnyErrors() ) {
            $response->addCommand(new ReplaceCommand('#modal_support_form', $form));
        } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          \Drupal::messenger()->addMessage(t('The email address ').'<b><i>' . $email . '</i></b>'.t(' is not valid.'), 'error');
          $response->addCommand(new ReplaceCommand('#modal_support_form', $form));
        }
        else {

            $support_needed_for = $form_values['mo_oauth_customer_support_method'];
            $query = $form_values['mo_oauth_support_query'];
            $query_type = 'Contact Support';
            if($support_needed_for == 'I want to Schedule a Setup Call/Demo'){
              $timezone = $form_values['miniorange_oauth_client_timezone'];
              $mo_date = $form['date_and_time']['miniorange_oauth_client_meeting_time']['#value']['date'];
              $mo_time = $form['date_and_time']['miniorange_oauth_client_meeting_time']['#value']['time'];
              $query_type = 'Call Request';
            }

            $timezone = !empty($timezone) ? $timezone : null;
            $mo_date  = !empty($mo_date) ? $mo_date : null;
            $mo_time = !empty($mo_time) ? $mo_time : null;

            $support = new MiniorangeOAuthServerSupport($email, '', $query, $query_type, $support_needed_for,$timezone,$mo_date,$mo_time);
            $support_response = json_decode($support->sendSupportQuery(), true);

            if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) {
                global $base_url;
                $current_path = explode($base_url, $_SERVER['HTTP_REFERER']);
                $url_object = \Drupal::service('path.validator')->getUrlIfValid($current_path[1]);
                $route_name = $url_object->getRouteName();
            } else {
                $route_name = 'oauth_server_sso.config_client';
            }

            if(isset($support_response['status']) && $support_response['status'] == "SUCCESS"){
              \Drupal::messenger()->addStatus(t('Support query successfully sent. We will get back to you shortly.'));
            }else{
              \Drupal::messenger()->addError(t('Error sending Support query. Please reach out to ').'<a target="_blank" href="mailto:drupalsupport@xecurify.com">drupalsupport@xecurify.com</a>');
            }

            $response->addCommand(new RedirectCommand(Url::fromRoute($route_name)->toString()));
        }
        return $response;
    }

    public function validateForm(array &$form, FormStateInterface $form_state) { }

    public function submitForm(array &$form, FormStateInterface $form_state) { }

}
