<?php

namespace Modules\Consultation\TwigExtension;

use Entity\Model\Fourniss;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Psr\Container\ContainerInterface;
use Skeleton\Router;
use Entity\Model\AoQstTh;
use TwigExtension\FormExtension;
use Entity\Model\AoQstR;
use Modules\Consultation\Repository\Reponse;

class QuestionnaireExtension extends \Twig\Extension\AbstractExtension
{
    protected $pdo;
    protected $contenaire;
    private $router;

    public function __construct(\PDO $pdo, ContainerInterface $contenaire, Router $router)
    {
        $this->pdo = $pdo;
        $this->contenaire = $contenaire;
        $this->router = $router;
    }

    public function getFunctions()
    {
        return [

            new \Twig\TwigFunction('buildTreeFormQuestionnaire', [
                $this,
                'buildTreeFormQuestionnaire',
            ], [
                'is_safe' => [
                    'html',
                ],
            ]),
        ];
    }

    public function buildTreeFormQuestionnaire($theme, $codeFou, $idRep, $typeFG, $CV, $trad, $canEdit = true)
    {
        $html = '<a class="list-group-item separateur_bottom clearfix" id="zone' . $theme['ID_THEME'] . '">
                    <span>' . $theme['LIB_THEME'] . '</span>
                    <span class="glyphicon glyphicon-chevron-down mg-icon pull-right"></span>
                </a>
                <div class="panel list-sub mg-show" style="display:block;">
                    <div class="panel-body">
                        <div class="list-group" id="id_' . $theme['ID_THEME'] . '">';

        $formExtension = new FormExtension($this->router, $this->pdo, $this->contenaire);

        $aoQstTh = new AoQstTh($this->pdo);
        $listeTheme = $aoQstTh->findAll(['NO_AO' => $theme['NO_AO'], 'ID_PERE' => $theme['ID_THEME']], [], ['tri_NM_ORDRE' => 'asc']);

        foreach ($listeTheme as $themeFils) {
            $html .= $this->buildTreeFormQuestionnaire($themeFils, $codeFou, $idRep, $typeFG, $CV, $trad, $canEdit);
        }

        $aoQstR = new AoQstR($this->pdo);
        // le fournisseur a accès à oxalink ? si non, on peut répondre aux questions fournisseur
        $isSupplierOxalink = Sql::boolSql((new Fourniss($this->pdo))->find(['CODE' => $codeFou], ['GEREPORTAIL'])['GEREPORTAIL']);

        $reponse = new Reponse($this->pdo);
        $listeQuestion = $reponse->getListeQuestionReponse($theme['NO_AO'], $theme['ID_THEME'], $codeFou, $idRep, $typeFG, $CV);

        foreach ($listeQuestion as $question) {
            //@phpstan-ignore-next-line
            $canEditSupplier = $canEdit && (!$isSupplierOxalink || ($isSupplierOxalink && (!Sql::boolSql($question['QUEST_FOUR'])) || Roles::droitsUtilisateur($this->pdo, 'HA_AO_SRF') ));
            $html .= '<div class="clearfix" style="margin-top:30px;padding: 0 15px 0 15px;position: relative;">
                        <label>' . $question['LIB_QUEST'] . '</label>';

            $html .= $formExtension->inputAdvance('TEXT', [
                'name' => 'NOTE-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'],
                'pathValidator' => $this->router->generateUri('Ajax.validator.float'),
                'paramsValidator' => "{'format' : 2.2}",
                'myFuncValidator' => 'updateReponse',
                'paramFuncValidator' => '[' .
                    json_encode(['name' => "NOTE", 'theme' => $theme['ID_THEME'], 'question' => $question['ID_QUEST']]) . ']',
                'addStyle' => 'width: 10%;position: absolute;right: 16px;top: ' .
                    (($question['TYPE_REP'] == 'L') ? '-30px;' : '-15px;') .
                    (($canEdit && $question['TYPE_REP'] != 'O') ? 'display: none;' : ' ') . '  ',
                'placeholder' => 'Note',
                'value' => $question['NOTE'],
                'option' => $question['TYPE_REP'] == 'O' ? '' : 'readOnly',
            ]);

            if ($question['TYPE_REP'] == 'O') {
                $html .= $formExtension->inputAdvance('TEXTAREA', [
                    'name' => 'REP_OUV_NM-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'],
                    'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                    'paramsValidator' => "{'sizeMin' : 0, 'sizeMax' : 3000}",
                    'myFuncValidator' => 'updateReponse',
                    'paramFuncValidator' => '[' .
                        json_encode(['name' => "REP_OUV_NM", 'theme' => $theme['ID_THEME'], 'question' => $question['ID_QUEST']]) . ']',
                    'value' => $question['repOuvert'],
                    'option' => $canEditSupplier ? '' : 'readOnly',
                ]);
            } elseif ($question['TYPE_REP'] == 'N') {
                $format = $question['NUM_FORMAT'];

                $split = explode('.', $format);
                $decimal = (int)($split[1] ?? 0);

                $html .= $formExtension->inputAdvance('TEXT', [
                    'name' => 'REP_NUM-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'],
                    'pathValidator' => $this->router->generateUri('Ajax.validator.float'),
                    'paramsValidator' => "{'format' : '" . $question['NUM_FORMAT'] . "', 'min': '" . $question['NUM_MIN'] . "','max': '" . $question['NUM_MAX'] . "'}",
                    'myFuncValidator' => 'updateReponse',
                    'paramFuncValidator' => '[' .
                        json_encode(['name' => "REP_NUM", 'theme' => $theme['ID_THEME'], 'question' => $question['ID_QUEST']]) . ']',
                    'myFunction' => 'separateurMilier',
                    'myParams' => '[this]',
                    'value' => number_format((float)$question['REP_NUM'], $decimal, '.', ''),
                    'option' => $canEditSupplier ? '' : 'readOnly',
                ]);
            } elseif ($question['TYPE_REP'] == 'L') {
                $html .= $formExtension->inputAdvance('SWITCH', [
                    'name' => 'REP_LOG-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'],
                    'myFunction' => 'updateReponse',
                    'myParams' => '[' . json_encode(['name' => "REP_LOG", 'theme' => $theme['ID_THEME'], 'question' => $question['ID_QUEST']]) . ']',
                    'value' => $question['REP_LOG'],
                    'option' => $canEditSupplier ? '' : 'disabled',
                ]);
            } elseif ($question['TYPE_REP'] == 'T') {
                $listeRep = $aoQstR->findAll(['NO_AO' => $theme['NO_AO'], 'ID_THEME' => $theme['ID_THEME'], 'ID_QUEST' => $question['ID_QUEST']]);
                $listeValue = [];

                $arrayJS = '[';

                $repPossible = false;
                foreach ($listeRep as $rep) {
                    $listeValue[$rep['ID_REP']] = $rep['TXT_REP'];

                    if (Sql::toBool($rep['COM_MANUEL'])) {
                        $arrayJS .= "'" . $rep['ID_REP'] . "',";

                        if ($question['REP_TAB'] == $rep['ID_REP']) {
                            $repPossible = true;
                        }
                    }
                }

                $arrayJS .= ']';

                $html .= $formExtension->inputAdvance('SELECT', [
                    'name' => 'REP_TAB-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'],
                    'myFunction' => 'updateReponse',
                    'myParams' => '[' . json_encode(['name' => "REP_TAB", 'theme' => $theme['ID_THEME'], 'question' => $question['ID_QUEST']]) . ']',
                    'optionVide' => true,
                    'listeValue' => $listeValue,
                    'value' => $question['REP_TAB'],
                    'option' => $canEditSupplier ? '' : 'readOnly',
                ]);

                $html .= $formExtension->inputAdvance('TEXTAREA', [
                    'name' => 'NM_COM-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'],
                    'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                    'paramsValidator' => "{'sizeMin' : 0, 'sizeMax' : 3000}",
                    'option' => ($repPossible && $canEditSupplier) ? '' : 'readOnly',
                    'addStyle' => 'margin-top:10px;',
                    'myFuncValidator' => 'updateReponse',
                    'paramFuncValidator' => '[' .
                        json_encode(['name' => "NM_COM", 'theme' => $theme['ID_THEME'], 'question' => $question['ID_QUEST']]) . ']',
                    'value' => $question['comRep'],
                ]);

                $html .= '<script>
                            $(\'#input_REP_TAB-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'] . '\').change(function(){ 
                                            $(\'#input_REP_TAB-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'] . '\').change(function(){ 
                            $(\'#input_REP_TAB-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'] . '\').change(function(){ 
                                if($.inArray($(this).val(), ' . $arrayJS . ') === -1){
                                    $(\'#input_NM_COM-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'] . '\').attr(\'readOnly\', true);
                                } else {
                                    $(\'#input_NM_COM-' . $theme['ID_THEME'] . '-' . $question['ID_QUEST'] . '\').attr(\'readOnly\', false);
                                }
                            });
                        </script>';
            }

            $html .= '</div><hr>';
        }


        $html .= '      </div>
                    </div>
                </div>';
        return $html;
    }
}
