<?php
namespace Modules\Panier\Service;

use Entity\Model\CCLDoc;
use Entity\Model\Centre;
use Entity\Model\CtcCtr;
use Entity\Model\OxaUserPanier;
use Entity\Model\OxaUserPanierCsDon;
use Entity\Model\OxaUserPanierFour;
use Entity\Model\OxaUserPanierFourClause;
use Entity\Model\OxaUserPanierFourContact;
use Entity\Model\OxaUserPanierFourDoc;
use Entity\Model\OxaUserPanierFourPj;
use Entity\Model\OxaUserPanierImputation;
use Entity\Model\OxaUserPanierLigne;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Helpers\Trad\Trad;
use Modules\Panier\Repository\PanierEntete;
use Modules\Panier\Repository\PanierLigne;

class PanierService
{
    private \PDO $pdo;

    public function __construct(\PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    /**
     * Undocumented function
     *
     * @param \PDO $pdoOxaFT
     * @param array<mixed> $parametrage
     * @return array<mixed>
     */
    public function getListeArticle(\PDO $pdoOxaFT, $parametrage)
    {
        $panierLigne = new PanierLigne($this->pdo);
        $listeLigneTmp = $panierLigne->getListeLignePanier();
        $articleRepo   = new RequeteArticle($this->pdo, $pdoOxaFT, '');

        $panierRegul = self::panierRegul(null, $this->pdo);

        $listeLigne = [];
        foreach ($listeLigneTmp as $ligne) {
            $ligne['isMultiFrs'] = false;
            
            if ($ligne['COD_ART'] != ''
                && $ligne['CODE_FM'] != ''
                && $ligne['CODE_MET'] != ''
                && $ligne['CODE_SPE'] != ''
                && (OutilPanierService::splitCaracArt($ligne['CARACT_ART_HAP'], 1) || Roles::droitsUtilisateur($this->pdo, 'OX_MOD_FRS'))
                && !$panierRegul
            ) {
                $ligne['isMultiFrs'] = true;
            } elseif ($ligne['type_de_ligne'] == 0
                && OutilPanierService::splitCaracArt($ligne['CARACT_ART_HAP'], 1)
                && !$panierRegul
            ) {
                $ligne['isMultiFrs'] = true;
            } elseif (($ligne['type_de_ligne'] == 1 || ('HAPLUS' == $ligne['ID_CAT'])
                && roles::droitsUtilisateur($this->pdo, 'OX_MOD_FRS'))
                && !$panierRegul
            ) {
                $ligne['isMultiFrs'] = true;
            }

            if ($panierRegul) {
                $ligne['CLASSNUM'] = '';
            }

            if ($ligne['PRIXDEGRESSIF']) {
                $ligne['IDLIGNE'] = $ligne['IDLIGNECAT'];
                $ligne['PRIXDEGRESSIF_VAL'] = $articleRepo->getListePrixDegressif($ligne, $parametrage['AFFTTC'], $ligne['TAUX_TVA']);
            }

            $result     = PanierLigneService::calculePrixUnite($ligne, $ligne['PX_ART'], (float)$ligne['TAUX_TVA'], $parametrage['AFFTTC'], $parametrage['decimal_PU']);
            $unite      = $result['unite'];
            $qteCond    = $result['qteCond'];

            if ($parametrage['AFFTTC']) {
                $ligne['PX_ART'] = $ligne['PX_ART'] * (1 + ($ligne['TAUX_TVA']/100));
            }

            $ligne['PX_ART'] = $ligne['PX_ART'] * $qteCond;
            $ligne['COD_UNIT'] = $unite;

            $listeLigne[$ligne['CRITERE_REGROUP']][] = $ligne;
        }

        return $listeLigne;
    }

    public function delete(string $idPanier, ITrad $trad, bool $withOutInit = false):void
    {
        ValidationPanierService::cleanPanierSession();
        
        $idUser = $_SESSION['id_user'];
        $idDelete = [
            'id_panier' => $idPanier,
            'id_user' => $idUser
        ];

        $idDeleteCAP = [
            'ID_PANIER' => $idPanier,
            'ID_USER' => $idUser
        ];
        
        $listePJ = (new OxaUserPanierFourPj($this->pdo))->findAll($idDelete);
        foreach ($listePJ as $pj) {
            if (!sql::boolSql($pj['LIEN_FICHIER'])) {
                Fichier::deleteFichierPj($pj['nom_piece_sys']);
            }
        }

        $listeDoc = (new OxaUserPanierFourDoc($this->pdo))->findAll($idDeleteCAP);
        foreach ($listeDoc as $doc) {
            Fichier::deleteFichierPj($doc['NOM_FIC_FINAL']);
        }

        (new OxaUserPanier($this->pdo))->delete($idDelete);

        (new OxaUserPanierCsDon($this->pdo))->delete($idDelete);
        (new OxaUserPanierImputation($this->pdo))->delete($idDelete);

        (new OxaUserPanierFour($this->pdo))->delete($idDelete);
        (new OxaUserPanierFourClause($this->pdo))->delete($idDelete);
        (new OxaUserPanierFourPj($this->pdo))->delete($idDelete);
        
        (new OxaUserPanierLigne($this->pdo))->delete($idDelete);
        
        (new CCLDoc($this->pdo))->delete([
            'ID_USER_BASKET'    => $idUser,
            'DOC_NUM'           => $idPanier,
        ]);

        //les colonnes sont en UPPERCASE ici
        (new OxaUserPanierFourDoc($this->pdo))->delete($idDeleteCAP);
        (new OxaUserPanierFourContact($this->pdo))->delete($idDeleteCAP);

        if ($_SESSION['id_panier'] == $idPanier || $idPanier === '0') {
            $_SESSION['id_panier'] = 0;
        }
        
        if ($idPanier === '0' && $withOutInit == false) {
            $nombreLigne = (new PanierLigne($this->pdo))->getNbLignePanier($idPanier, $idUser);

            $panierEnteteService = new PanierEnteteService($this->pdo);
            $panierEnteteService->initPanierEntete($trad, ($nombreLigne? false:true));
            $panierEnteteService->getTotalPanier('0');

            if (array_key_exists('RUPTURE_DA', $_SESSION)) {
                unset($_SESSION['RUPTURE_DA']);
            }
            if (array_key_exists('RUPTURE_DS', $_SESSION)) {
                unset($_SESSION['RUPTURE_DS']);
            }
            if (array_key_exists('RUPTURE_CDE', $_SESSION)) {
                unset($_SESSION['RUPTURE_CDE']);
            }
            if (array_key_exists('RUPTURE_AVEN', $_SESSION)) {
                unset($_SESSION['RUPTURE_AVEN']);
            }
        }
    }
    public function updateCtrLiv(string $id_user, int $id_panier, string $ctr_liv, string $mode_trs = '', int $id_ligne = 0) : void
    {
        $panierLigne = new PanierLigne($this->pdo);
        
        $panierLigne->updateLignePanierCtrLiv($id_user, $id_panier, $ctr_liv, $mode_trs, $id_ligne);
        if ($listeLignePanier = $panierLigne->getAllLignePanier($id_panier)) {
            foreach ($listeLignePanier as $lignePanier) {
                CritereRegroupService::recalculCritereRegroup($this->pdo, $id_panier, $lignePanier['id_lig']);
            }
        }
    }

    public static function panierRegul(?string $CHPSPECCLT = null, ?\PDO $pdo = null):bool
    {
        if (is_null($CHPSPECCLT) && $pdo) {
            $panierEntete = new PanierEntete($pdo);
            $infoEntete = $panierEntete->getEntetePanier($_SESSION['id_panier'], $_SESSION['id_user']);

            $CHPSPECCLT = $infoEntete['CHPSPECCLT'];
        }
        $champSpecifique = explode('=', $CHPSPECCLT);
        if ('REGUL|codfrs' == $champSpecifique[0]) {
            return true;
        }

        return false;
    }
    /**
     * @param string|null $CHPSPECCLT
     * @param \PDO|null $pdo
     * @return string|null
     */
    public static function getFrsRegul(?string $CHPSPECCLT = null, ?\PDO $pdo = null)
    {
        $frsImposer = null;
        if (is_null($CHPSPECCLT) && $pdo) {
            $panierEntete = new PanierEntete($pdo);
            $infoEntete = $panierEntete->getEntetePanier($_SESSION['id_panier'], $_SESSION['id_user']);

            $CHPSPECCLT = $infoEntete['CHPSPECCLT'];
        }

        $champSpecifique = explode('=', $CHPSPECCLT);
        if ('REGUL|codfrs' == $champSpecifique[0] && '' != $champSpecifique[1]) {
            $frsImposer = $champSpecifique[1];
        }

        return $frsImposer;
    }

    public 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 ($newsCentre && $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['ADRESSE']??'',
                'LIV_VILLE' => $infoCentre['VILLE1']??'',
                'LIV_CP'    => $infoCentre['CPOSTAL']??'',
                'LIV_PAYS'  => $infoCentre['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']??'',
            ]);

            return true;
        }

        return false;
    }
}
