<?php
namespace Modules\Index\Controller;

use DateTime;
use Firebase\JWT\Key;
use GuzzleHttp\Psr7\Response;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Roles;
use Helpers\Session\ParseBase1;
use Skeleton\Controller\Controller;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Helpers\Outil\Captcha;

class DiagsController extends Controller
{

    protected string  $nameFileMdpConnexionUser = 'accuserdiags.oxa';
    
    /**
     * init
     *
     * @return void
     */
    public function init()
    {
    }
        
    /**
     * nouveauMotDePasseAction
     *
     * @return string|\GuzzleHttp\Psr7\Response
     */
    public function nouveauMotDePasseAction()
    {
        
        $messageErreur = '';
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        if (isset($post['MDP']) && trim($post['MDP']) != '' && isset($post['MDP2']) && trim($post['MDP2']) != '') {
            if ($post['MDP'] != $post['MDP2']) {
                $messageErreur = $trad->t('Les deux mots de passe ne sont pas identiques.');
            }

            if ($messageErreur == '') {
                $payload = [
                    'mdp'=> $post['MDP'],
                 ];

                $jwt = \Firebase\JWT\JWT::encode($payload, $this->JWTKEY, 'HS256');
                Fichier::createFichier((new ParseBase1())->getRep()->etc, $this->nameFileMdpConnexionUser, $jwt);
                
                return $this->redirect('Index.Diags.connexion');
            }
        }

        return $this->renderer->render('@index/diags/nouveauMotDePasse', [
            'messageErreur' => $messageErreur
        ]);
    }

    /**
     * @return Response
     */
    public function activeTracingRequeteAction()
    {
        if (isset($_SESSION['activeTracingRequete'])) {
            unset($_SESSION['activeTracingRequete']);
        } else {
            $_SESSION['activeTracingRequete'] = true;
        }
        return new Response(200, [], (string)json_encode([
            'activeTracingRequete' => $_SESSION['activeTracingRequete']??false
        ]));
    }
    
    /**
     * connexionAction
     *
     * @return string|\GuzzleHttp\Psr7\Response
     */
    public function connexionAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        if (isset($post['MDP']) && trim($post['MDP']) != '') {
            $messageErreur = '';
            $captcha = new Captcha();
            $validator = $this->createValidator();
            $validator->captcha($captcha->getCaptcha('login')['code'], $post['login']);
            if (!$validator->isValid()) {
                $messageErreur = $validator->getError();
            }
            if ($messageErreur =='') {
                $wsdl = new \Modules\Index\WebService\Utilisateur($this->pdo);
                if (file_exists((new ParseBase1())->getRep()->etc.$this->nameFileMdpConnexionUser)) {
                    $fichierContent = file_get_contents((new ParseBase1())->getRep()->etc.$this->nameFileMdpConnexionUser);
                    try {
                        $verify = \Firebase\JWT\JWT::decode((string)$fichierContent, new Key($this->JWTKEY, 'HS256'));
                        $verify = (array)$verify;
                        if ($verify['mdp'] == $post['MDP']) {
                            $_SESSION['ConnexionOKDiags'] = true;
                            return $this->redirect($this->contenaire->get('base').'diags.php');
                        } else {
                            $resultat = \Modules\Index\Outil\OutilConnexionDiags::connexionOxauser($wsdl, $post['MDP']);
                            
                            if ($resultat['ConnexionReussie'] == 'true') {
                                $_SESSION['ConnexionOKDiags'] = true;
                                return $this->redirect('Index.Diags.index');
                                //return $this->redirect($this->contenaire->get('base').'diags.php');
                            } else {
                                $messageErreur = $trad->t('Le mot de passe n\'est pas valide.');
                            }
                        }
                    } catch (\Exception $e) {
                        $messageErreur = $e->getMessage();
                    }
                } else {
                    if ($post['MDP'] == 'changeit' && strpos((new ParseBase1())->getServer(), 'oxacloud') === false) {
                        return $this->redirect('Index.Diags.nouveauMotDePasse');
                    } else {
                        $resultat = \Modules\Index\Outil\OutilConnexionDiags::connexionOxauser($wsdl, $post['MDP']);
                            
                        if ($resultat['ConnexionReussie'] == 'true') {
                            $_SESSION['ConnexionOKDiags'] = true;
                            $_SESSION['modeOXAUSER'] = true;
                            return $this->redirect($this->contenaire->get('base').'diags.php');
                        } else {
                            $messageErreur = $trad->t('Le mot de passe n\'est pas valide.');
                        }
                    }
                }
            }
        } elseif (isset($post['MDP']) && trim($post['MDP']) == '') {
            $messageErreur = $trad->t('Veuillez renseigner votre mot de passe ainsi que le code de sécurité.');
        }

        return $this->renderer->render('@index/diags/connexion', [
            'messageErreur' => $messageErreur ?? ''
        ]);
    }

    /**
     * @return string|\GuzzleHttp\Psr7\Response
     */
    public function indexAction()
    {
        if (Roles::GetALL()) {
            $_SESSION['ConnexionOKDiags'] = true;
        }
        
        if ($_SESSION['ConnexionOKDiags']??false) {
            return $this->renderer->render('@index/diags/index', [
                'base1' => file_get_contents(\Helpers\Roles\ParseConfigFile::getDirectoryBase1()),
                'OXAUSER' => $_SESSION['modeOXAUSER'] ?? false,
            ]);
        }

        return $this->redirect('Index.Diags.connexion');
    }

    public function phpinfoAction():string
    {
        @phpinfo();
        return '';
    }

    /**
     * @return mixed
     */
    public function oxaReportAction()
    {
        $sec = (new ParseBase1())->getHttps()? 'https://' : 'http://';
        $broker = (new ParseBase1())->getBroker() == '1' ? '' : (new ParseBase1())->getBroker();
        $token = hash('sha256', jddayofweek(cal_to_jd(CAL_GREGORIAN, (int)date("m"), (int)date("d"), (int)date("Y")), 1).'&'.date("d"));

        $diagsOxaReport = $sec.$_SERVER['HTTP_HOST'].'/OXAREPORTS'.$broker.'_WEB/FR/Diags.awp?token='.$token;

        $file_headers = @get_headers($diagsOxaReport);

        if ($file_headers && $file_headers[0] != 'HTTP/1.1 404 Not Found') {
            return $this->redirect($diagsOxaReport);
        } else {
            return "il n'y a pas de diags pour : ".$diagsOxaReport;
        }
    }

    public function perfRequeteAction():string
    {
        $file = (new ParseBase1())->getRep()->oxadata.'batchs\\Performances_Evaluation.sql';

        if (file_exists($file)) {
            $content = file_get_contents($file);
            $explodeFile = explode('/*<SEPARATEUR>*/', (string)$content);
    
            $totalStart = null;
            $stats = [];
            foreach ($explodeFile as $requete) {
                $start = new DateTime();
                if ($totalStart == null) {
                    $totalStart = $start;
                }
                $this->executeRequete($requete);
                $end = new DateTime();
                
                $diff = $start->diff($end);

                $stats[] = [
                    'requete' => $requete,
                    'start' => $start->format('H:i:s.u'),
                    'end' => $end->format('H:i:s:u'),
                    'diff' => $diff->format('%H:%I:%S.%F'),
                ];
            }

            $totalDiff = $totalStart->diff($end);
            $totalTime = $totalDiff->format('%H:%I:%S.%F');
        }

        return $this->renderer->render('@index/diags/perfRequete', [
            'stats' => $stats??[],
            'totalTime' => $totalTime??'',
        ]);
    }

    /**
     * @return bool|string
     */
    private function executeRequete(string $requete)
    {
        //$this->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

        $requete = str_replace(strtoupper('select'), "SELECT 'test' OXALYS,", strtoupper($requete));
        $requete .= "ORDER BY OXALYS  DESC OFFSET ((1 - 1) * 30) ROWS FETCH NEXT 10000 ROWS ONLY";

        $exec = $this->pdo->prepare($requete);
        $exec->execute([]);

        $rows = $exec->fetchAll(\PDO::FETCH_ASSOC);
        return json_encode($rows);
    }
}
