<?php

namespace Drupal\azure_ad\Form;

use Drupal;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Config\Config;
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\azure_ad\Helper\moAzureADHelper;
use Drupal\user_provisioning\ProviderSpecific\APIHandler\UserAPIHandler\moUserAzureAPIHandler;

class MoReviewAzureConfig extends FormBase{

    private ImmutableConfig $config;
    protected $messenger;
    private Config $config_factory;

    public function __construct()
    {
        $this->config = Drupal::config('azure_ad.settings');
        $this->messenger = Drupal::messenger();
        $this->config_factory = \Drupal::configFactory()->getEditable('azure_ad.settings');
    }

    public function getFormId() {
        return 'mo_azure_review_config';
    }

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

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


        $form['mo_azure_ad_to_drupal_library'] = [
            '#attached' => [
                'library' => [
                    'azure_ad/azure_ad.admin',
                    'azure_ad/azure_ad.update_summary_form'
                ]
            ],
        ];

        $form['azure_ad_to_drupal_header_style'] = [
            '#markup' => t('<div class="mo_azure_header_container_step1">'),
        ];

        $overview = new MoAzureOverview();
        $overview->AzureADConfigurationTable($form, $form_state, 'summary');

        if ( !empty($this->config->get('mo_azure_application_id')) && !empty($this->config->get('mo_azure_application_secret')) && !empty($this->config->get('mo_azure_tenant_id')) && !empty($this->config->get('mo_azure_tenant_name'))) {
            $result = $this->moAzureTestResultajax();
            $form['azure_test_config_result'] = $result;
        }

        $form['div_test_close'] = array(
            '#markup' => '</div>'
        );

        $form['actions'] = array('#type' => 'actions');
        $form['actions']['send'] = [
          '#type' => 'submit',
          '#value' => $this->t('Save and Test Configuration'),
          '#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();
        // If there are any form errors, AJAX replace the form.
        if ( $form_state->hasAnyErrors() ) {
            $response->addCommand(new ReplaceCommand('#modal_support_form', $form));
        } else {
            $form_values = ($form_state->getValues())['mo_configure_azure_configuration'];
            \Drupal::logger('azure_ad')->notice(print_r($form['azure_ad_summary_details']['mo_configure_azure_configuration'],true));

            $overview = new MoAzureOverview();
            $overview->moAzureStep1SaveButton($form, $form_state);
            
            $result = $this->moAzureTestResultajax($form, $form_state);
          
            $response->addCommand(new ReplaceCommand('#modal_support_form', $form));
            $response->addCommand(new ReplaceCommand('#test_config_result', $result));  
        }
        return $response;
    }

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

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

    public function moAzureTestResultajax(){
        $azure_test_data = Json::decode($this->config->get('mo_azure_attr_list_from_server'));
  
        $testresult['azure_step2_test_data'] = array(
            '#type' => 'details',
            '#title' => $this->t('Test Configuration Result'),
            '#prefix' => '<div id="test_config_result">',
            '#open' => isset($azure_test_data["error|code"])
        );

        $testresult['azure_step2_test_data']['header_message'] = [
            '#markup' => isset($azure_test_data["error|code"]) ?
                $this->t('<div style="font-family:Calibri;padding:0 3%;">
                <div style="color: #a94442;background-color: #f2dede;padding: 15px;margin-bottom: 20px;text-align:center;border:1px solid #E6B3B2;font-size:18pt;">
                    ERROR
                </div><div style="color: #a94442;font-size:14pt; margin-bottom:20px;">') :
                $this->t('<div style="font-family:Calibri;padding:0 3%;"><div style="width:95%;color: #3c763d;background-color: #dff0d8;padding: 2%;margin-bottom: 20px;text-align: center;border: 1px solid #AEDB9A;font-size: 18pt;">
                    SUCCESS
                </div>'),
        ];

        if (isset($azure_test_data['Profile Picture'])) {
            $testresult['azure_step2_test_data']['profile_picture'] = [
                '#markup' => $this->t('<div style="text-align: center;"><img width="100px" height="100px" style=" max-height: 200px; display: inline-block;" src="' . Html::escape('data:image/jpeg;base64,' . $azure_test_data['Profile Picture']) . '" alt="profile image"></div><br>'),
            ];
        }

        $testresult['azure_step2_test_data']['azure_ad_step2_show_test_data'] = [
            '#type' => 'table',
            '#responsive' => true,
            '#attributes' => ['style' => 'border-collapse: separate;', 'class' => ['mo_azure_test_data']],
        ];

        $this->config_factory->set('test_azure_config_result', isset($azure_test_data["error|code"]))->save();

        foreach ($azure_test_data as $key => $value) {
            if ($key != 'Profile Picture') {
                $overview = new MoAzureOverview();
                $row = $overview->AzureADTestConfigurationData($key, $value);
                $testresult['azure_step2_test_data']['azure_ad_step2_show_test_data'][$key] = $row;
            }
        }
        return $testresult;
    }

    
}