<?php

namespace Modules\Consultation\Service;

use Entity\Model\AoEntet;
use Entity\Model\Articles;
use Entity\Model\OxaUserPanier;
use Entity\Model\Paravrac;
use Helpers\Outil\Sql;
use Helpers\Parametres\Constante;
use Helpers\Trad\ITrad;
use Helpers\Trad\Trad;
use Modules\Consultation\Repository\ConsultationPanier;
use Modules\Index\Service\SessionService;
use Modules\Panier\Repository\PanierEntete;
use Modules\Panier\Service\CalculTauxTvaService;
use Modules\Panier\Service\OutilPanierService;
use Modules\Panier\Service\PanierLigneService;
use Modules\Panier\Service\PanierService;

class ConsultationPanierService
{
    private \PDO $pdo;
    private ITrad $trad;
    private string $idConsult;

    /**
     * @var array<mixed> $aoEntet
     */
    private $aoEntet;

    public function __construct(\PDO $pdo, ITrad $trad, string $idConsult)
    {
        $this->pdo = $pdo;
        $this->trad = $trad;
        $this->idConsult = $idConsult;

        $this->aoEntet = (new AoEntet($this->pdo))->find($this->idConsult);
    }

    /**
     * @param string|null $codeSte
     * @return string|null
     */
    public function controleSociete(string $codeSte = null)
    {
        if ($this->aoEntet['TYPE_SG'] == 'S' || !$codeSte) {
            $codeSte = $this->aoEntet['CODE_STE'];
        }

        $sessionService = new SessionService($this->pdo);
        $new_variables_session = $sessionService->getAllValueInitSessionByUserAndSociete($_SESSION['Session_Login'], $codeSte);
        
        if (($new_variables_session['CTR_EMET']??'') == '' || ($new_variables_session['CTR_LIV']??'') == '') {
            return Trad::strBuild($this->trad->t('Veuillez renseigner les informations centre de livraison et / ou centre émetteur de la société @1@'), $codeSte);
        }

        $sessionService->setAllFieldsSessionUser($new_variables_session);

        (new PanierService($this->pdo))->delete('0', $this->trad);

        $_SESSION['id_panier'] = 0;
        return null;
    }

    /**
     * @param array<mixed> $listeFrs
     * @param string|null $codeSte
     * @return void
     */
    public function createPanier(\pdo $pdoOxaFT, $listeFrs, string $codeSte = null):void
    {
        $codeUnit = Sql::paravrac($this->pdo, 'PARAMGEN', 'UNITE_DEF');
        $sfamDefaut = sql::paravrac($this->pdo, 'OXAPROC', 'DEFSFAMMAN');
        
        if ($this->aoEntet['TYPE_SG'] == 'S' || !$codeSte) {
            $codeSte = $this->aoEntet['CODE_STE'];
        }

        $listeFinal = [];
        foreach ($listeFrs as $k => $frs) {
            $listeFinal[] = explode(Constante::spliter, $k)[1];
        }

        $arrayUpdate['COD_DEV'] = $this->aoEntet['DEVISE'];
        if ($this->aoEntet['EMETTEUR']) {
            $arrayUpdate['OUPA_CENTRE_EMETTEUR'] = $this->aoEntet['EMETTEUR'];
        }
        if ($this->aoEntet['CTR_LIV']) {
            $arrayUpdate['LIV_CTR'] = $this->aoEntet['CTR_LIV'];
        }

        (new OxaUserPanier($this->pdo))->update($arrayUpdate, [
            'id_user' => $_SESSION['id_user'],
            'id_panier' => '0',
        ]);

        $panierLigneService = new PanierLigneService($this->pdo, $pdoOxaFT, 'CREEAO');
        $calculTauxTvaService = new CalculTauxTvaService($this->pdo);
        $entetePanier = (new PanierEntete($this->pdo))->getEntetePanier('0', $_SESSION['id_user']);

        $listeNewLine = [];
        $listeLigne = (new ConsultationPanier($this->pdo))->getLigneWithSligne($this->idConsult);

        foreach ($listeLigne as $ligne) {
            if ($this->aoEntet['TYPEDEL'] == 'D' && ($ligne['DELAI'] != '' || $ligne['DELAI'] != '00000000')) {
                $dteLivr = $ligne['DELAI'];
            } elseif ($this->aoEntet['TYPEDEL'] == 'J') {
                $traitementDA = (int) (new Paravrac($this->pdo))->getValue('PARAMGEN', 'DUREETTDA');
                $dteLivr = OutilPanierService::getDateLivraisonMin($ligne['DELAIJ'], $traitementDA);
            } else {
                $dteLivr = '';
            }

            if ($ligne['SSFAMILLE'] == '') {
                $articleFound = (new Articles($this->pdo))->find($ligne['CODE_ART']);
                if ($articleFound) {
                    $ligne['SSFAMILLE'] = $articleFound['SSFAM'];
                } else {
                    $ligne['SSFAMILLE'] = $sfamDefaut;
                }
            }

            $ctrLivraison = $entetePanier['LIV_CTR'];

            if ($ligne['TYPE_FG'] == 'G') {
                $ligne['CODE_FOU'] = $listeFrs[$ligne['TYPE_FG'].Constante::spliter.$ligne['CODE_FOU']]??'';
            }
            
            if (!in_array($ligne['CODE_FOU'], $listeFinal)) {
                continue;
            }

            $article = [
                'PROVENANCE'    => 'AO',
                'COD_ART'       => $ligne['CODE_ART'],
                'DES_ART'       => $ligne['DES_ART'],
                'DES_COMP'      => $ligne['DES_COMP'],
                'REF_FAB'       => $ligne['REF_FAB'],
                'REF_FOURN'     => $ligne['REF_FOUR'],
                'qte'           => $ligne['QTE_PROP'],
                
                'COD_GAM'       => $ligne['COD_GAM'],
                'COD_FAB'       => $ligne['COD_FAB'],
                
                'COD_SFAM'      => $ligne['SSFAMILLE'],
                
                'PX_ART'        => $ligne['PU'],
                'PX_ART_INIT'   => $ligne['PU'],
                'COD_FOURN'     => $ligne['CODE_FOU'],
                'ARTASSOCIE'    => false,
                'COEFCONV'      => 0,
                'ID_CAT'        => '',
                'CATPRLST'      => '',
                'COD_UNIT'      => $ligne['UNITE']??$codeUnit,
                
                'type_de_ligne' => 1,

                'COD_DEV'       => $ligne['DEVISE'],
                'DEVISE'        => $ligne['DEVISE'],

                'CTR_LIVR'      => $ctrLivraison,
                'MODE_TRS'      => $entetePanier['MOD_TRS'],

                'TAUX_TVA'      => $calculTauxTvaService->getTauxTva($ligne['CODE_ART'], $ligne['SSFAMILLE'], $ligne['CODE_FOU'], $ctrLivraison),
            ];

            if ($article['qte'] == '') {
                $article['qte'] = 1;
            }
            
            $listeNewLine[] = $panierLigneService->addPanier($article, $article['qte'], ['dteLivr' => $dteLivr], false, false, [], true);
        }
    }
}
