<?php
namespace Modules\Panier\Service;

use Entity\Model\CCLDoc;
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\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) || $_SESSION['AuthModifFournisseur'])
                && !$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'])
                && $_SESSION['AuthModifFournisseur'])
                && !$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']);
            }

            $qteCond = 1;
            if ((float)$ligne['CONDITNT'] && $ligne['TXTCOND'] != '') {
                $qteCond = (float)$ligne['CONDITNT'];
            }

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

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

            if ($ligne['TXTCOND']) {
                if ((float)$ligne['CONDITNT'] != 1 && (float)$ligne['CONDITNT'] != 0) {
                    $text = Trad::strBuild(
                        $parametrage['libTrad'],
                        $ligne['TXTCOND'],
                        (number_format($ligne['CONDITNT'], 2, '.', ' ').' '.$ligne['COD_UNIT']),
                        number_format($ligne['PX_ART']/$qteCond, $parametrage['decimal_PU'], '.', ' ').' '.$ligne['COD_DEV'].' / '.$ligne['COD_UNIT']
                    );
                } else {
                    $text = $ligne['TXTCOND'];
                }
                $ligne['COD_UNIT'] = $text;
            }

            $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) {
            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($idUser, $idPanier);

            $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']);
            }

            //todo DELETE V1
            $_SESSION['PANIER_TYPE_SPEC'] = '';
        }
    }
    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);
        
        if ($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;
    }
}
