<?php

namespace Drupal\azure_ad\Helper;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\Config;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user_provisioning\ProviderSpecific\APIHandler\UserAPIHandler\moUserAzureAPIHandler;

class moAzureADHelper
{
    private ImmutableConfig $config;
    private Config $config_factory;
    private $base_url;
    private string $url_path;

    public function __construct() {
        global $base_url;
        $this->base_url = $base_url;
        $this->config = \Drupal::config('azure_ad.settings');
        $this->config_factory = \Drupal::configFactory()->getEditable('azure_ad.settings');
        $this->url_path = $this->base_url . '/' . \Drupal::service('extension.list.module')->getPath('azure_ad'). '/includes';
    }

    public function fetchAttributes(){

        $azure = new moUserAzureAPIHandler();
        $test_user = $this->config->get('mo_azure_test_upn');

        if (empty($test_user)){
            $error_code = [
                "Error" => "Empty UPN",
                "Description" => "UPN is not configured in the module or incorrect."
            ];
            $azure->show_error_message($error_code);
        }

        $user_details = $azure->moAzureGetUserDetails();
        $user_details = $this->moAzureArrayFlattenAttributes($user_details);
        
        if(isset($user_details['id'])){
          $profile_pic = $azure->moAzureGetProfilePic($user_details['id']);
          if(!empty($profile_pic)){
            $user_details['Profile Picture'] = $profile_pic;
          }
        }

        $user_details_encoded = Json::encode($user_details);
        $this->config_factory
            ->set('mo_azure_attr_list_from_server', $user_details_encoded)
            ->save();
    }

    private function moAzureArrayFlattenAttributes($details): array
    {
        $arr = [];
        foreach ($details as $key => $value){
            if(empty($value)){continue;}
            if(!is_array($value)){
                $arr[$key] = filter_var($value);
            }else{
                $this->moAzureArrayFlattenAttributesLvl2($key,$value,$arr);
            }
        }
        return $arr;
    }

    private function moAzureArrayFlattenAttributesLvl2($index, $arr, &$haystack){
        foreach ($arr as $key => $value) {
            if( empty($value) ){continue;}
            if( !is_array($value) ){
                if(!strpos(strtolower($index),'error'))
                    $haystack[ $index. "|". $key] = $value;
            }else{
                $this->moAzureArrayFlattenAttributesLvl2($index. "|" . $key, $value, $haystack);
            }
        }
    }

    public function moAzureShowCustomerSupportIcon(array &$form, FormStateInterface $form_state){
        $form['mo_azure_customer_support_icon'] = [
            '#markup' => t('<a class="use-ajax mo-bottom-corner" href="CustomerSupportAzure"><img src="' . $this->url_path . '/mo-customer-support.png" alt="Support icon"></a>'),
        ];
    }

}
