<?php

namespace Drupal\azure_ad\Controller;

use Drupal;
use Drupal\azure_ad\MoAzureUtilities;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Config\Config;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Drupal\user_provisioning\moUserProvisioningConstants;
use Drupal\user_provisioning\moUserProvisioningUtilities;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\RedirectResponse;

class MoAzureController extends ControllerBase
{
    private Config $config_factory;
    protected $messenger;
    protected $formBuilder;
    private ImmutableConfig $config;
    private ParameterBag $get;

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

    public function openTrialRequestForm(): AjaxResponse
    {
        $response = new AjaxResponse();
        $modal_form = $this->formBuilder->getForm('\Drupal\azure_ad\Form\MoAzureRequestTrial');
        $response->addCommand(new OpenModalDialogCommand('Request 7-Days Full Feature Trial License', $modal_form, ['width' => '45%'] ) );
        return $response;
    }

    public function openCustomerRequestForm(): AjaxResponse
    {
        $response = new AjaxResponse();
        $modal_form = $this->formBuilder->getForm('\Drupal\azure_ad\Form\MoAzureCustomerRequest');
        $response->addCommand(new OpenModalDialogCommand('Contact miniOrange Support', $modal_form, ['width' => '45%'] ) );
        return $response;
    }

    public function openconfigform(): AjaxResponse
    {
        $response = new AjaxResponse();
        $modal_form =  $this->formBuilder->getForm('\Drupal\azure_ad\Form\MoReviewAzureConfig');
        $response->addCommand(new OpenModalDialogCommand('Azure Configurations', $modal_form, ['width' => '60%'] ) );
        return $response;
    }

    public function configureApp($app){

        $this->config_factory->set('azure_ad_provisioning_step', 'step3')->save();
        $path = Url::fromRoute('azure_ad.overview')->toString();
        $response = new RedirectResponse($path);
        $response->send();
        return $response;
    }

    /**
     * @throws \Exception
     */
    public function moAzureADFeedbackFunc($email, $reason, $q_feedback, $skip_feedback, $trial){

        global $base_url;

        $modules_info = \Drupal::service('extension.list.module')->getExtensionInfo('azure_ad');
        $modules_version = $modules_info['version'];
        $_SESSION['mo_other'] = "False";
        $url = moUserProvisioningConstants::BASE_URL. '/moas/api/notify/send';
        $utilities = new MoAzureUtilities();

        if ($skip_feedback) {
            $utilities->skipFeedback($modules_version, $url);
        } else {
            $trial = !empty($trial) ? 'Yes' : 'No';
            $message = 'Reason: ' . $reason . '<br>Feedback: ' . $q_feedback . '<br><br>Is Trial selected: ' . $trial;

            if(empty($email)){
                $admin_email       =  $this->config->get('user_provisioning_customer_admin_email');
                if(empty($admin_email)){
                    $current_user      = \Drupal::currentUser();
                    $admin_email       = $current_user->getEmail();
                }
                $site_mail         = \Drupal::config('system.site')->get('mail');
                $email             = !empty($admin_email) ?  $admin_email : $site_mail;
            }
             
            [$customerKey] = $utilities->CustomerApiKey();

            $subject = 'Drupal ' . \DRUPAL::VERSION . ' Azure AD Sync Module Feedback | ' . $modules_version;
            $query = '[Drupal ' . moUserProvisioningUtilities::mo_get_drupal_core_version() . ' Azure AD Sync | ' . $modules_version . ' | PHP Version '.phpversion().']: ' . $message;
            $content = '<div >Hello, <br><br>Company :<a href="' . $_SERVER['SERVER_NAME'] . '" target="_blank" >' . $_SERVER['SERVER_NAME'] . '</a><br><br>Email :<a href="mailto:' . $email . '" target="_blank">' . $email . '</a><br><br>Query :' . $query .'</div>';

            $fields = array(
                'customerKey' => $customerKey,
                'sendEmail' => true,
                'email' => [
                    'customerKey' => $customerKey,
                    'fromEmail' => $email,
                    'fromName' => 'miniOrange',
                    'toEmail' => moUserProvisioningConstants::SUPPORT_EMAIL,
                    'toName' => moUserProvisioningConstants::SUPPORT_EMAIL,
                    'subject' => $subject,
                    'content' => $content
                ],
            );

            $utilities->AzureHttpCall($fields, $url);
        }

        \Drupal::configFactory()->getEditable('azure_ad.settings')->set('miniorange_azure_uninstall_status', true)->save();
        \Drupal::service('module_installer')->uninstall(['azure_ad']);
        $uninstall_redirect = $base_url.'/admin/modules/uninstall';

        \Drupal::messenger()->addMessage($this->t('The selected modules have been uninstalled.'));
        return new RedirectResponse($uninstall_redirect);
    }
}
