<?php

/**
 * @file
 * Contains \Drupal\oauth_server_sso\Form\MiniorangeServerMapping.
 */
namespace Drupal\oauth_server_sso\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;
use Drupal\oauth_server_sso\Utilities;

class MiniorangeServerMapping extends FormBase
{
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'miniorange_general_settings';
    }

    public function buildForm(array $form, FormStateInterface $form_state){
        global $base_url;
        $form['markup_library'] = array(
            '#attached' => array(
                'library' => array(
                    "oauth_server_sso/oauth_server_sso.style_settings",
                    "core/drupal.dialog.ajax",
                )
            ),
        );

        $url_path = $base_url . '/' . \Drupal::service('extension.list.module')->getPath('oauth_server_sso'). '/includes/images';
        $form['mo_oauth_server_style'] = array('#markup' => '<div class="mo_oauth_table_layout mo_oauth_container_full">');
        $form['oauth_server_basic_attribute_mapping']= array(
            '#markup' =>'<h5>'.t('Attribute Mapping').'</h5>'
        );
        $form['markup_note_1'] = array(
            '#prefix'=>'<br>',
            '#markup' => '<div class="mo_oauth_server_highlight_background_note_2">'.t('The attributes below will be sent to the configured Client Application when it requests the Get Userinfo Endpoint.').'</div>',
        );
        $form['basic_mapping_table'] = array(
            '#type' => 'table',
            '#header'=> array( t('Attribute Name'), t('Drupal User Profile Attribute Machine Name') ),
            '#responsive' => TRUE ,
        );
        $default_attrs = array(
            'id'       => 'uid',
            'uuid'     => 'uuid',
            'email'    => 'mail',
            'username' => 'name',
        );
        foreach($default_attrs as $key =>$value){
            $basic_map= self::createRow($key,$value,'basic','');
            $form['basic_mapping_table'][$key] = $basic_map;
        }
        $form['markup_note']= array(
            '#markup' => '<b>'.t('Note: ').'</b>'.t('You can edit the values for the Attribute Names however, it is highly recommended not to change the default values.').'<br><br>',
        );

        $form['basic_mapping_update'] = array(
            '#type' => 'submit',
            '#button_type' => 'primary',
            '#value' => t('Update Configuration'),
        );

        $form['basic_mapping_reset'] = array(
            '#type' => 'submit',
            '#value' => t('Reset Configuration'),
            '#limit_validation_errors' => array(),
            '#submit' => array('::setMappingToDefault'),

        );
//custom attributes
        $form['oauth_server_custom_attribute_mapping'] = array(
          '#prefix'=>'<br><hr><br>',
           '#markup' => '<h5>'.t('Custom Attribute Mapping ').'<a href="licensing"><img class="mo_oauth_pro_icon1" src="' . $url_path . '/pro.png" alt="Premium"><span class="mo_pro_tooltip">'.t('Available in the Premium version').'</span></a></h5>',
        );

        $form['oauth_server_sso_custom_attribute_markup'] = array(
             '#markup' => '<div class="mo_oauth_server_highlight_background_note_2">'.t('Map extra User attributes which you wish to be included in the Get Userinfo Endpoint response.').'<br>
              <b>'.t('Note: ').'</b>'.t('Enter the name you want to send as the attribute name under the \'Attribute Name\' text field and select the Drupal user attribute (machine name) whose value you want to send from \'Drupal User Profile Attribute Machine Name\' drop-down menu.').'</div>',
             '#prefix' => '<br>',
        );

        $form['custom_mapping_table'] = array(
            '#type' => 'table',
            '#header'=> array( t('Attribute Name'), t('Drupal User Profile Attribute Machine Name'),'',),
            '#responsive' => TRUE ,
            '#prefix' => '<br>',

        );
        $custom_fields = Utilities::customUserFields('mapping');
        $custom_map= self::createRow('','','custom',$custom_fields);
        $form['custom_mapping_table']['first']=$custom_map;
        $form['custom_add_more_button'] = array(
            '#type' => 'button',
            '#value' => t('Add more'),
            '#disabled' => true,
            '#attributes' =>[
                'class' =>['button--small button--primary'],
                'style' => 'margin-left: 15px;'
            ]
        );
//constant attributes
        $form['oauth_server_constant_attribute_mapping'] = array(
          '#prefix'=>'<br><hr><br>',
          '#markup' => '<h5>'.t('Constant Attributes ').'<a href="licensing"><img class="mo_oauth_pro_icon1" src="' . $url_path . '/pro.png" alt="Premium"><span class="mo_pro_tooltip">'.t('Available in the Premium version').'</span></a></h5>',
        );

        $form['oauth_server_sso_constant_attribute_markup'] = array(
             '#markup' => '<div class="mo_oauth_server_highlight_background_note_2">'.t(' This section is to send some constant values to your Client Application for every user. The \'Attribute Name\' is the unique name and the \'Attribute Value\' is the constant value that you want to send to in every SSO.').'</div>',
             '#prefix' => '<br>',
        );

        $form['constant_mapping_table'] = array(
            '#type' => 'table',
            '#header'=> array( t('Attribute Name'), t('Attribute Value'),'',),
            '#responsive' => TRUE ,
        );
        $constant_map= self::createRow('','','constant','');
        $form['constant_mapping_table']['first']=$constant_map;
        $form['Constant_add_more_button'] = array(
            '#type' => 'button',
            '#value' => t('Add more'),
            '#disabled' => true,
            '#attributes' =>[
                'class' =>['button--small button--primary'],
                'style' => 'margin-left: 15px;'
            ]
        );
        $form['next_step_1'] = array(
            '#type' => 'submit',
            '#disabled' => true,
            '#button_type' => 'primary',
            '#value' => t('Save Configuration'),
            '#attributes' => array('style' => '	margin: auto; display:block; '),
        );
        Utilities::moOAuthServerShowCustomerSupportIcon($form, $form_state);
        return $form;
    }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        $config = \Drupal::configFactory()->getEditable('oauth_server_sso.settings');
        $form_values = $form_state->getValue('basic_mapping_table');
        $uid_attr_name=$form_values['id']['id_name'];
        $uuid_attr_name=$form_values['uuid']['uuid_name'];
        $mail_attr_name=$form_values['email']['email_name'];
        $username_attr_name=$form_values['username']['username_name'];
        $config->set('uid_attr_name', $uid_attr_name)
                ->set('uuid_attr_name',$uuid_attr_name)
                ->set('mail_attr_name', $mail_attr_name)
                ->set('name_attr_name', $username_attr_name)
                ->save();
        \Drupal::messenger()->addMessage($this->t('Configurations updated successfully.'));
    }

    public function setMappingToDefault(){
        $config = \Drupal::configFactory()->getEditable('oauth_server_sso.settings');
        $config->set('uid_attr_name', 'id')
               ->set('uuid_attr_name','sub')
               ->set('mail_attr_name', 'email')
                ->set('name_attr_name', 'username')
               ->save();
        \Drupal::messenger()->addMessage($this->t('Configurations have been reset successfully.'));
    }

    public function createRow($key, $value, $type='', $custom_fields=array()){
        $config = \Drupal::config('oauth_server_sso.settings');
        if($type=='custom' || $type=='constant'){
            $row_form['name']= array(
            '#type' => 'textfield',
            '#attributes' => ['placeholder' => t('Enter Attribute Name'),],
            '#disabled' => true,
            );
            if($type=='constant'){
                $row_form['value']= array(
                    '#type' => 'textfield',
                    '#attributes' => ['placeholder' => t('Enter the Value'),],
                    '#disabled' => true,
                );
            }else{
                $row_form['value']= array(
                    '#type' => 'select',
                    '#options' => $custom_fields,

                );
            }
            $row_form['mo_minus_button'] = array(
                    '#type' => 'button',
                    '#value' => t('Remove'),
                    '#disabled' => true,
                    '#attributes' => ['class' => ['button--small button--primary']]
            );
        }elseif($type=='basic'){
            $row_form[$key.'_name']=array(
                '#type' => 'textfield',
                '#default_value' => $config->get($value.'_attr_name'),
                '#required' =>true,
            );
            $row_form[$key.'_value']=array(
            '#type' => 'textfield',
            '#default_value' => $value,
            '#disabled' => true,
             );
        }
     return $row_form;
    }
}
