<?php

namespace Drupal\azure_ad\Form;

use Drupal;
use Drupal\azure_ad\Helper\moAzureADHelper;
use Drupal\azure_ad\MoAzureUtilities;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Config\Config;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Url;
use Drupal\user\Entity\User;
use Drupal\user_provisioning\Helpers\moUserProvisioningAudits;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

class MoAzureMapping 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');
    }

    /**
     * @inheritDoc
     */
    public function getFormId()
    {
        return "mo_azure_azure_audit_logs";
    }

    /**
     * @inheritDoc
     */
    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $form['mo_user_provisioning_add_css'] = array(
            '#attached' => array(
                'library' => array(
                    'user_provisioning/user_provisioning.admin',
                    'azure_ad/azure_ad.admin',
                    'core/drupal.dialog.ajax',
                )
            ),
        );

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

        $form['mo_azure_ad_mapping_back_to_drupal_to_azure_sync'] = [
            '#type' => 'submit',
            '#value' => t('&#11164; &nbsp;Back'),
            '#button_type' => 'danger',
            '#submit' => ['::moAzureProvBacktodrupaltoazuresync'],
        ];

        $form['Drupal_to_azure_sync'] = array(
            '#type' => 'fieldset',
            '#title' => 'Mapping for Drupal to Azure AD Sync',
            '#attributes' => ['class' => ['attribute_mapp'] , 'style' => 'margin: 0px;'],
        );

        $form['Drupal_to_azure_sync']['azure_ad_attribute_mapping'] = [
            '#type' => 'fieldset',
            '#title' => t('Basic Attribute Mapping<hr>'),
        ];

        $form['Drupal_to_azure_sync']['azure_ad_attribute_mapping']['azure_ad_attribute_mapping_table'] = [
            '#type' => 'table',
            '#responsive' => TRUE ,
            '#attributes' => ['class' => ['attribute_mapping_table'] , 'style' => 'border-collapse: separate;'],
        ];

        $row = $this->moAzureADAttributeMapTable();
        $form['Drupal_to_azure_sync']['azure_ad_attribute_mapping']['azure_ad_attribute_mapping_table']['attributes'] = $row;

        $form['Drupal_to_azure_sync']['azure_ad_attribute_mapping']['save'] = [
            '#type' => 'submit',
            '#value' => t('Save Configuration '),
            '#button_type' => 'primary',
        ];

        $form['Drupal_to_azure_sync']['azure_ad_custom_attribute_mapping'] = array(
            '#type' => 'fieldset',
            '#title' => t('Custom Attribute Mapping&nbsp;<a href="azure_upgrade_plans"><small>[PREMIUM]</small></a><hr>'),
        );

        $form['Drupal_to_azure_sync']['azure_ad_custom_attribute_mapping']['attribute_mapping_info'] = array(
            '#markup' => '<div class="mo_azure_highlight_background">This feature allows you to map the user attributes from your Drupal to Azure AD.</div>',
        );

        $custom_fields = [];
        $usr = User::load(\Drupal::currentUser()->id());
        $usrVal = $usr->toArray();
        foreach ($usrVal as $key => $value) {
            $custom_fields[$key] = $key;
        }

        $form['Drupal_to_azure_sync']['azure_ad_custom_attribute_mapping']['azure_ad_custom_attribute_mapping_table'] = [
            '#type' => 'table',
            '#responsive' => TRUE ,
            '#attributes' => ['class' => ['custom_attribute_mapping_table']]
        ];

        $row = $this->moAzureADCustomAttributeMapTable($custom_fields);
        $form['Drupal_to_azure_sync']['azure_ad_custom_attribute_mapping']['azure_ad_custom_attribute_mapping_table']['custom_mapping'] = $row;
        
        $azure_mapping = new MoAzureToDrupalSync();
        $azure_mapping->attributeMapping($form,$form_state);


        return $form;

    }

    public function moAzureADCustomAttributeMapTable($custom_fields){
        $row['azure_ad_drupal_attr_name'] = [
            '#title' => t('Drupal Attribute Name'),
            '#type' => 'select',
            '#options' => $custom_fields,
            '#disabled' => true,
        ];

        $row['azure_ad_attribute_name'] = [
            '#type' => 'textfield',
            '#title' => t('Azure AD Attribute Name'),
            '#disabled' => true,
        ];

        $row['azure_ad_add_button'] = [
            '#type' => 'submit',
            '#button_type' => 'primary',
            '#disabled' => true,
            '#value' => '+',
        ];

        $row['azure_ad_sub_button'] = [
            '#type' => 'submit',
            '#button_type' => 'danger',
            '#disabled' => true,
            '#value' => '-',
        ];

        return $row;
    }

    public function moAzureADAttributeMapTable(){

        $default_user_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('user', NULL);
        foreach($default_user_fields as $key => $value)
        {
            $default_user_fields[$key]=$key;   
        }

        $default_user_fields = $default_user_fields;

        $email_attr = $this->config->get('azure_ad_mapping_mail_attr');
        $username_attr = $this->config->get('azure_ad_mapping_username_attr');

        if(!isset($email_attr)){
            $this->config_factory->set('azure_ad_mapping_mail_attr', 'name')->save();
        }

        if(!isset($username_attr)){
            $this->config_factory->set('azure_ad_mapping_username_attr', 'name')->save();
        }

        $row['username_attribute'] = [
            '#type' => 'select',
            '#title' => t('Username Attribute'),
            '#options' => $default_user_fields,
            '#default_value' => $this->config->get('azure_ad_mapping_username_attr')
        ];

        $row['email_attribute'] = [
            '#type' => 'select',
            '#title' => t('Email Attribute'),
            '#options' => $default_user_fields,
            '#default_value' => $this->config->get('azure_ad_mapping_mail_attr')
        ];

        return $row;
    }


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

        $form_values = $form_state->getValues();
        
        $username_attribute = $form_values['azure_ad_attribute_mapping_table']['attributes']['username_attribute'];
        $email_attribute = $form_values['azure_ad_attribute_mapping_table']['attributes']['email_attribute'];
        
        $this->config_factory->set('azure_ad_mapping_mail_attr', $email_attribute)->save();
        $this->config_factory->set('azure_ad_mapping_username_attr', $username_attribute)->save();
        $this->messenger->addstatus(t('Configurations saved successfully.'));
    }

    public function moAzureProvBacktodrupaltoazuresync(){
        $response = new RedirectResponse(Url::fromRoute('azure_ad.configure_azure')->toString());
        $response->send();
        return new Response();
    }

}