<?php
namespace Modules\API\APIInterne\Diags\Controller;

use Helpers\Log\LogSysteme;

use Modules\Index\Repository\Connexion;
use Skeleton\Controller\Controller;
use Modules\API\APIInterne\Diags\Outil\OutilDiags;
use Firebase\JWT\JWT;
use GuzzleHttp\Psr7\Response;

    // phpcs:ignore
defined('in_ISO88591') or define('in_ISO88591', 0);

    // phpcs:ignore
defined('in_UTF8') or define('in_UTF8', 1);

// Définition de constante pour la correspondance entre indice et type de base
defined('DB_MYSQL') or define('DB_MYSQL', 19);
defined('DB_MSSQL') or define('DB_MSSQL', 21);
defined('DB_ORA') or define('DB_ORA', 14);

defined('DB_OXASQLDB') or define('DB_OXASQLDB', 'OXASQLDB');
defined('DB_OXACATDB') or define('DB_OXACATDB', 'OXACATDB');
defined('DB_OXAPROCDB') or define('DB_OXAPROCDB', 'OXAPROCDB');
defined('DB_OXALINKDB') or define('DB_OXALINKDB', 'OXALINKDB');
defined('DB_OXADDWB') or define('DB_OXADDWB', 'OXADWDB');
defined('DB_OXASVDB') or define('DB_OXASVDB', 'OXASVDB');
defined('DB_OXAFTDB') or define('DB_OXAFTDB', 'OXAFTDB');

// CONEXION PDO
defined('DB_OXASQLDB_PDO') or define('DB_OXASQLDB_PDO', 'OXASQLDB_PDO');
defined('DB_OXACATDB_PDO') or define('DB_OXACATDB_PDO', 'OXACATDB_PDO');
defined('DB_OXAPROCDB_PDO') or define('DB_OXAPROCDB_PDO', 'OXAPROCDB_PDO');
defined('DB_OXADWDB_PDO') or define('DB_OXADWDB_PDO', 'OXADWDB_PDO');
defined('DB_OXAFTDB_PDO') or define('DB_OXAFTDB_PDO', 'OXAFTDB_PDO');

class DiagsController extends Controller
{
    /**
     * @return bool|Response|string
     */
    public function diagsExcelAction()
    {
        $connexionRepo = new Connexion($this->pdo);
        $post = $this->request->getParsedBody();
        $json = $this->request->getAttribute('json') ?? false;
        $diags = new OutilDiags();
        $arrayDiags = [];

        $motDePasse = date('l&d');
        $token = array(
            "token" => $motDePasse,
        );
        
        $token = JWT::encode($token, $this->JWTKEY, 'HS256');
        
        /** ********* **/
        /** INTEGRITE **/
        /** ********* **/
        /** @phpstan-ignore-next-line */
        $versionProduit = $this->getVersion();
        $versionProduit = mb_substr($versionProduit, 0, 7);
        $diags->testIntegrity($this->pdo, $arrayDiags, $versionProduit);
        
        /** *************** **/
        /** VERSION A JOURS **/
        /** *************** **/
        $versionBDD = $connexionRepo->reqGetVersion();
        if ($versionBDD==$versionProduit) {
            $versionOK = true;
        }

        /** *************** **/
        /** Lecture base 1  **/
        /** *************** **/
        $diags->testBase1($arrayDiags);

        /** *************** **/
        /** Environnement   **/
        /** *************** **/
        $diags->testEnvironnement($this->pdo, $arrayDiags);


        /** *********************************************** **/
        /**       Répertoire de stockage des fichiers       **/
        /** *********************************************** **/
        $diags->testDir($arrayDiags);
        
        /** **************** **/
        /** Bases de données **/
        /** **************** **/
        $diags->testDatabaseConnection($arrayDiags);

        /** Connexion PDO à la base OXASQLDB **/
        $isOkFT = $diags->testPDO($arrayDiags);


        /** ***************** **/
        /** Configuration PHP **/
        /** ***************** **/
        $diags->doPHPTest($arrayDiags);

        /** ********* **/
        /** Full-text **/
        /** ********* **/
        $diags->writeTestFullText($arrayDiags, $isOkFT);

        /** ************ **/
        /** Web-Services **/
        /** ************ **/
        $arrayTmp = $diags->doWebServiceTest();
        
        $arrayDiags['WSDL']['CONNEXION_WEBSERVICE'] = [
            'libelle'   => 'CONNEXION_WEBSERVICE',
            'text'      => '',
            'value'     => $arrayTmp['is_connexion'] == 1 ? 'OK' : 'KO',
        ];
        
        /** ****** **/
        /** Moteur **/
        /** ****** **/
        $arrayMoteur = $diags->doMoteurTest();
        
        $diags->writeMoteurTest($arrayDiags, $arrayMoteur);

        
        /** *************** **/
        /** PARAMÉTRAGE PHP **/
        /** *************** **/
        $arrayTmp = $diags->doExtTest();
        $diags->writeExtTest($arrayDiags, $arrayTmp);
        
        if ($json) {
            return new Response(
                200,
                [
                            'Content-Type' => 'application/json'
                        ],
                str_replace(['"OK"', '"KO"', '"text":"",'], ['true', 'false', ''], json_encode((array)$arrayDiags)) //@phpstan-ignore-line
            );
        } else {
            $arrayDiags = array_reduce($arrayDiags, function ($result, $array) {
                return array_merge($result, $array);
            }, []);
            $arrayDiags = array_values($arrayDiags);

            $nomFichier = new \Helpers\ExportTo\Generate("DATA_DIAGS", 'csvV2', $arrayDiags);

            $pathInfo = pathinfo($nomFichier->urlCsv);
            
            $newPath = ($pathInfo['dirname'] ?? '').'\\'
                .LogSysteme::getServerName().'.DATA_DIAGS_'
                .$token.'.'.($pathInfo['extension'] ?? '');
        }

        if (isset($post['modeFile']) && $post['modeFile']) {
            header('Content-type: text/xml');
            $xml = new \SimpleXMLElement('<Diags/>');
        
            $xml->addChild('statut', 'O');
            $xml->addChild('fichier', $pathInfo['basename']);
            return $xml->asXML();
        } else {
            rename($nomFichier->urlCsv, $newPath);
            return file_get_contents($newPath);
        }
    }
}
