<?php
namespace Modules\Parametrage\Oxalink\Controller;

use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Trad\Trad;
use Helpers\Outil\Sql;
use Helpers\Validator\Validator;
use Entity\Model\Paravrac;
use Helpers\Ariane\ArianeSub;
use Modules\Parametrage\Oxalink\Repository\ParametrageOxalink;
use Entity\Model\ParamDico;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Securite\Securite;
use Helpers\Session\ParseBase1;

class ParametrageFrsOxalinkController extends Controller
{

    public string $menuActive = '';
    public string $menuLeft = '';
    
    public function init():void
    {
        if (($_SESSION['ariane'][0]['path']??null) == $this->router->generateUri('Parametrage.Parametrage.index')) {
            $this->menuActive = 'Parametrage';
            $this->menuLeft = 'Parametrage';
        } else {
            $this->menuActive = 'Fournisseur';
            $this->menuLeft = 'Parametrage';
        }
    }
    public function fournisseurAction() : string
    {
        $post = $this->request->getParsedBody();

        $param = file((new ParseBase1())->getRep()->etc.'OXALINK_ ListeChampsFourn.oxa');

        $listeChpsFrs = [];
        $regleAffichage = [];
        
        $groupeChps = [];
        
        $groupe = false;
        
        /** @phpstan-ignore-next-line */
        foreach ($param as $ligne) {
            if (substr($ligne, 0, 4)=='GRP;') {
                $explode = explode(';', $ligne);
                $groupe = $explode[1];

                if ($explode[0]=='GRP') {
                    $listeChpsFrs['GRP_'.$explode[1]] = $explode[2];
                    $regleAffichage['GRP_'.$explode[1]]['VISI'] = $explode[3];
                    $regleAffichage['GRP_'.$explode[1]]['OBLI'] = $explode[4];
                }
            }
            
            if (substr($ligne, 0, 4)=='END;') {
                $groupe = false;
            }
            
            if (substr($ligne, 0, 4)!='REM;' && substr($ligne, 0, 4)!='GRP;' && substr($ligne, 0, 4)!='END;' && $groupe == false) {
                $explode = explode(';', $ligne);
 
                if ($explode[0]=='CHP' && $explode[1]=='CONTFOUR.CTC_CONSULT') {
                    $listeChpsFrs[$explode[1]] = $explode[2];
                    $regleAffichage[$explode[1]]['VISI'] = true;
                    $regleAffichage[$explode[1]]['OBLI'] = false;
                } elseif ($explode[0]=='CHP') {
                    $listeChpsFrs[$explode[1]] = $explode[2];
                    $regleAffichage[$explode[1]]['VISI'] = $explode[3];
                    $regleAffichage[$explode[1]]['OBLI'] = $explode[4]??0;
                } elseif ($explode[0]=='STR') {
                    $listeChpsFrs['SPLIT_'.$explode[1]] = $explode[2];
                    $regleAffichage['SPLIT_'.$explode[1]]['VISI'] = $explode[3];
                }
            }
            
            if ($groupe && substr($ligne, 0, 4)=='CHP;') {
                $explode = explode(';', $ligne);
                $groupeChps[$groupe][] = $explode[1];
            }
        }
        
        $listeCS = [];
        if ($regleAffichage['SPLIT_ListChampsSup']['VISI']=='O') {
            $listeCS = ChampSupp::listeCSoxalink($this->pdo);
        }

        $paramOxalink = new ParametrageOxalink($this->pdo);
        $paravrac = new Paravrac($this->pdo);

        if ($post) {
            $validator = $this->createValidator();
 
            
            $paramdico = new ParamDico($this->pdo);
            
            $validator->isCheck($post['CAPTCHA_ACTIF']);
            
            if (!in_array($post['PROSPECT_REFERENCE'], ['P', 'R'])) {
                $post['PROSPECT_REFERENCE'] = 'R';
            }
            $paravrac->set('PF_OXALINK', 'PROSPECT_REFERENCE', $post['PROSPECT_REFERENCE']);
            
            /** CAPTCHA_ACTIF **/
            $paravrac->set('PF_OXALINK', 'CAPTCHA_ACTIF', $post['CAPTCHA_ACTIF']? 'O':'N');
            
            $paramDicoTmp = $paramdico->findAll(['TYPEDICO' => 'OXALINK_FOURN_CHP']);
            
            $arrayParamDico = [];
            foreach ($paramDicoTmp as $param) {
                $arrayParamDico[$param['ID1']][$param['ID2']] = $param['LIBELLE'];
            }
            
            $paramDicoTmp2 = $paramdico->findAll(['TYPEDICO' => 'OXALINK_FOURN_STR']);
            
            $arrayParamDicoStr = [];
            foreach ($paramDicoTmp2 as $param) {
                $arrayParamDicoStr[$param['ID1']] = $param['LIBELLE'];
            }

            foreach ($listeChpsFrs as $key => $value) {
                if (substr($key, 0, 6)!='SPLIT_' && substr($key, 0, 4)!='GRP_') {
                    $insertTab = explode('.', $key);
                    $keyPost = $insertTab[0].'_'.$insertTab[1];
                    $validator->isCheck($post[$keyPost]);
                    $validator->isCheck($post['obli_'.$keyPost]);
                    
                    if (isset($arrayParamDico[$insertTab[0]][$insertTab[1]])) {
                        $paramdico->update(['ALPHA1' => $post[$keyPost]? 'N':'O', 'ALPHA2' => $post['obli_'.$keyPost]? 'O':'N'], ['TYPEDICO' => 'OXALINK_FOURN_CHP','ID1' => $insertTab[0], 'ID2' => $insertTab[1]]);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'OXALINK_FOURN_CHP', 'ID1' => $insertTab[0], 'ID2' => $insertTab[1], 'ALPHA1' => $post[$keyPost]? 'N':'O', 'ALPHA2' => $post['obli_'.$keyPost]? 'O':'N']);
                    }
                } elseif (substr($key, 0, 4)=='GRP_') {
                    $keyPost = $key;
                    
                    $keyTmp =  substr($key, 4);
                    
                    $validator->isCheck($post[$keyPost]);
                    $validator->isCheck($post['obli_'.$keyPost]);

                    foreach ($groupeChps[$keyTmp] as $sousGroupe) {
                        $insertTab = explode('.', $sousGroupe);
                        
                        if (isset($arrayParamDico[$insertTab[0]][$insertTab[1]])) {
                            $paramdico->update(['ALPHA1' => $post[$keyPost]? 'N':'O', 'ALPHA2' => $post['obli_'.$keyPost]? 'O':'N', 'LIBELLE' => $keyTmp], ['TYPEDICO' => 'OXALINK_FOURN_CHP','ID1' => $insertTab[0], 'ID2' => $insertTab[1]]);
                        } else {
                            $paramdico->insert(['TYPEDICO' => 'OXALINK_FOURN_CHP', 'ID1' => $insertTab[0], 'ID2' => $insertTab[1], 'ALPHA1' => $post[$keyPost]? 'N':'O', 'ALPHA2' => $post['obli_'.$keyPost]? 'O':'N', 'LIBELLE' => $keyTmp]);
                        }
                    }
                } elseif (substr($key, 0, 6)=='SPLIT_') {
                    if ($regleAffichage[$key]['VISI']=='N') {
                        $post[$key] = true;
                    }
                    
                    $validator->isCheck($post[$key]);

                    $structure = substr($key, 6);

                    if (isset($arrayParamDicoStr[$structure])) {
                        $paramdico->update(['ALPHA1' => $post[$key]? 'N':'O'], ['TYPEDICO' => 'OXALINK_FOURN_STR','ID1' => $structure]);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'OXALINK_FOURN_STR', 'ID1' => $structure, 'ALPHA1' => $post[$key]? 'N':'O']);
                    }
                }
            }
            
            foreach ($listeCS as $cs) {
                $validator->isCheck($post['CS_'.$cs['NUM_FIX']]);
                $validator->isCheck($post['obli_CS_'.$cs['NUM_FIX']]);
                ChampSupp::updateCSoxalink($this->pdo, $cs['NUM_FIX'], $post['CS_'.$cs['NUM_FIX']], $post['obli_CS_'.$cs['NUM_FIX']]);
            }
        } else {
            $post['PROSPECT_REFERENCE'] = $paravrac->getValue('PF_OXALINK', 'PROSPECT_REFERENCE') ?? 'R';
            $post['CAPTCHA_ACTIF']      = $paravrac->getFlag('PF_OXALINK', 'CAPTCHA_ACTIF');
        }
        
        $listeParamChpsFrs = $paramOxalink->listeParamChpsFrs();
        $chpsVisibile = [];
        foreach ($listeParamChpsFrs as $ParamChpsFrs) {
            if ($ParamChpsFrs['LIBELLE']) {
                $chpsVisibile['GRP_'.$ParamChpsFrs['LIBELLE']]= $ParamChpsFrs['ALPHA1'];
                $chpsObligatoire['obli_GRP_'.$ParamChpsFrs['LIBELLE']] = $ParamChpsFrs['ALPHA2'];
            } elseif ($ParamChpsFrs['TYPEDICO']=='OXALINK_FOURN_CHP') {
                $chpsVisibile[$ParamChpsFrs['ID1'].'.'.$ParamChpsFrs['ID2']] = $ParamChpsFrs['ALPHA1'];
                $chpsObligatoire['obli_'.$ParamChpsFrs['ID1'].'.'.$ParamChpsFrs['ID2']] = $ParamChpsFrs['ALPHA2'];
            } else {
                if ('SPLIT_'.$ParamChpsFrs['ID1'] == 'SPLIT_Identity' || 'SPLIT_'.$ParamChpsFrs['ID1'] == 'SPLIT_ListContacts') {
                    // To set Identity "All" on checked by default
                    $chpsVisibile['SPLIT_'.$ParamChpsFrs['ID1']] = 'O';
                    $regleAffichage['SPLIT_'.$ParamChpsFrs['ID1']]['VISI'] = 'O';
                } else {
                    $chpsVisibile['SPLIT_'.$ParamChpsFrs['ID1']] = $ParamChpsFrs['ALPHA1'];
                }
            }
        }

        $trad = $this->getTranslationService();
        
        $liste_PROSPECT_REFERENCE = [
            'R'=> $trad->t('Référencé'),
            'P' => $trad->t('Prospect'),
        ];

        //Ariane::generate(0, $trad->t('Gestion des paramètres'), $post);
        ArianeSub::generate(0, 1, $trad->t('Demande référencement'), $this->router->generateUri('Parametrage.ParametrageOxalink.fournisseur'), 1);
        
        return $this->renderer->render('@ParamOxalink/demandeReferencement', [
            'menuActive' => $this->menuActive,
            'menuLeft' => $this->menuLeft,
            'post' => $post,
            'liste_PROSPECT_REFERENCE' => $liste_PROSPECT_REFERENCE,
            'listeChpsFrs' => $listeChpsFrs,
            'chpsVisibile' => $chpsVisibile,
            'chpsObligatoire' => $chpsObligatoire??[],
            'regleAffichage' => $regleAffichage,
            'listeCS' => $listeCS,
        ]);
    }
}
