<?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 Entity\Model\OxaUsers;
use Helpers\CaracCompl\CaracCompl;
use Helpers\Outil\Sql;
use Modules\Panier\Repository\PanierLigne;

class TransferePanierService
{
    private \PDO $pdo;
    private string $idPanier;
    private string $idUser;
    private string $userDestination;

    public function __construct(\PDO $pdo, string $idPanier, string $idUser)
    {
        $this->pdo = $pdo;
        $this->idPanier = $idPanier;
        $this->idUser = $idUser;
        $this->userDestination = '';
    }
    public function getMaxIdPanier():int
    {
        $currentId = (new OxaUserPanier($this->pdo))->find(['id_user' => $this->userDestination], ['MAX(id_panier) maxId']);

        return (int)$currentId['maxId'] + 1;
    }

    public function getNewIdUser(?string $codeNewUser = null):string
    {
        $this->userDestination = $this->userDestination($codeNewUser);
        return $this->userDestination;
    }


    private function userDestination(?string $codeUser = null):string
    {
        $idUser = $this->idUser;
        if ($codeUser) {
            $findByCode = (new OxaUsers($this->pdo))->find(['login' => $codeUser], ['id_user']);
            if ($findByCode) {
                $idUser = $findByCode['id_user'];
            } else {
                (new OxaUsers($this->pdo))->insert([
                    'login'             => $codeUser,
                    'ExpirationMdP'     => 0,
                    'CodeCtrLivraison'  => '',
                    'NbLignePagination' => 0,
                    'AuthLigneManuelle' => 0,
                    'GestionMotdePasse' => 0,
                    'NomUser'           => '',
                ]);
                $idUserTmp = (string)Sql::getLastInsertId($this->pdo, 'oxa_users', 'id_user');
                if ($idUserTmp) {
                    $idUser = $idUserTmp;
                }
            }
        }

        $this->userDestination = $idUser;
        return $this->userDestination;
    }

    public function savePanierModele(\PDO $pdoOxaFT, string $libPanier, int $idPanierCible) :void
    {
        (new OxaUserPanier($this->pdo))->duplicate([
            'lib_panier'            => $libPanier,
            'flg_panier_modele'     => 1,
            'id_panier'             => $idPanierCible,
            'id_user'               => null,
            'NO_CDE'                => null,
            'CODE_FM'               => null,
            'COD_DEV'               => null,
            'mnt_budget'            => null,
            'IS_INITIALIZED'        => null,
            'CHPSPECCLT'            => null,
            'NO_DA'                 => null,
            'NO_DEM'                => null,
            'TOTAL_DA'              => null,
            'BUDGET_DA'             => null,
            'CODE_STE'              => null,
            'DEVISE'                => null,
            'SI_CODE'               => null,
            'CDC_CODE'              => null,
            'CTC_GSM'               => null,
            'ZONE_LIBRE'            => null,
            'ORIGINE'               => null,
            'SCA_CODE'              => null,
            'COMMENT_INT'           => null,
            'CG_CODE'               => null,
            'CHIF_EXEC'             => null,
            'TITRE_DA'              => null,
            'LIV_CTR'               => null,
            'CHIF_EXEC_LOCK'        => null,
            'MOD_TRS'               => null,
            'LIV_ADR'               => null,
            'LIV_PAYS'              => null,
            'LIV_CP'                => null,
            'LIV_VILLE'             => null,
            'CTC_TEL'               => null,
            'CTC_FCT'               => null,
            'CTC_NOM'               => null,
            'CTC_FAX'               => null,
            'CTC_MAIL'              => null,
            'OUPA_CENTRE_EMETTEUR'  => null,
            'CDE_COMPTOIR'          => null,
        ], [
            'id_user' => $this->idUser,
            'id_panier' => $this->idPanier,
        ]);

        $this->importPanierModele($pdoOxaFT, false, true, $idPanierCible);
    }
    
    public function importPanierModele(\PDO $pdoOxaFT, bool $initImputation, bool $societeIdentique, int $idPanierCible = 0):void
    {
        $listeArticle = (new OxaUserPanierLigne($this->pdo))->findAll([
            'id_panier'         => $this->idPanier,
            'id_user'           => $this->idUser
        ]);

        $panierLigneRepo = new PanierLigne($this->pdo);
        
        if ($initImputation == false && $societeIdentique) {
            foreach ($listeArticle as $article) {
                $arrayParm = [
                    'idUser'        => $this->idUser,
                    'idPanier'      => $this->idPanier,
                    'idLigne'       => $article['id_lig'],
    
                    'idUserCible'   => $_SESSION['id_user'],
                    'idPanierCible' => $idPanierCible,
                ];
    
                (new PanierLigneService($this->pdo, $pdoOxaFT, ''))->duplicateLigne($arrayParm);
            }

            (new OxaUserPanierImputation($this->pdo))->duplicate([
                'id_user'       => $_SESSION['id_user'],
                'id_panier'     => $idPanierCible,
                'id_imputation' => null,
                'SI_CODE'       => null,
                'CG_CODE'       => null,
                'CDC_CODE'      => null,
                'SCA_CODE'      => null,
                'REPARTITION'   => null
            ], [
                'id_user' => $this->idUser,
                'id_panier' => $this->idPanier,
            ]);
        } else {
            $panierLigneService = new PanierLigneService($this->pdo, $pdoOxaFT, 'panier');
            // on insert comme un nouvel article
            // on exclus les articles associers, on laisse addPanier les recalculer
            foreach ($listeArticle as $article) {
                $article['DEVISE'] = $article['COD_DEV'];
                $article['RECEP_AUTO'] = sql::boolSql($article['RECEP_AUTO']);
                $article['NONRECEPT'] = sql::boolSql($article['NONRECEPT']);
                $article['IDLIGNE'] = $article['IDLIGNECAT'];
                
                $idNewLigne = $panierLigneService->addPanier(
                    $article,
                    floatval($article['qte']),
                    ['initCC' => false],
                    true,
                    false,
                    [],
                    $initImputation,
                    '0',
                    $_SESSION['id_user']
                );

                $caracCompl = new CaracCompl($this->pdo);
                $caracCompl->duplicateCC(
                    'PAN',
                    $idPanierCible,
                    $idNewLigne,
                    $_SESSION['id_user'],
                    'PAN',
                    $this->idPanier,
                    $article['id_lig'],
                    $_SESSION['id_user']
                );
            }
        }

        // la v1 le faisait pas, mais en V2 on le fait
        // on recalcule les ID_LIGNE_ASSOC
        $listeArtAssoc = $panierLigneRepo->rqListArtAssocWithNewId($_SESSION['id_user'], $_SESSION['id_panier']);
        foreach ($listeArtAssoc as $assoc) {
            (new OxaUserPanierLigne($this->pdo))->update([
                'ID_LIGNE_ASSOC' => $assoc['NEW_ID_LIGNE_ASSOC']
            ], [
                'ID_LIGNE_ASSOC' => $assoc['ID_LIGNE_ASSOC']
            ]);
        }

        (new OxaUserPanierFour($this->pdo))->duplicate([
            'id_user'               => $_SESSION['id_user'],
            'id_panier'             => $idPanierCible,
            'COD_FOURN'             => null,
            'commentaire'           => null,
            'PX_ART'                => null,
            'Note'                  => null,
            'flg_add_pj'            => null,
            'flg_add_clause'        => null,
            'MDP'                   => null,
            'CDP'                   => null,
            'MDL'                   => null,
            'MSG_STD'               => null,
            'DOSSIER_ACHAT_COMP'    => null,
            'COMMENT_SUIVI_ACHAT'   => null,
            'CRITERE_REGROUP'       => null,
            'CODE_PAYS'             => null,
            'CPOSTAL'               => null,
            'VILLE1'                => null,
            'ADR'                   => null,
            'TYP_ACH'               => null,
        ], [
            'id_user' => $this->idUser,
            'id_panier' => $this->idPanier,
        ]);


        (new OxaUserPanierFourPj($this->pdo))->duplicate([
            'id_user'               => $_SESSION['id_user'],
            'id_panier'             => $idPanierCible,

            'COD_FOURN'             => null,
            'CRITERE_REGROUP'       => null,
            'PJ_TYPES'              => null,
            'TYP_ACH'               => null,
            'nom_piece_user'        => null,
            'nom_piece_sys'         => null,
            'PHYSIQUE'              => null,
            'OUVRABLE'              => null,
            'IMPRIMABL'             => null,
            'VERROU'                => null,
            'ISSU_DOCATT'           => null,
            'TABLE_DOCATT'          => null,
            'TITRE'                 => null
        ], [
            'id_user' => $this->idUser,
            'id_panier' => $this->idPanier,
        ]);

        (new OxaUserPanierFourClause($this->pdo))->duplicate([
            'id_user'               => $_SESSION['id_user'],
            'id_panier'             => $idPanierCible,

            'COD_FOURN'             => null,
            'CRITERE_REGROUP'       => null,
            'CONTENU'               => null,
            'TYP_ACH'               => null,
            'CLAU_FIX'              => null,
            'VERROU'                => null

        ], [
            'id_user' => $this->idUser,
            'id_panier' => $this->idPanier,
        ]);

        (new OxaUserPanierFourContact($this->pdo))->duplicate([
            'ID_USER'               => $_SESSION['id_user'],
            'ID_PANIER'             => $idPanierCible,
            
            'CTC_TYPE'              => null,
            'CODE_FOURN'            => null,
            'CRITERE_REGROUP'       => null,
            'CTC_IND'               => null,
            'CTC_NOM'               => null,
            'CTC_FCT'               => null,
            'CTC_TEL'               => null,
            'CTC_FAX'               => null,
            'CTC_MAIL'              => null,
            'CTC_GSM'               => null
        ], [
            'ID_USER' => $this->idUser,
            'ID_PANIER' => $this->idPanier,
            'CTC_TYPE' => 'fournisseur'
        ]);

        (new OxaUserPanierFourDoc($this->pdo))->duplicate([
            'ID_USER'               => $_SESSION['id_user'],
            'ID_PANIER'             => $idPanierCible,

            'COD_FOURN'             => null,
            'NUM_DOC'               => null,
            'TITRE'                 => null,
            'TYPE_DOC'              => null,
            'NOM_FIC_ORI'           => null ,
            'NOM_FIC_FINAL'         => null,
            'DATE_PARUTION'         => null,
            'DATE_VALIDITE'         => null,
            'AUTEUR'                => null,
            'CENTRE'                => null,
            'COMMENTAIRE'           => null ,
            'CRITERE_REGROUP'       => null

        ], [
            'ID_USER' => $this->idUser,
            'ID_PANIER' => $this->idPanier,
        ]);

        if ($societeIdentique) {
            (new OxaUserPanierFourContact($this->pdo))->duplicate([
                'ID_USER'               => $_SESSION['id_user'],
                'ID_PANIER'             => $idPanierCible,
                
                'CTC_TYPE'              => null,
                'CODE_FOURN'            => null,
                'CRITERE_REGROUP'       => null,
                'CTC_IND'               => null,
                'CTC_NOM'               => null,
                'CTC_FCT'               => null,
                'CTC_TEL'               => null,
                'CTC_FAX'               => null,
                'CTC_MAIL'              => null,
                'CTC_GSM'               => null
            ], [
                'ID_USER' => $this->idUser,
                'ID_PANIER' => $this->idPanier,
                'CTC_TYPE' => 'livraison'
            ]);
        }
    }

    /**
     * @param int $idPanierDestination
     * @param string $libPanier
     * @param bool $panierModele
     * @return int|bool
     */
    public function movePanier(int $idPanierDestination, string $libPanier, bool $panierModele)
    {
        if (!$this->userDestination) {
            $this->userDestination = $this->idUser;
        }
        
        $idOrigin = [
            'id_panier'         => $this->idPanier,
            'id_user'           => $this->idUser
        ];

        $idOriginUpper = [
            'ID_PANIER'         => $this->idPanier,
            'ID_USER'           => $this->idUser
        ];

        $idNewPanier = [
            'id_panier'         => $idPanierDestination,
            'id_user'           => $this->userDestination
        ];

        $idNewPanierUpper = [
            'ID_PANIER'         => $idPanierDestination,
            'ID_USER'           => $this->userDestination
        ];

        (new OxaUserPanier($this->pdo))->update($idNewPanier+[
            'lib_panier'        => $libPanier,
            'flg_panier_modele' => $panierModele? 1:0,
        ], $idOrigin);

        (new OxaUserPanierCsDon($this->pdo))->update($idNewPanier, $idOrigin);
        (new OxaUserPanierImputation($this->pdo))->update($idNewPanier, $idOrigin);

        (new OxaUserPanierFour($this->pdo))->update($idNewPanier, $idOrigin);
        (new OxaUserPanierFourClause($this->pdo))->update($idNewPanier, $idOrigin);
        (new OxaUserPanierFourPj($this->pdo))->update($idNewPanier, $idOrigin);
        
        (new OxaUserPanierLigne($this->pdo))->update($idNewPanier, $idOrigin);
        //select * from oxa_users_panier_ligne where id_user = '113' and id_panier = '0' and (type_de_ligne = '3' or ID_LIGNE_ASSOC != 0)
        
        (new CCLDoc($this->pdo))->update([
            'ID_USER_BASKET'    => $this->userDestination,
            'DOC_NUM'           => $idPanierDestination,
        ], [
            'ID_USER_BASKET'    => $this->idUser,
            'DOC_NUM'           => $this->idPanier,
        ]);

        //les colonnes sont en UPPERCASE ici
        (new OxaUserPanierFourDoc($this->pdo))->update($idNewPanierUpper, $idOriginUpper);
        (new OxaUserPanierFourContact($this->pdo))->update($idNewPanierUpper, $idOriginUpper);

        (new PanierEnteteService($this->pdo))->resetControlePanier((string)$idPanierDestination);

        return $idPanierDestination;
    }
}
