<?php

namespace Modules\Evaluation\Service;

use Helpers\Fichier\Fichier;
use Helpers\Outil\Sql;
use Helpers\Session\ParseBase1;
use Modules\Evaluation\Repository\BibliothequeDeQuestions;
use PDO;
use PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace;

class BibliothequeService
{

    public function treeBibliotheque($parent, $array, $post, $urlImage = null, bool $redirect = false)
    {
        $result = array();
        foreach ($array as $noeud) {
            if ($parent == trim($noeud['ID_PERE'])) {
                $result[] = array(
                    'id' => $noeud['ID_THEME'],
                    'text' => '<mark class="truncate">'.$noeud['LIB_THEME'] . '</mark>' .($urlImage? '<div class="divMenuContextuel" onClick="' . ($redirect ? 'importTheme(this);' : 'AfficheMenu(this);') . 'roueDenteActive(this);"><img class="imagePoint" style="float: right;" src="'.$urlImage.'" width="5px" style=""/></div><ul class="ss_parametres"></ul>':''),
                    'children' => $this->treeBibliotheque($noeud['ID_THEME'], $array, $post, $urlImage, $redirect),
                    'li_attr' => [ "data-drop" => $noeud['COUNT_QUEST'] == '0' ? 'true':'false' ],
                );
            }
        }
        return $result;
    }
    
    /**
     * replaceRequest
     * récupère les infos d'une question calculée et construit une requête pour tester la requête (en remplaçant les tags notamment)
     *
     * @param  string $select
     * @param  string $request
     * @param  int $campaignId
     * @return array<mixed>
     */
    public function replaceRequest(string $select, string $request, int $campaignId)
    {
        $arrayReq = [];
        $req = 'SELECT ' . \strtoupper($select) . ' ' . \strtoupper($request);
        if (\strpos($req, '<TAG_USER>')) {
            $req = \str_replace('<TAG_USER>', ':USER', $req);
            $arrayReq[':USER'] = $_SESSION['Session_Login'];
        }
        if (\strpos($req, '<TAG_SOCIETE>')) {
            $req = \str_replace('<TAG_SOCIETE>', ':SOCIETE', $req);
            $arrayReq[':SOCIETE'] = $_SESSION['Session_SocUsr'];
        }
        if (\strpos($req, '<TAG_PERIODE>')) {
            $req = \str_replace('<TAG_PERIODE>', '(SELECT COD_PER FROM CAMP_ENT WHERE ID_CAMP = :ID_CAMP)', $req);
            $arrayReq[':ID_CAMP'] = $campaignId;
        }
        if (\strpos($req, '<TAG_FOURN>')) {
            $req = \str_replace('<TAG_FOURN>', '(SELECT TOP 1 CODE_FOU FROM CAMP_LST_FOUR WHERE ID_CAMP = :ID_CAMP2)', $req);
            $arrayReq[':ID_CAMP2'] = $campaignId;
        }

        $request = array(
            'req'       => $req,
            'arrayReq'  => $arrayReq,
        );

        return $request;
    }
    
    /**
     * resetQuiz
     *
     * @param  PDO $pdo
     * @param  string $mode
     * @param  string|int $modeId
     * @return bool
     */
    public function resetQuiz(PDO $pdo, string $mode, $modeId)
    {
        $bibRepo = new BibliothequeDeQuestions($pdo);

        switch ($mode) {
            case 'campagne':
                $themeTable = 'CAMP_QST_TH';
                $questionsTable = 'CAMP_QST_Q';
                $answersTable = 'CAMP_QST_R';
                $dependenciesTable = 'CAMP_QST_DEP';
                $key = 'ID_CAMP';
                break;
            
            case 'modele':
                $themeTable = 'GRIL_THEME';
                $questionsTable = 'GRIL_QST_Q';
                $answersTable = 'GRIL_QST_R';
                $dependenciesTable = '';
                $key = 'ID_MODEL';
                break;
            
            case 'AO_CONTRIB':
            case 'AO':
                $themeTable = 'AO_QST_TH';
                $questionsTable = 'AO_QST_Q';
                $answersTable = 'AO_QST_R';
                $dependenciesTable = '';
                $key = 'NO_AO';
                break;
            
            default:
                $themeTable = '';
                $questionsTable = '';
                $answersTable = '';
                $dependenciesTable = '';
                $key = '';
                break;
        }

        $reset = $bibRepo->resetQuiz($themeTable, $questionsTable, $answersTable, $key, $modeId, $dependenciesTable);

        return $reset;
    }
    
    /**
     * isQuizEditableOnRfx
     *
     * @param  PDO $pdo
     * @param  int $id
     * @return int
     */
    public function isQuizEditableOnRfx(PDO $pdo, int $id)
    {
        $bibRepo = new BibliothequeDeQuestions($pdo);
        $check = $bibRepo->isQuizEditableOnRfx($id);

        return Sql::toBool($check) ? 0 : 1;
    }

    /**
     * checkIfSqlRequestWorks
     *
     * @param  string $select
     * @param  string $from
     * @param  PDO $pdo
     * @return bool
     */
    public function checkIfSqlRequestWorks(string $select, string $from, PDO $pdo) : bool
    {
        $bibliothequeRepo = new BibliothequeDeQuestions($pdo);
        return $bibliothequeRepo->checkIfSqlRequestWorks($select, $from);
    }
}
