<?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;

class MoOAuthRequestDemo extends FormBase{
    public function getFormId() {
        return 'oauth_server_sso_request_demo';
    }

    public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {

        $form['#prefix'] = '<div id="modal_example_form">';
        $form['#suffix'] = '</div>';
        $form['status_messages'] = [
            '#type' => 'status_messages',
            '#weight' => -10,
        ];

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

        $form['mo_oauth_trial_email_address'] = array(
            '#type' => 'email',
            '#required' => true,
            '#title' => t('Email'),
            '#default_value' => $user_email,
            '#attributes' => array('placeholder' => t('Enter your email')),
        );

        $form['mo_oauth_number_of_users'] = array(
            '#type' => 'number',
            '#title' => $this->t('Number of users'),
            '#attributes' => ['style' => 'width: 82%;'],
            '#required'=>TRUE,
            '#default_value' => 100,
            '#min' => 25,
            '#description' => $this->t('The "Number of users" is the users who will be using the SSO service, not the number of users present on your Drupal site.')
        );

        $form['mo_oauth_server_oauth_client_name'] = array(
            '#type' => 'textfield',
            '#title' => $this->t('OAuth Client Name'),
            '#description' => $this->t('The application name where you want to login using SSO service.')
        );

        $form['mo_oauth_trial_description'] = array(
            '#type' => 'textarea',
            '#rows' => 4,
            '#required' => true,
            '#title' => t('Description'),
            '#attributes' => array('placeholder' => t('Describe your use case here!')),
        );

        $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_trial_email_address'];
        // If there are any form errors, AJAX replace the form.
        if ( $form_state->hasAnyErrors() ) {
            $response->addCommand(new ReplaceCommand('#modal_example_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_example_form', $form));
        }else {
            $query = $form_values['mo_oauth_trial_description'];

            $query_content = '<strong>Number of Users: </strong>' . $form_values['mo_oauth_number_of_users'];
            $query_content .= '<br><br><strong>OAuth Client Name: </strong>' . $form_values['mo_oauth_server_oauth_client_name'];
            $query .= "<br><br>Usecase Details:<br><pre style=\"border:1px solid #444;padding:10px;\"><code>" . $query_content . "</code></pre>";
            $query_type = 'Trial Request';

            $support = new MiniorangeOAuthServerSupport($email, '', $query, $query_type);
            $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('Success! Trial query successfully sent. We will send you an email including the steps to activate the trial shortly. Please check your inbox for further instructions.'));
            }else{
                \Drupal::messenger()->addError(t('Error sending Trial Request. 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) { }

}
