<?php

namespace Modules\Suivi\Service;

use Entity\Model\CaEntet;
use Entity\Model\CaLigne;
use Entity\Model\OxaUserPanierCsDon;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Date;
use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Modules\Panier\Service\PanierEnteteService;
use Modules\Suivi\Repository\DuplicateRepo;
use Modules\Suivi\Repository\SuiviCdeRepo;

class DuplicateCdeService extends DuplicateAbs
{
    protected function initItem():void
    {
        $this->entete  = (new CaEntet($this->pdo))->find($this->idDocument);
        $this->lignes = (new DuplicateRepo($this->pdo))->getListeLigneCdeForDuplicate($this->idDocument);
        $this->codeFou = $this->entete['CODE_FOU'];
    }

    protected function getTypeItem():string
    {
        return 'CDE';
    }

    protected function getFieldLigneCtrLivraison():string
    {
        return 'CTR_LIV';
    }


    protected function getFieldLignQte():string
    {
        return 'QTE_COMM';
    }

    /**
     * @return array<mixed>
     */
    protected function getListeFrs()
    {
        return (new DuplicateRepo($this->pdo))->getInfoFrsCde($this->idDocument);
    }

    /**
     * @return array<mixed>
     */
    protected function getContactFournisseur()
    {
        return [
            'CTC_NOM'   => $this->entete['CTCT_FOU'],
            'CTC_FCT'   => '',
            'CTC_TEL'   => $this->entete['TEL_CTCT'],
            'CTC_FAX'   => $this->entete['FAX_CTCT'],
            'CTC_MAIL'  => $this->entete['EMA_CTCT'],
            'CTC_GSM'   => $this->entete['PORTCFOU'],
        ];
    }

    /**
     * @return array<mixed>
     */
    protected function getEnteteDocument()
    {
        //si société différente de la société du document, alors on reprend un certain nombre d'élément de la session
        if ($this->entete['CODE_STE'] != $_SESSION['Session_SocUsr']) {
            $arraySession = (new PanierEnteteService($this->pdo))->getArrayInitSession($this->trad);
        } else {
            $arraySession = [];
        }

        if ($this->mode == DuplicateAbs::AVENANT) {
            $libPanier = $this->trad->t('Avenant sur commande N°').' '.$this->entete['NO_CDE'];
            $CHIF_EXEC_LOCK = '1';
            $origin = $this->mode . "|*|" . $this->entete['NO_CDE'] . '|';
        } else {
            $libPanier = $this->trad->t('En cours');
            $CHIF_EXEC_LOCK = '0';
            $origin = $this->mode;
        }

        return [
            'id_user'           => $_SESSION['id_user'],
            'id_panier'         => '0',
            
            //general panier
            'IS_INITIALIZED'    => '1',
            'COD_DEV'           => $this->entete['DEVISE'],
            'mnt_budget'        => 0,
            'ORIGINE'           => $origin, //CreationAvenant // duplication // modificationChifExe // CreationAvenant //modification
            'CHIF_EXEC'         => 'E',
            'CHIF_EXEC_LOCK'    => $CHIF_EXEC_LOCK,
            'lib_panier'        => $libPanier,

            //imputation
            'CODE_STE'          => $_SESSION['Session_SocUsr'],
            'SI_CODE'           => $arraySession? $arraySession['SI_CODE']:$this->entete['SECTIMP'],
            'CDC_CODE'          => $arraySession? $arraySession['CDC_CODE']:$this->entete['CODECOMP'],
            'SCA_CODE'          => $arraySession? $arraySession['SCA_CODE']:$this->entete['SSCPTEANA'],
            'CG_CODE'           => $arraySession? $arraySession['CG_CODE']:$this->entete['CODGES'],
            
            
            //centre emetteur
            'OUPA_CENTRE_EMETTEUR' => $arraySession?
                $arraySession['OUPA_CENTRE_EMETTEUR']:($this->entete['CTR_EMETT']??$_SESSION['Session_CodeCtrEmetteur']),

            //DA
            'TOTAL_DA'          => 0,
            'BUDGET_DA'         => $this->entete['TOT_CDEHT'],
            'NO_DA'             => '0',
            'TITRE_DA'          => '',
            'NO_DEM'            => $_SESSION['Session_Login'],

            //CDE
            'NO_CDE'            => '',

            //Centre
            'MOD_TRS'           => $arraySession? $arraySession['MOD_TRS']:$this->entete['MOD_TRS'],
            'LIV_ADR'           => $arraySession? $arraySession['LIV_ADR']:$this->entete['ADR_LIV'],
            'LIV_CTR'           => $arraySession? $arraySession['LIV_CTR']:$this->entete['CTR_LIV'],
            'LIV_PAYS'          => $arraySession? $arraySession['LIV_PAYS']:$this->entete['PAY_LIV'],
            'LIV_CP'            => $arraySession? $arraySession['LIV_CP']:$this->entete['CPLIV'],
            'LIV_VILLE'         => $arraySession? $arraySession['LIV_VILLE']:$this->entete['VILLELIV'],
            
            'CTC_TEL'           => $arraySession? $arraySession['CTC_TEL']:$this->entete['TLCTC1L'],
            'CTC_FCT'           => $arraySession? $arraySession['CTC_FCT']:$this->entete['FTCTC1L'],
            'CTC_NOM'           => $arraySession? $arraySession['CTC_NOM']:$this->entete['NMCTC1L'],
            'CTC_FAX'           => $arraySession? $arraySession['CTC_FAX']:$this->entete['FXCTC1L'],
            'CTC_MAIL'          => $arraySession? $arraySession['CTC_MAIL']:$this->entete['MLCTC1L'],
            'CTC_GSM'           => $arraySession? $arraySession['CTC_GSM']:$this->entete['PRCTC1L'],

            // ??
            'CHPSPECCLT'        => '',
            'ZONE_LIBRE'        => '',
            'COMMENT_INT'       => '',

            'CDE_COMPTOIR'      => Sql::FALSE
        ];
    }

    protected function updateCS(?string $idLigne = null, ?string $noPoDoc = null):void
    {
        $codTab = $idLigne? 'CA_LIGNE':'CA_ENTET';
        $listeCs = (new ChampSupp($this->pdo))->generateChampSupp(
            $codTab,
            ChampSupp::autoCompletCodeEnr($this->idDocument, $noPoDoc, $codTab),
        );
        
        foreach ($listeCs as $cs) {
            if ($cs['TAB_SOUR'] == ($idLigne? 'DA_LIGNE':'DA_ENTET')) {
                if (sql::boolSql($cs['NONDUPLI']) && $this->mode == DuplicateAbs::DUPLI) {
                    if ($cs['FORMAT'] == 'D') {
                        $value = Date::dateConverte('00000000');
                    } elseif ($cs['FORMAT'] == 'H') {
                        $value = '00:00:00';
                    } else {
                        $value = '';
                    }
                } else {
                    if ($cs['FORMAT'] == 'L') {
                        $value = $cs['VALUECHAMPSUPP'] == 'O'? '1':'0';
                    /*} elseif ($cs['FORMAT'] == 'D') {
                        $value = Date::dateConverte($cs['VALUECHAMPSUPP']);
                    */
                    } else {
                        $value = $cs['VALUECHAMPSUPP'];
                    }
                }

                (new OxaUserPanierCsDon($this->pdo))->update([
                    'VALEUR'        => $value,
                ], [
                    'id_user'       => $_SESSION['id_user'],
                    'id_panier'     => '0',
                    'NUM_FIX'       => $cs['CHP_SOUR'],
                    'ID_LIGNE'      => $idLigne??'0',
                    'COD_TAB'       => $idLigne? 'DA_LIGNE':'DA_ENTET'
                ]);
            }
        }
    }
}
