<?php
namespace Modules\API\APIInterne\OxaMobility\Controller;

use SimpleXMLElement;
use Helpers\Trad\Trad;
use Skeleton\Controller\Controller;
use Helpers\Outil\Outils;
use Entity\Model\Fourniss;
use Entity\Model\OxaUsers;
use Helpers\Fichier\Fichier;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Roles;

// phpcs:ignore
class PAGE_FicheFournController extends Controller
{

    protected $ID_CHP;

    public function init() : void
    {
        /** A deplacer dans absAPIcontroller plus tard car pas top */
        $trad = $this->getTranslationService();
        if ($trad instanceof Trad) {
            $trad->setLang($_SESSION['Session_Langue']);
        }
    }

    /**
     * @OA\Post(
     *      path="/page_fichefourn/init",
     *      summary="retourne les informations de contact d'un fournisseur",
     *      tags={"Fiche fournisseur"},
     *      @OA\RequestBody(
     *          description="CodeSoc",
     *          required=true,
     *          @OA\MediaType(
     *              mediaType="application/xml",
     *          )
     *      ),
     *      @Oa\Response(
     *          response="200",
     *          description="Succès",
     *          @OA\XmlContent(
     *             type="array",
     *             @OA\items(
     *                  type="string"))
     *       )
     * )
     */
    public function INITAction($body = [], $jwtPayload = [], $json = true)
    {
        $trad = $this->getTranslationService();
        $codeFourn = $body['CodeFourn'];
        
        $critere = array(
            'COD_FOURN' => $body['CodeFourn'],
            'id_panier' => $body['IdPanier'] ?? 0,
            'CRITERE_REGROUP' => ''
        );

        $oxauser = new OxaUsers($this->pdo);
        $critere['id_user'] = $oxauser->find(['login' => $jwtPayload['user']])['id_user'];

        $fourniss = new Fourniss($this->pdo);
        $fournissArray = $fourniss->find($codeFourn);
        
        $param = new \Modules\GlobalApplication\Repository\Param($this->pdo);
        $liste_champ_frs = $param->getAllFieldsInfoBulle('FOURN', true);

        $gestionFournisseur = new \Modules\Fournisseur\Repository\GestFourniss($this->pdo);

        $i=0;
        if (is_array($liste_champ_frs)) {
            $tmpChampFRS = '';
            
            foreach ($liste_champ_frs as $champarray) {
                unset($liste_champ_frs['ATTR_CHP']);
                unset($liste_champ_frs['MASQ_CHP']);

                if ($champarray['CODE_CHP'] == 'ADR' || $champarray['CODE_CHP'] == 'VILLE1' || $champarray['CODE_CHP'] == 'CPOSTAL' || $champarray['CODE_CHP'] == 'CODE_PAYS') {
                    $tmpChampFRS .= '<Champ>';
                    $arrayTmp = $champarray;
                    foreach ($champarray as $key => $value) {
                        if ($key == 'LIB_CHP') {
                            // reference de la V1 => 'LIB_CHP' => tradNoExtract($champ->getLIB_CHP()),
                            $tmpChampFRS .= '<'.$key.'>'. $trad->t($value).'</'.$key.'>';
                        } elseif ($key == 'NUM_CHP') {
                            $i++;
                            $tmpChampFRS .= '<'.$key.'>'.$i.'</'.$key.'>';
                        } else {
                            $tmpChampFRS .= '<'.$key.'>'.\htmlspecialchars($value, ENT_XML1, 'UTF-8').'</'.$key.'>';
                        }
                    }
                    $tmpChampFRS .= '<VALEUR>'.\htmlspecialchars($fournissArray[$champarray['CODE_CHP']], ENT_XML1, 'UTF-8').'</VALEUR>';
                    
                    $tmpChampFRS .= '</Champ>';
                }
            }
            

            $repoCS = new ChampSupp($this->pdo);
            foreach ($liste_champ_frs as $champ) {
                if (($champ['NUM_CHP'] != 0 || $this->isDroitModificationAdresse($champ['CODE_CHP'])) && !($champ['CODE_CHP'] == 'ADR' || $champ['CODE_CHP'] == 'VILLE1' || $champ['CODE_CHP'] == 'CPOSTAL' || $champ['CODE_CHP'] == 'CODE_PAYS')) {
                    if (stripos($champ['CODE_CHP'], 'CS|') !== false) {
                        // On récupère le numéro du CS
                        $NUM_CSTmp = explode('|', $champ['CODE_CHP']);
                        $NUM_CS = (int) $NUM_CSTmp[1];
                        
                        // On récupère la valeur du CS en question
                        $info_cs = $repoCS->getInfoValueCs('FOURNISS', $codeFourn, $NUM_CS);
                        
                       
                        
                        $champ['VALEUR'] = $info_cs['VALEUR'];
                    }
                    foreach ($fournissArray as $key => $value) {
                        if ($key == $champ['CODE_CHP']) {
                            $champ['VALEUR'] = $value;
                        }
                    }
                    unset($champ['ATTR_CHP']);
                    unset($champ['MASQ_CHP']);
                    $tmpChampFRS .= '<Champ>';
    
                    foreach ($champ as $key => $value) {
                        if ($key == 'LIB_CHP') {
                            // reference de la V1 => 'LIB_CHP' => tradNoExtract($champ->getLIB_CHP()),
                            $tmpChampFRS .= '<'.$key.'>'. $trad->t($value).'</'.$key.'>';
                        } elseif ($key == 'NUM_CHP') {
                            $i++;
                            $tmpChampFRS .= '<'.$key.'>'.$i.'</'.$key.'>';
                        } else {
                            $tmpChampFRS .= '<'.$key.'>'.\htmlspecialchars($value, ENT_XML1, 'UTF-8').'</'.$key.'>';
                        }
                    }
                    $tmpChampFRS .= '</Champ>';
                }
            }
        }


        $return['Fournisseur'] = 'replace0';

        // $liste_champ_frs = $param->getAllFieldsInfoBulle('CTCFOU',true );
        // foreach($liste_champ_frs as $champ)
        // {
        //     foreach($contact as $key => $value)
        //     {
        //         if($key == $champ['CODE_CHP'])
        //         {
        //             $infoContactFrsTMP = [];
        //             unset($champ['CODE_CHP']);
        //             unset($champ['ATTR_CHP']);
        //             unset($champ['MASQ_CHP']);
        //             $infoContactFrsTMP = $champ;
        //             $infoContactFrsTMP['VALEUR'] = $value;
        //             $return['ContactFournisseur'][$key] = $infoContactFrsTMP;
        //         }
        //     }
        // }

        $ArrayString = '';
       
        $contFourAll = $gestionFournisseur->getContactFournisseurAll($codeFourn);
        foreach ($contFourAll as $cont) {
            $ArrayString .= "<Contact>
                <Code>".\htmlspecialchars($cont['IND_FOU'], ENT_XML1)."</Code>
                <Nom>".\htmlspecialchars($cont['NOM'], ENT_XML1)."</Nom>
                <Fonction>".\htmlspecialchars($cont['FONCTION'], ENT_XML1)."</Fonction>,
                <Tel>".\htmlspecialchars($cont['TEL'], ENT_XML1)."</Tel>
                <TelPort>".\htmlspecialchars($cont['TELPORT'], ENT_XML1)."</TelPort>
                <Fax>".\htmlspecialchars($cont['FAX'], ENT_XML1)."</Fax>
                <Email>".\htmlspecialchars($cont['EMAIL'], ENT_XML1)."</Email>
                <Createur>".\htmlspecialchars($cont['CREE_PAR'], ENT_XML1)."</Createur></Contact>";
        }
       
        $return['ListeContactFournisseur'] = 'replace1';
        
        
        
        $trad = $this->getTranslationService();
        $return['Trads']['MLS_Copie'] = $trad->t('Adresse copiée dans le presse-papier');
        $return['Trads']['MLS_Erreur_Adresse'] = $trad->t('Impossible de lire la position GPS de l\'adresse');
        $return['Trads']['MLS_Professionel'] = $trad->t('Professionnel');
        $return['Trads']['MLS_Mobile'] = $trad->t('Mobile');
       
        if ($json) {
            $retourJSON['MPROC_Out'] = $return;
            header('content-type:application/json');
            if ($_SESSION['_debug'] == true) {
                Fichier::createFichierTmp(str_replace('|', '_', $body['Action']).'_Out.json', json_encode($retourJSON));
            }
            return json_encode($retourJSON);
        }
    
        $xml = new SimpleXMLElement('<MPROC_Out/>');
        header('Content-Type: application/xml; charset=utf-8');
        \Helpers\Outil\Outils::array_to_xml($return, $xml, $body['Action']);
        $domxml = new \DOMDocument('1.0');
        $domxml->preserveWhiteSpace = false;
        $domxml->formatOutput = true;
        $domxml->loadXML(str_replace('replace0', $tmpChampFRS, str_replace('replace1', $ArrayString, $xml->asXML())));
        return $domxml->saveXML();
    }

    /**
     * @OA\Post(
     *      path="/page_fichefourn/ifichefournpanier",
     *      summary="retourne les informations de contact du fournisseur d'un panier",
     *      tags={"Fiche fournisseur"},
     *      @OA\RequestBody(
     *          description="CodeSoc",
     *          required=true,
     *          @OA\MediaType(
     *              mediaType="application/xml",
     *          )
     *      ),
     *      @Oa\Response(
     *          response="200",
     *          description="Succès",
     *          @OA\XmlContent(
     *             type="array",
     *             @OA\items(
     *                  type="string"))
     *       )
     * )
     */
    public function IFicheFournPanierAction($body = [], $jwtPayload = [], $json = true)
    {
        $codeFourn = $body['CodeFourn'];
        
        $critere = array(
            'COD_FOURN' => $body['CodeFourn'],
            'id_panier' => $body['IdPanier'] ?? 0,
            'CRITERE_REGROUP' => ''
        );

        $oxauser = new OxaUsers($this->pdo);
        $critere['id_user'] = $oxauser->find(['login' => $jwtPayload['user']])['id_user'];

        $fourniss = new Fourniss($this->pdo);
        $fournissArray = $fourniss->find($codeFourn);
        
        $param = new \Modules\GlobalApplication\Repository\Param($this->pdo);
        $liste_champ_frs = $param->getAllFieldsInfoBulle('FOURN', true);

        $gestionFournisseur = new \Modules\Fournisseur\Repository\GestFourniss($this->pdo);

        $i=0;
        if (is_array($liste_champ_frs)) {
            $tmpChampFRS = '';
            $panier = new \Modules\Panier\Repository\PanierEntete($this->pdo);
             
            if ($panierFour =$panier->getInfoFourPanier($critere)) {
                foreach ($liste_champ_frs as $champarray) {
                    unset($champarray['ATTR_CHP']);
                    unset($champarray['MASQ_CHP']);

                    if ($champarray['CODE_CHP'] == 'ADR' || $champarray['CODE_CHP'] == 'VILLE1' || $champarray['CODE_CHP'] == 'CPOSTAL' || $champarray['CODE_CHP'] == 'CODE_PAYS') {
                        $tmpChampFRS .= '<Champ>';
                        $arrayTmp = $champarray;
                        foreach ($champarray as $key => $value) {
                            if ($key == 'NUM_CHP') {
                                $i++;
                                $tmpChampFRS .= '<'.$key.'>'.$i.'</'.$key.'>';
                            } else {
                                $tmpChampFRS .= '<'.$key.'>'.$value.'</'.$key.'>';
                            }
                        }
                        $tmpChampFRS .= '<VALEUR>'.$panierFour[$champarray['CODE_CHP']].'</VALEUR>';
                        
                        $tmpChampFRS .= '</Champ>';
                    }
                }
            }
            $repoCS = new ChampSupp($this->pdo);
            foreach ($liste_champ_frs as $champ) {
                if (($champ['NUM_CHP'] != 0 || $this->isDroitModificationAdresse($champ['CODE_CHP'])) && !($champ['CODE_CHP'] == 'ADR' || $champ['CODE_CHP'] == 'VILLE1' || $champ['CODE_CHP'] == 'CPOSTAL' || $champ['CODE_CHP'] == 'CODE_PAYS')) {
                    if (stripos($champ['CODE_CHP'], 'CS|') !== false) {
                        // On récupère le numéro du CS
                        $NUM_CSTmp = explode('|', $champ['CODE_CHP']);
                        $NUM_CS = (int) $NUM_CSTmp[1];
                        
                        // On récupère la valeur du CS en question
                        $info_cs = $repoCS->getInfoValueCs('FOURNISS', $codeFourn, $NUM_CS);
                        
                       
                        
                        $champ['VALEUR'] = $info_cs['VALEUR'];
                    }
                    foreach ($fournissArray as $key => $value) {
                        if ($key == $champ['CODE_CHP']) {
                            $champ['VALEUR'] = $value;
                        }
                    }
                    unset($champ['ATTR_CHP']);
                    unset($champ['MASQ_CHP']);
                    $tmpChampFRS .= '<Champ>';
    
                    foreach ($champ as $key => $value) {
                        if ($key == 'NUM_CHP') {
                            $i++;
                            $tmpChampFRS .= '<'.$key.'>'.$i.'</'.$key.'>';
                        } else {
                            $tmpChampFRS .= '<'.$key.'>'.$value.'</'.$key.'>';
                        }
                    }
                    $tmpChampFRS .= '</Champ>';
                }
            }
        }


        $return['Fournisseur'] = 'replace0';

        // $liste_champ_frs = $param->getAllFieldsInfoBulle('CTCFOU',true );
        // foreach($liste_champ_frs as $champ)
        // {
        //     foreach($contact as $key => $value)
        //     {
        //         if($key == $champ['CODE_CHP'])
        //         {
        //             $infoContactFrsTMP = [];
        //             unset($champ['CODE_CHP']);
        //             unset($champ['ATTR_CHP']);
        //             unset($champ['MASQ_CHP']);
        //             $infoContactFrsTMP = $champ;
        //             $infoContactFrsTMP['VALEUR'] = $value;
        //             $return['ContactFournisseur'][$key] = $infoContactFrsTMP;
        //         }
        //     }
        // }

        $ArrayString = '';
       
        $contFourAll = $gestionFournisseur->getContactFournisseurAll($codeFourn);
        foreach ($contFourAll as $cont) {
            $ArrayString .= "<Contact>
                <Code>".$cont['IND_FOU']."</Code>
                <Nom>".$cont['NOM']."</Nom>
                <Fonction>".$cont['FONCTION']."</Fonction>,
                <Tel>".$cont['TEL']."</Tel>
                <TelPort>".$cont['TELPORT']."</TelPort>
                <Fax>".$cont['FAX']."</Fax>
                <Email>".$cont['EMAIL']."</Email>
                <Createur>".$cont['CREE_PAR']."</Createur></Contact>";
        }
       
        $return['ListeContactFournisseur'] = 'replace1';
        
        $trad = $this->getTranslationService();
        $return['Trads']['MLS_Txt_Adresse'] = $trad->t('Adresse') . $trad->colon();
        $return['Trads']['MLS_Txt_Plan'] = $trad->t('Plan') . $trad->colon();
        $return['Trads']['MLS_Txt_Contacts'] = $trad->t('Contacts') . $trad->colon();
        $return['Trads']['MLS_Txt_Err_Serv'] = $trad->t('Impossible de lire la réponse du serveur. Veuillez recommencer, ou contactez votre administrateur.');
        
    
       
        if ($json) {
            $retourJSON['MPROC_Out'] = $return;
            header('content-type:application/json');
            if ($_SESSION['_debug'] == true) {
                Fichier::createFichierTmp(str_replace('|', '_', $body['Action']).'_Out.json', json_encode($retourJSON));
            }
            return json_encode($retourJSON);
        }
    
        $xml = new SimpleXMLElement('<MPROC_Out/>');
        header('Content-Type: application/xml; charset=utf-8');
        \Helpers\Outil\Outils::array_to_xml($return, $xml, $body['Action']);
        $domxml = new \DOMDocument('1.0');
        $domxml->preserveWhiteSpace = false;
        $domxml->formatOutput = true;
        $domxml->loadXML(str_replace('replace0', $tmpChampFRS, str_replace('replace1', $ArrayString, $xml->asXML())));
        return $domxml->saveXML();
    }

    /**
     * @OA\Post(
     *      path="/page_fichefourn/isdroitmodificationadresse",
     *      summary="retourne vrai si l'utilisateur a le droit de modifier l'adresse d'un fournisseur",
     *      tags={"Fiche fournisseur"},
     *      @OA\RequestBody(
     *          description="CodeSoc",
     *          required=true,
     *          @OA\MediaType(
     *              mediaType="application/xml",
     *          )
     *      ),
     *      @Oa\Response(
     *          response="200",
     *          description="Succès",
     *          @OA\XmlContent(
     *             type="array",
     *             @OA\items(
     *                  type="string"))
     *       )
     * )
     */
    public function isDroitModificationAdresse($CODE_CHP = null)
    {
        $result = false;
        if (is_null($CODE_CHP)) {
            $result = Roles::droitsUtilisateur($this->pdo, 'HA_CDE_ADR');
        } else {
            $result = Roles::droitsUtilisateur($this->pdo, 'HA_CDE_ADR') && ($CODE_CHP == 'ADR' || $CODE_CHP == 'VILLE1' || $CODE_CHP == 'CPOSTAL' || $CODE_CHP == 'CODE_PAYS');
        }
        return $result;
    }

    // phpcs:ignore
    public function setID_CHP($v)
    {
        $this->ID_CHP = $v;
    }
}
