<?php

namespace Drupal\azure_ad\Form;

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

class MoAzureToDrupalSync extends FormBase
{
    private Config $config_factory;

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

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

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

        if(!isset($_COOKIE['request_trial']))
        {
            setrawcookie('request_trial', 'true', \Drupal::time()->getRequestTime() + 172800, '/');
            echo"<script type='text/javascript'>
            function showtrialform() {
                var url = window.location.pathname;
                url = url.replace('azure_to_drupal_configure', 'requestTrialAzure');
                console.log(url);
                var button = document.getElementById('trial');
                button.click();
            }
             setTimeout(showtrialform, 5000);
            </script>";
        }
         
        $form['azure_ad_to_drupal_header_style'] = [
            '#markup' => t('<div class="mo_azure_header_container_step1">'),
        ];

        $form['azure_ad_to_drupal_back_to_overview'] = array(
            '#type' => 'submit',
            '#value' => t('&#11164; &nbsp;Back to Overview'),
            '#attributes' => ['class' => ['button', 'button--danger']],
            '#submit' => ['::moAzureBackToOverview'],
        );

        $this->AzureADDrupalProvisioning($form, $form_state);

        $form['azure_ad_to_drupal_header_end'] = [
            '#markup' => t('</div>'),
        ];

        $azure_ad_helper = new moAzureADHelper();
        $azure_ad_helper->moAzureShowCustomerSupportIcon($form, $form_state);

        return $form;
    }

    /**
     * @inheritDoc
     */
    public function submitForm(array &$form, FormStateInterface $form_state){}

    private function AzureADDrupalProvisioning(array &$form, FormStateInterface $form_state){

        $form['mo_azure_ad_provisioning_fieldset'] = [
            '#type' => 'fieldset',
            '#title' => t('Manual Provisioning Configuration <a href="azure_upgrade_plans"><small>[PREMIUM]</small></a> <hr>'),
        ];

        $form['mo_azure_ad_provisioning_fieldset']['automatic_provisioning_choose_operations'] = [
            '#type' => 'fieldset',
            '#title' => t('Choose Operations in Manual Provisioning<hr>'),
        ];

        $form['mo_azure_ad_provisioning_fieldset']['automatic_provisioning_choose_operations']['azure_ad_provisioning_operations'] = [
            '#type' => 'table',
            '#responsive' => true,
        ];

        $row = $this->moProvisioningOperations();
        $form['mo_azure_ad_provisioning_fieldset']['automatic_provisioning_choose_operations']['azure_ad_provisioning_operations']['operations'] = $row;

        $form['mo_azure_ad_provisioning_fieldset']['create_user_fieldset']=[
            '#type' => 'fieldset',
            '#title' => $this->t('Sync Users<hr>'),
        ];

        $form['mo_azure_ad_provisioning_fieldset']['create_user_fieldset']['mo_azure_drupal_username'] = [
            '#type' => 'textfield',
            '#attributes' => ['placeholder' => 'Search Azure AD username of user to sync'],
            '#autocomplete_route_name' => 'user_provisioning.autocomplete',
            '#disabled' => true,
            '#prefix' => '<p class="mo_azure_highlight_background"><strong>Note:</strong> Search the username of user present in Azure AD to sync it to the Drupal.</p><div class="container-inline">',
        ];

        $form['mo_azure_ad_provisioning_fieldset']['create_user_fieldset']['mo_azure_sync_button'] = [
            '#type' => 'submit',
            '#value' => t('Sync'),
            '#button_type' => 'primary',
            '#attributes' => ['class' => ['mo_azure_sync_button']],
            '#disabled' => true,
        ];

        $form['mo_azure_ad_provisioning_fieldset']['create_user_fieldset']['mo_azure_sync_all_button'] = [
            '#type' => 'submit',
            '#value' => t('Sync All Users'),
            '#button_type' => 'primary',
            '#attributes' => ['class' => ['mo_azure_sync_all_button']],
            '#disabled' => true,
        ];

        $form['mo_azure_ad_automatic_provisioning_fieldset'] = [
            '#type' => 'fieldset',
            '#title' => t('Automatic Provisioning Configuration <a href="azure_upgrade_plans"><small>[PREMIUM]</small></a><hr>'),
        ];

        $form['mo_azure_ad_automatic_provisioning_fieldset']['auto_prov_note'] = [
            '#markup' => '<p class="mo_azure_highlight_background">Azure AD / B2C to Drupal user sync can be scheduled at a specific time interval. This will create / update the users automatically after the time specified in the <strong>Enable Automatic User Creation</strong> field. Number of users synced per request can be configured here in the <strong>Number of User Records/Request</strong> textfield.</p>',
        ];

        $form['mo_azure_ad_automatic_provisioning_fieldset']['create_user_fieldset'] = [
            '#type' => 'fieldset',
            '#title' => $this->t('Sync Users<hr>'),
        ];

        $form['mo_azure_ad_automatic_provisioning_fieldset']['create_user_fieldset']['enable_auto_creation'] = [
            '#type' => 'checkbox',
            '#title' => t('Enable Automatic User Creation'),
            '#disabled' => true,
        ];

        $form['mo_azure_ad_automatic_provisioning_fieldset']['create_user_fieldset']['records_number'] = [
            '#type' => 'number',
            '#title' => t('Number of User Records/Request'),
            '#disabled' => true,
        ];

        $form['mo_azure_ad_automatic_provisioning_fieldset']['create_user_fieldset']['auto_creation'] = [
            '#type' => 'number',
            '#title' => t('Fetch All users details in next * minutes'),
            '#disabled' => true,
        ];

        $form['mo_azure_ad_profile_sync_fieldset'] = [
            '#type' => 'fieldset',
            '#title' => t('Profile Picture Sync <a href="azure_upgrade_plans"><small>[PREMIUM]</small></a><hr>'),
        ];

        $form['mo_azure_ad_profile_sync_fieldset']['auto_prov_note'] = [
            '#markup' => '<p class="mo_azure_highlight_background">It provides the feature to sync profile picture of users from your Active Directory. Default profile picture value can be set in the profile mapping settings in case there is no profile picture associated for some user accounts.</p>',
        ];

        $form['mo_azure_ad_profile_sync_fieldset']['enable_auto_creation'] = [
            '#type' => 'checkbox',
            '#title' => t('Enable Profile Picture Sync'),
            '#disabled' => true,
        ];

    }

    private function moProvisioningOperations(): array
    {
        $row['read_user_azure_ad'] = [
            '#type' => 'checkbox',
            '#title' => t('Read user'),
            '#disabled' => true,
            '#prefix'=> '<div class="container-inline">',
        ];

        $row['create_user_azure_ad'] = [
            '#type' => 'checkbox',
            '#title' => t('Create user '),
            '#disabled' => true,
        ];

        $row['update_user_azure_ad'] = [
            '#type' => 'checkbox',
            '#title' => t('Update user'),
            '#disabled' => true,
        ];

        $row['deactivate_user_azure_ad'] = [
            '#type' => 'checkbox',
            '#title' => t('Deactivate user '),
            '#disabled' => true,
        ];

        $row['delete_user_azure_ad'] = [
            '#type' => 'checkbox',
            '#title' => t('Delete user'),
            '#disabled' => true,
        ];

        $row['manual_provisioning_save_button'] = [
            '#type' => 'submit',
            '#value' => t('Save'),
            '#button_type' => 'primary',
            '#disabled' => true,
            '#suffix' => '</div>',
        ];

        return $row;
    }

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

        $form['mo_azure_attribute_mapping_details'] =[
            '#type' => 'fieldset',
            '#open' => false,
            '#title' => t('Mapping for Azure AD to Drupal Sync <a href="azure_upgrade_plans"><small>[PREMIUM]</small></a>'),
            '#attributes' => ['class' => ['attribute_mapp'] , 'style' => 'margin-bottom: 2px;'],
        ];

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

        $form['mo_azure_attribute_mapping_details']['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['mo_azure_attribute_mapping_details']['azure_ad_attribute_mapping']['azure_ad_attribute_mapping_table']['attributes'] = $row;

        $form['mo_azure_attribute_mapping_details']['azure_ad_attribute_mapping']['azure_ad_basic_mapping_save_button'] = [
            '#type' => 'submit',
            '#value' => t('Save Configuration '),
            '#button_type' => 'primary',
            '#disabled' => true,
        ];

        $form['mo_azure_attribute_mapping_details']['azure_ad_custom_attribute_mapping'] = array(
            '#type' => 'fieldset',
            '#title' => t('Custom Attribute Mapping<hr>'),
        );

        $form['mo_azure_attribute_mapping_details']['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['mo_azure_attribute_mapping_details']['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['mo_azure_attribute_mapping_details']['azure_ad_custom_attribute_mapping']['azure_ad_custom_attribute_mapping_table']['custom_mapping'] = $row;
    }

    private 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(){
        $row['username_attribute'] = [
            '#type' => 'select',
            '#title' => t('Username Attribute'),
            '#options' => [ 1 => 'name'],
            '#disabled' => true,
        ];

        $row['email_attribute'] = [
            '#type' => 'select',
            '#title' => t('Email Attribute'),
            '#options' => [ 1 => 'mail'],
            '#disabled' => true,
        ];

        return $row;
    }

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

}