<?php

namespace Modules\Consultation\TwigExtension;

use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Psr\Container\ContainerInterface;
use Skeleton\Router;
use TwigExtension\FormExtension;
use Entity\Model\AoQstR;

class QuestionnaireContributorExtension extends \Twig\Extension\AbstractExtension
{
    protected \PDO $pdo;
    /**
     * contenaire
     *
     * @var mixed
     */
    protected $contenaire;
    private Router $router;
    private ITrad $trad;
    
    public function __construct(\PDO $pdo, ContainerInterface $contenaire, Router $router)
    {
        $this->pdo = $pdo;
        $this->contenaire = $contenaire;
        $this->router = $router;
        $this->trad = $contenaire->get(ITrad::class);
    }

    public function getFunctions()
    {
        return [

            new \Twig\TwigFunction('buildQuestion', [
                $this,
                'buildQuestion',
            ], [
                'is_safe' => [
                    'html',
                ],
            ]),
        ];
    }
    
    /**
     * buildQuestion
     *
     * @param  array<mixed> $question
     * @param  array<mixed> $supplier
     * @param  bool $canEdit
     * @return string
     */
    public function buildQuestion(array $question, array $supplier, bool $canEdit = true): string
    {
        $formExtension = new FormExtension($this->router, $this->pdo, $this->contenaire);

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

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

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

            $html .= $formExtension->inputAdvance('TEXT', [
                'name' => 'REP_NUM-' . $question['ID_THEME'] . '-' . $question['ID_QUEST'] . '-' . $supplier['CODE_FOU'],
                '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' => $question['ID_THEME'], 'question' => $question['ID_QUEST'], 'supplier' => $supplier['CODE_FOU']]) . ']',
                'myFunction' => 'separateurMilier',
                'myParams' => '[this]',
                'value' => number_format((float)$question['suppliers'][$supplier['CODE_FOU']]['REPONSE'], $decimal, '.', ''),
            ]);
        } elseif ($question['TYPE_REP'] == 'L') {
            $html .= $formExtension->inputAdvance('SELECT', [
                'name' => 'REP_LOG-' . $question['ID_THEME'] . '-' . $question['ID_QUEST'] . '-' . $supplier['CODE_FOU'],
                'myFunction' => 'updateReponse',
                'myParams' => '[' . json_encode(['name' => "REP_LOG", 'theme' => $question['ID_THEME'], 'question' => $question['ID_QUEST'], 'supplier' => $supplier['CODE_FOU']]) . ']',
                'optionVide' => true,
                'listeValue' => ['0' => $this->trad->t('Non'), '1' => $this->trad->t('Oui')],
                'value' => (! Sql::toBool($question['suppliers'][$supplier['CODE_FOU']]['TERMINE'])
                    ? ''
                    : (Sql::toBool($question['suppliers'][$supplier['CODE_FOU']]['REPONSE'])
                        ? '1'
                        : '0')),
            ]);
        } elseif ($question['TYPE_REP'] == 'T') {
            $listeRep = (new AoQstR($this->pdo))
                ->findAll(['NO_AO' => $question['NO_AO'], 'ID_THEME' => $question['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['suppliers'][$supplier['CODE_FOU']]['REPONSE'] == $rep['ID_REP']) {
                        $repPossible = true;
                    }
                }
            }

            $arrayJS .= ']';
            $html .= $formExtension->inputAdvance('SELECT', [
                'name' => 'REP_TAB-' . $question['ID_THEME'] . '-' . $question['ID_QUEST'] . '-' . $supplier['CODE_FOU'],
                'myFunction' => 'updateReponse',
                'myParams' => '[' . json_encode(['name' => "REP_TAB", 'theme' => $question['ID_THEME'], 'question' => $question['ID_QUEST'], 'supplier' => $supplier['CODE_FOU']]) . ']',
                'optionVide' => true,
                'listeValue' => $listeValue,
                'value' => $question['suppliers'][$supplier['CODE_FOU']]['REP_TAB'],
            ]);

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

        $html .= $formExtension->inputAdvance('TEXTAREA', [
            'name' => 'NM_COM' . '-' . $question['ID_THEME'] . '-' . $question['ID_QUEST'] . '-' . $supplier['CODE_FOU'],
            'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
            'placeholder' => $this->trad->t('Commentaire optionnel'),
            'paramsValidator' => "{'sizeMin' : 0, 'sizeMax' : 3000}",
            'addStyle' => 'margin-top:10px;',
            'myFuncValidator' => 'updateReponse',
            'paramFuncValidator' => '[' . json_encode([
                'name' => 'NM_COM',
                'theme' => $question['ID_THEME'],
                'question' => $question['ID_QUEST'],
                'supplier' => $supplier['CODE_FOU']
            ]) . ']',
            'value' => $question['suppliers'][$supplier['CODE_FOU']]['COMMENTAIRE'] ?? '',
            'inputAttr' => [
                'placeholder' => $this->trad->t('Commentaire optionnel'),
            ],
            'option' => ($canEdit ? '' : 'readOnly disabled'),
        ]);

        return $html;
    }
}
