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

use Helpers\Outil\ArrayHelper;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Sql;
use Entity\Model\Paravrac;
use Helpers\Ariane\ArianeSub;
use Entity\Model\ParamDico;
use GuzzleHttp\Psr7\Response;
use Helpers\ChampsSupplementaire\ChampSupp;
use Modules\Parametrage\Oxaproc\Repository\ParametrageOxaproc;
use Helpers\Session\ParseBase1;
use Modules\Parametrage\Fournisseur\Repository\ParametrageFournisseur;

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();
        $trad = $this->getTranslationService();
        
        /// init de l'ariane
        \Helpers\Ariane\ArianeSub::init();

        $param = file((new ParseBase1())->getRep()->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' && ($explode[1] == 'CONTFOUR.CTC_CONSULT' || $explode[1] == 'CONTFOUR.VIBOXAP')) {
                        $listeChpsFrs[$explode[1]] = $explode[2];
                        $regleAffichage[$explode[1]]['VISI'] = true;
                        $regleAffichage[$explode[1]]['OBLI'] = false;
                    } elseif (($explode[0]=='CHP') && ($explode[1]=='FOURNISS.CODE_REGR')) {
                        $listeChpsFrs[$explode[1]] = 'Catégorie';
                        $regleAffichage[$explode[1]]['VISI'] = $explode[3];
                        $regleAffichage[$explode[1]]['OBLI'] = $explode[4]??0;
                    } elseif ($explode[0]=='CHP' && $explode[1] != 'CONTFOUR.OXALINK_ID') {
                        $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 **/
            $paravrac->set('PF_OXAPROC', 'CAPTCHA_ACTIF', $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 (!empty($paramdico->find(['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => $insertTab[0], 'ID2' => $insertTab[1]]))) {
                        $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 (!empty($paramdico->find(['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => $insertTab[0], 'ID2' => $insertTab[1]]))) {
                            $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 (!empty($paramdico->find(['TYPEDICO' => 'OXAPROC_FOURN_STR','ID1' => $structure]))) {
                        $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 (!empty($paramdico->find(['TYPEDICO' => 'OXAPROC_FOURN_CHP','ID1' => 'CS', 'ID2' => $key]))) {
                        $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]]);
            }
        }
        
        $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('Tableau de bord'), $this->router->generateUri('Parametrage.ParametrageFournisseur.dashboardRules'));

        return $this->renderer->render('@ParamFou/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,
        ]);
    }

    /**
     * @return string|Response
     */
    public function dashboardRulesAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $paravrac = new Paravrac($this->pdo);

        if ($post) {
            $listField = array_map(fn($i) => 'CAT_FOUR_'. $i, range(1, 5));
            $paravrac->delete([
                'TYPEPARV' => 'PARAMTDB',
                'CODEPARV' => $listField,
            ]);

            $formData = array_intersect_key($post, array_flip($listField));
            $formData = array_filter($formData); // Remove empty values
            foreach ($formData as $key => $value) {
                $paravrac->insert([
                    'TYPEPARV' => 'PARAMTDB',
                    'CODEPARV' => $key,
                    'LIB01PARV' => $value,
                ]);
            }

            return new Response(200);
        }
        
        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'));
        ArianeSub::generate(0, 2, $trad->t('Tableau de bord'), $this->router->generateUri('Parametrage.ParametrageFournisseur.dashboardRules'), 1);

        return $this->renderer->render('@ParamFou/parametrage_tdb', [
            'menuActive' =>  $this->menuActive,
            'menuLeft' => $this->menuLeft,
            'post' => $post,
            'mapCategorie' => $paravrac->getMap('PARAMTDB'),
        ]);
    }

    /**
     * @return string
     */
    public function addSupplierCategoryAction(
        ParametrageFournisseur $parametrageFournisseur
    ) : string {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $categoriesList = $parametrageFournisseur->getDashboardParam();

        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'));
        ArianeSub::generate(0, 2, $trad->t('Tableau de bord'), $this->router->generateUri('Parametrage.ParametrageFournisseur.dashboardRules'), 1);

        return $this->renderer->render('@ParamFou/parametrage_tdb', [
            'menuActive' =>  $this->menuActive,
            'menuLeft' => $this->menuLeft,
            'post' => $post,
            'categoriesList' => $categoriesList,
        ]);
    }

    /**
     * @return string
     */
    public function deleteSupplierCategoryAction(
        ParametrageFournisseur $parametrageFournisseur
    ) : string {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $pdpId = $this->request->getAttribute('pdp');

        $categoriesList = $parametrageFournisseur->getDashboardParam();

        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'));
        ArianeSub::generate(0, 2, $trad->t('Tableau de bord'), $this->router->generateUri('Parametrage.ParametrageFournisseur.dashboardRules'), 1);

        return $this->renderer->render('@ParamFou/parametrage_tdb', [
            'menuActive' =>  $this->menuActive,
            'menuLeft' => $this->menuLeft,
            'post' => $post,
            'categoriesList' => $categoriesList,
        ]);
    }
}
