<?php
namespace Modules\Parametrage\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 Entity\Model\ParamDico;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Securite\Securite;
use Modules\Parametrage\Repository\ParametrageOxaproc;

class ParametrageFournisseurController extends Controller
{

    /**
     * menuActive
     *
     * @var string
     */
    public $menuActive = '';
    /**
     * menuLeft
     *
     * @var string
     */
    public $menuLeft = '';
    /**
     * indexAriane
     *
     * @var int
     */
    public $indexAriane = 0;
    /**
     * init
     *
     * @return void
     */
    public function init()
    {
        if (($_SESSION['ariane'][0]['path']??null) == $this->router->generateUri('Parametrage.Parametrage.index')) {
            $this->menuActive = 'Parametrage';
            $this->menuLeft = 'Parametrage';
            $this->indexAriane = 1;
        } else {
            $this->menuActive = 'Fournisseur';
            $this->indexAriane = 0;
        }
    }
    /**
     * @return string
     */
    public function rulesAction() : string
    {
        
        $post = $this->request->getParsedBody();
        
        /// init de l'ariane
        \Helpers\Ariane\ArianeSub::init();

        $param = file($_SESSION['_etc'].'OXAPROC_ ListeChampsFourn.oxa');

        $listeChpsFrs = [];
        $regleAffichage = [];
        
        $groupeChps = [];
        
        $groupe = false;

        $paravrac = new Paravrac($this->pdo);
        $paramdico = new ParamDico($this->pdo);
      
        if ($param) {
            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') {
                        $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);
        // }
        
        $BlocCsObligatoire = false;
        
        foreach ($listeCS as $cs) {
            if ($post) {
                $listeChpsFrs['CS_'.$cs['NUM_FIX']]['VISI'] = ($cs['OXALINK_VIS'] == 'O' ? 'on':'');
                $listeChpsFrs['CS_'.$cs['NUM_FIX']]['OBLI'] = ($cs['OXALINK_OBLIG'] == 'O' ? 'on':'');
                $listeChpsFrs['CS_'.$cs['NUM_FIX']] = ($cs['OXALINK_VIS'] == 'O' ? 'on':'');
            }
            if ($cs['OXALINK_OBLIG'] == 'O') {
                $BlocCsObligatoire = true;
            }
        }
        
        $paramOxaproc = new ParametrageOxaproc($this->pdo);


        if ($post) {
            $paramdico->delete(['TYPEDICO'=> 'OXAPROC_FOURN_CHP']);
            $paramdico->delete(['TYPEDICO'=> 'OXAPROC_FOURN_STR']);
            
            $validator = $this->createValidator();
        
 
            // champs obligatoire lors de l'inscription
            $post['obli_FOURNISS_RS'] = 'on';
            $post['FOURNISS_RS'] = 'on';

            $post['obli_GRP_ADR'] = 'on';
            $post['GRP_ADR'] = 'on';
            
            $validator->isCheck($post['CAPTCHA_ACTIF']);
            
            $post['CAPTCHA_ACTIF'] = $post['CAPTCHA_ACTIF']? 'O':'N';

            /** CAPTCHA_ACTIF **/
            if (count($paravrac->find(['TYPEPARV' => 'PF_OXAPROC', 'CODEPARV' => 'CAPTCHA_ACTIF'])) != 0) {
                $paravrac->update(['LIB01PARV' => $post['CAPTCHA_ACTIF']], ['TYPEPARV' => 'PF_OXAPROC', 'CODEPARV' => 'CAPTCHA_ACTIF']);
            } else {
                $paravrac->insert(['TYPEPARV' => 'PF_OXAPROC', 'CODEPARV' => 'CAPTCHA_ACTIF', 'LIB01PARV' => $post['CAPTCHA_ACTIF']]);
            }
           
            foreach ($listeChpsFrs as $key => $value) {
                if (substr($key, 0, 6)!='SPLIT_' && substr($key, 0, 4)!='GRP_' && substr($key, 0, 3)!='CS_') {
                    $insertTab = explode('.', $key);
                    $keyPost = $insertTab[0].'_'.$insertTab[1];
                    $keyPostVisu = $insertTab[0].'_'.$insertTab[1];
                    
                    $validator->isCheck($post[$keyPost]);
                    $validator->isCheck($post['obli_'.$keyPost]);

                    if (count($paramdico->find(['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => $insertTab[0], 'ID2' => $insertTab[1]])) != 0) {
                        $paramdico->update(
                            [
                                'ALPHA1' => (($post[$keyPostVisu] == 1)? 'O':'N'),
                                'ALPHA2' => (($post['obli_'.$keyPost]) == 1? 'O':'N'),
                                'ID3' => $structure ?? ''
                            ],
                            ['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => $insertTab[0], 'ID2' => $insertTab[1]]
                        );
                    } else {
                        $paramdico->insert(
                            [
                                'TYPEDICO' => 'OXAPROC_FOURN_CHP',
                                'ID1' => $insertTab[0],
                                'ID2' => $insertTab[1],
                                'ALPHA1' => (($post[$keyPostVisu] == 1)? 'O':'N'),
                                'ALPHA2' => (($post['obli_'.$keyPost] == 1)? 'O':'N'),
                                'ID3' => $structure ?? ''
                            ]
                        );
                    }
                } 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 (count($paramdico->find(['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => $insertTab[0], 'ID2' => $insertTab[1]])) != 0) {
                            $paramdico->update(['ALPHA1' => $post[$keyPost]? 'O':'N', 'ALPHA2' => $post['obli_'.$keyPost]? 'O':'N', 'ID3' => $structure ?? ''], ['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => $insertTab[0], 'ID2' => $insertTab[1]]);
                        } else {
                            $paramdico->insert(['TYPEDICO' => 'OXAPROC_FOURN_CHP', 'ID1' => $insertTab[0], 'ID2' => $insertTab[1], 'ID3' => $structure ?? '', 'ALPHA1' => $post[$keyPost]? 'O':'N', 'ALPHA2' => $post['obli_'.$keyPost]? 'O':'N', 'LIBELLE' => $keyTmp ]);
                        }
                    }
                } elseif (substr($key, 0, 6)=='SPLIT_') {
                    if ($regleAffichage[$key]['VISI']=='N') {
                        $post[$key] = true;
                    }
                    
                    $structure = substr($key, 6);
                    $validator->isCheck($post[$key]);

                    if (count($paramdico->find(['TYPEDICO' => 'OXAPROC_FOURN_STR','ID1' => $structure])) != 0) {
                        $paramdico->update(['ALPHA1' => $post[$key]? 'O':'N', 'ID2' => $value], ['TYPEDICO' => 'OXAPROC_FOURN_STR','ID1' => $structure]);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'OXAPROC_FOURN_STR', 'ID1' => $structure, 'ALPHA1' => $post[$key]? 'O':'N', 'ID2' => $value]);
                    }
                } elseif (substr($key, 0, 3)=='CS_') {
                    // $insertTab = explode('.', $key);
                    // $keyPost = $insertTab[0].'_'.$insertTab[1];
                    // $keyPostVisu = $insertTab[0].'_'.$insertTab[1];
                    if (isset($listeChpsFrs[$key]['VISI'])) {
                        $post[$key] = $listeChpsFrs[$key]['VISI'];
                        $post['obli_'.$key] = $listeChpsFrs[$key]['OBLI'];
                    }

                    $validator->isCheck($post[$key]);
                    $validator->isCheck($post['obli_'.$key]);

                    if (count($paramdico->find(['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => 'CS', 'ID2' => $key])) != 0) {
                        $paramdico->update(
                            [
                                'ALPHA1' => (($post[$key] == 1)? 'O':'N'),
                                'ALPHA2' => (($post['obli_'.$key]) == 1? 'O':'N'),
                                'ID3' => 'CS'
                            ],
                            ['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => 'CS', 'ID2' => $key]
                        );
                    } else {
                        $paramdico->insert(
                            [
                                'TYPEDICO' => 'OXAPROC_FOURN_CHP',
                                'ID1' => 'CS',
                                'ID2' =>$key,
                                'ALPHA1' => (($post[$key] == 1)? 'O':'N'),
                                'ALPHA2' => (($post['obli_'.$key] == 1)? 'O':'N'),
                                'ID3' => 'CS'
                            ]
                        );
                    }
                }
            }
            
            //TODO BBA
            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'] = Sql::paravrac($this->pdo, 'PF_OXAPROC', 'PROSPECT_REFERENCE');
            $post['CAPTCHA_ACTIF']      = Sql::paravrac($this->pdo, 'PF_OXAPROC', 'CAPTCHA_ACTIF')=='N'? false:true;
        }
        
        $listeParamChpsFrs = $paramOxaproc->listeParamChpsFrsOxaproc();
        $chpsVisibile = [];
        foreach ($listeParamChpsFrs as $ParamChpsFrs) {
            if ($ParamChpsFrs['LIBELLE']) {
                $chpsVisibile['GRP_'.$ParamChpsFrs['LIBELLE']]= $ParamChpsFrs['ALPHA1'];
                $chpsObligatoire['obli_GRP_'.$ParamChpsFrs['LIBELLE']] = $ParamChpsFrs['ALPHA2'];
            } elseif ($ParamChpsFrs['TYPEDICO']=='OXAPROC_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'];
                }
            }
        }

        $head = '';

        foreach ($listeChpsFrs as $k => $p) {
            if (substr($k, 0, 6) == 'SPLIT_') {
                $head = $p;
            } else {
                $insertTab = explode('.', $k);

                $paramdico->update(['ALPHA3' => $head], ['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID2' => $insertTab[1] ?? '', 'ID1' => $insertTab[0]]);
            }
        }

        $trad = $this->getTranslationService();
        
        $liste_PROSPECT_REFERENCE = [
            'R'=> $trad->t('Référencé'),
            'P' => $trad->t('Prospect'),
        ];
        Ariane::generate($this->indexAriane, $trad->t('Gestion des paramètres'), $post);
        ArianeSub::generate(0, 1, $trad->t('Création simplifiée'), $this->router->generateUri('Parametrage.ParametrageFournisseur.rules'), 1);
        // ArianeSub::generate(0, 2, $trad->t('Documents rattachés'), $this->router->generateUri('GlobalApplication.DocumentRattaches.document', ['MODULE' => 'Fourniss']));

        return $this->renderer->render('@Parametrage/parametrageFournisseur/parametrage', [
            'menuActive' =>  $this->menuActive,
            'menuLeft' => $this->menuLeft,
            'post' => $post,
            'liste_PROSPECT_REFERENCE' => $liste_PROSPECT_REFERENCE,
            'listeChpsFrs' => $listeChpsFrs,
            'chpsVisibile' => $chpsVisibile,
            'chpsObligatoire' => $chpsObligatoire??[],
            'regleAffichage' => $regleAffichage,
            'listeCS' => $listeCS,
            'BlocCsObligatoire' => $BlocCsObligatoire,
            ]);
    }
}
