<?php

namespace Modules\Additional\Specifique\Client128\Modules\Panier\Service;

use Entity\Model\Centre;
use Entity\Model\CtcCtr;
use Entity\Model\OxaUserPanier;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Sql;
use Modules\Panier\Service\PanierEnteteService;

class UpdateValueCtrLivraison
{
    /**
     * le fichier existe aussi pour le client 61, donc on met la fonction qui retourne false pour éviter les erreurs le temps de mieux gérer les spécifiques
     * @param \PDO $pdo
     */
    public static function initCentreLivraisonSI(\PDO $pdo, string $si = null) : bool
    {
        return false;
    }

    /**
     * @param \PDO $pdo
     */
    public static function initCentreLivraisonCG(\PDO $pdo, string $cg = null) : bool
    {
        $newsCentre = ChampSupp::getEnregByValueSpecific([
            'COD_TAB' => 'CENTRE',
            'VALEUR' => $cg,
            'typedico' => 'PARNCS0128',
            'codedico' => 'NCS_CENTRE_INSTALLATION',
        ], $pdo);

        return self::initCentre($pdo, $newsCentre['COD_ENR']);
    }

    private static function initCentre(\PDO $pdo, string $newsCentre = null) : bool
    {
        $panier = (new OxaUserPanier($pdo))->find([
            'id_user' => $_SESSION['id_user'],
            'id_panier'=> $_SESSION['id_panier'],
        ], ['LIV_CTR']);

        if ($panier['LIV_CTR'] != $newsCentre) {
            $infoCentre = (new Centre($pdo))->find($newsCentre);

            if (sql::boolSql($infoCentre['TRS_INTER'])) {
                $MOD_TRS = $infoCentre['MOD_TRS'];
            }

            $ctcCtrEntity = new CtcCtr($pdo);
            $ctcCtr = $ctcCtrEntity->fetchAll([], ['filter_egal_COD_CTR' => $newsCentre, 'filter_egal_CTC_RCA' => 'T', 'tri_CTC_IND' => 'asc']);
            $ctcCtr = $ctcCtr[0]??[];

            (new PanierEnteteService($pdo))->changeCentreLivraison([
                'LIV_CTR'   => $newsCentre,

                'LIV_ADR'   => $infoCentre['LIV_ADR']??'',
                'LIV_VILLE' => $infoCentre['LIV_VILLE']??'',
                'LIV_CP'    => $infoCentre['LIV_CP']??'',
                'LIV_PAYS'  => $infoCentre['LIV_PAYS']??'',
                'MOD_TRS'   => $MOD_TRS??'',
            
                'CTC_NOM'   => $ctcCtr['CTC_NOM']??'',
                'CTC_FCT'   => $ctcCtr['CTC_FCT']??'',
                'CTC_FAX'   => $ctcCtr['CTC_FAX']??'',
                'CTC_TEL'   => $ctcCtr['CTC_TEL']??'',
                'CTC_GSM'   => $ctcCtr['CTC_GSM']??'',
                'CTC_MAIL'  => $ctcCtr['CTC_MAIL']??4,
            ]);

            return true;
        }

        return false;
    }
}
