<?php

namespace Modules\Additional\Specifique\Client155\Modules\Declaratif\Outil;

use Entity\Model\Centre;
use Entity\Model\Contfour;
use Entity\Model\CsChps;
use Entity\Model\CtcCtr;
use Entity\Model\Fourniss;
use Entity\Model\Hastutil;
use Entity\Model\ParamDico;
use Entity\Model\Societe;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Date;
use Helpers\Outil\Sql;
use Helpers\Session\ParseBase1;
use Modules\Additional\Specifique\Client155\Modules\Declaratif\Repository\Commande;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Declaratif
{
    /** @var \PDO $pdo */
    private \PDO $pdo;

    /** @var string $file */
    private string $file;

    /** @var array<string>  */
    protected array $dateColumn = [
        'Date du chiffre d\'affaires',
        'Date de période de la cde'
    ];

    /** @var array<string> $content */
    private array $content;

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

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

    /** @var array<mixed> $societe */
    private array $societe = [];

    /** @var array<mixed> $centre */
    private array $centre = [];

    /** @var array<mixed> $paravrac */
    private array $paravrac = [];

    /** @var array<mixed> $contactFou */
    private array $contactFou = [];

    /** @var array<mixed> $fourniss */
    private array $fourniss = [];

    /** @var array<mixed> $ctcCtr */
    private array $ctcCtr = [];

    /** @var int $nbTotalLine */
    private int $nbTotalLine = 0;

    /** @var int $nbLineTreated */
    private int $nbLineTreated = 0;

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

    /** @var array<mixed> $cde */
    private array $cde = [];

    /** @var array<mixed> $cdeFail */
    private array $cdeFail = [];

    /** @var array<mixed> $failInsert */
    private array $failInsert = [];

    /** @var array<mixed> $toTreat */
    private array $toTreat = [];

    /** @var array<mixed> $duplicatParamDico */
    private array $duplicatParamDico = [];

    /**  ParamDico $paramDico */
    private ParamDico $paramDico;

    /** @var string $typeDicoKey */
    private string $typeDicoKey;


    /**
     * @param \PDO $pdo
     * @param string $file
     */
    public function __construct(\PDO $pdo, string $file)
    {
        $this->pdo = $pdo;
        $this->file = $file;
        $this->paramDico = new ParamDico($this->pdo);
        $this->typeDicoKey = 'SYSU_IMPORT_CDE';
    }

    /**
     * @param string $file
     * @return void
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    private function extract(string $file): void
    {
        $ext = pathinfo($this->file, PATHINFO_EXTENSION);

        $this->content = ($ext === 'csv') ? $this->extractFromCsv() : $this->extractFromExcel();
    }

    /**
     * @return array<mixed>
     */
    private function extractFromCsv(): array
    {
        $contents = [];

        $headerInFile = [];
        $fp = fopen($this->file, 'r');
        if ($fp) {
            while (($data = fgetcsv($fp, 0, ',')) !== false) {
                if (!($headerInFile)) {
                    $headerInFile = $data;
                } else {
                    $row = explode(';', $data[0]);
                    $contents[] = $row;
                }
            }
        }
        
        return $contents;
    }

    /**
     * @return array<mixed>
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    private function extractFromExcel(): array
    {
        $input = IOFactory::identify($this->file);
        $objReader = IOFactory::createReader($input);
        $objReader->setReadDataOnly(true);

        $excel = $objReader->load($this->file);

        $sheet = $excel->getSheet(0);
        $nbRow = $sheet->getHighestRow();

        $data = [];

        $positionColumnDate = '';

        $rowCount = 0;
        $maxColumn = 0;
        foreach ($sheet->getRowIterator(1, $nbRow) as $row) {
            $rowContent = [];
            $iC = 0;
            foreach ($row->getCellIterator() as $column) {
                // Première ligne = en tête
                $value = $column->getCalculatedValue();

                if ($rowCount === 0) {
                    if ($value == 'NULL') {
                        if ($maxColumn === 0) {
                            $maxColumn = $iC;
                        }
                        continue;
                    }
                    if (strpos($value, 't| ') !== false) {
                        $value = str_replace('t| ', '', $value);
                    }

                    if ($column->getColumn() === 'E') {
                        $positionColumnDate = $iC;
                    }
                }

                if ($rowCount > 0) {
                    if ($maxColumn !== 0 && $iC >= $maxColumn) {
                        continue;
                    }

                    if ($iC === $positionColumnDate && ($value != '' && $value != '0')) {
                        $value = Date::transformExcelDateToPHP($value);
                    }
                }

                $rowContent[] = $value;
                $iC++;
            }

            if ($rowCount !== 0) {
                $dataLine = $rowContent;
                $data[] = $dataLine;
            }
            $rowCount++;
        }

        return $data;
    }

    /**
     * @return array<mixed>
     * @throws \DOMException
     */
    private function buildXML(): array
    {
        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $commandesNoeud = $dom->createElement('Commandes');
        $i = 0;
        
        foreach ($this->content as $index => $line) {
            $this->nbTotalLine++;
            $this->buildNode((array)$line, $dom, $commandesNoeud, $index);
            $i++;
        }
        $dom->appendChild($commandesNoeud);
        
        $xml = $dom->saveXML();
        
        
        $nomFichier = "CA_{$_SESSION['Session_Login']}_".date('Ymd')."_".date('His').'.xml';
        
        // Si aucune commande à créé parmis les lignes traitées -> pas de fichier XML ?
        if ($this->nbLineTreated) {
            $tmp = fopen((new ParseBase1())->getRep()->oxadata.'interfaces\\imports\\'.$nomFichier, 'w');
            if ($tmp) {
                fputs($tmp, $xml);
                fclose($tmp);
            }
        }

        return [
            'file' => Fichier::URLDownload($nomFichier),
            'nbLine' => $this->nbTotalLine,
            'nbTreated' => $this->nbLineTreated,
        ];
    }

    /**
     * @param array<mixed> $line
     * @param \DOMDocument $xml
     * @param \DOMElement $node
     * @param int $index
     * @return void
     * @throws \DOMException
     */
    private function buildNode(array $line, \DOMDocument &$xml, \DOMElement $node, int $index): void
    {
        $paravrac = new \Entity\Model\Paravrac($this->pdo);
        $codeFOU = $line[0];

        if (!in_array($index, $this->toTreat)) {
            return;
        }

        $this->nbLineTreated++;

        $recordNode = $xml->createElement('Record');

        if (isset($this->cde[$index])) {
            $arrayToXml = [
                'NO_CDE' => 'NO_CDE',
                'AVENANT' => 'AVENANT',
            ];

            foreach ($arrayToXml as $key => $ref) {
                $element = $xml->createElement($key, $this->cde[$index]['cde'][$ref]);
                if ($this->cde[$index]['cde']['DTE_VALID'] !== '00000000') {
                    $recordNode->appendChild($element);
                }
            }

            if ($this->cde[$index]['cde']['DTE_VALID'] !== '00000000') {
                $motAvenant = $xml->createElement('MOT_AVNT', "Complément de chiffre d'affaire");
                $recordNode->appendChild($motAvenant);
            }
        }

        $valuePeriode = ($this->isNotEmpty($line[4])) ? $line[4] : (new \DateTime('now'))->format('d/m/Y');

        $dtePerio = $xml->createElement("DTE_PERIO", $valuePeriode);
        $recordNode->appendChild($dtePerio);

        $this->buildContactFouLine($line, $xml, $recordNode);

        $dteCreat = $xml->createElement("DTE_CREAT", $valuePeriode);
        $recordNode->appendChild($dteCreat);

        // CS N°1 "Chef de produit" fiche fournisseur cde
        if (isset($this->cs[$codeFOU])) {
            $acheteur = $this->cs[$codeFOU];
        } else {
            $csChamps = new CsChps($this->pdo);
            $test = $csChamps->find([
                'COD_TAB' => 'FOURNISS',
                'NOM' => 'Chef de produit'
            ]);
            $acheteur = ChampSupp::getValueCS('FOURNISS', $codeFOU, $test['NUM_FIX'], $this->pdo);

            if ($acheteur == '') {
                if (isset($this->paravrac['ACHCDEDIR'])) {
                    $defaultAcheteur = $this->paravrac['ACHCDEDIR'];
                } else {
                    $defaultAcheteur = $paravrac->find(['TYPEPARV' => 'PARAMGEN', 'CODEPARV' => 'ACHCDEDIR'])['LIB01PARV'] ?? null;
                    $this->paravrac['ACHCDEDIR'] = $defaultAcheteur;
                }
                $acheteur = $defaultAcheteur;
            }

            $this->cs[$codeFOU] = $acheteur;
        }

        $ach = $xml->createElement('ACH', $acheteur);
        $recordNode->appendChild($ach);

        $this->buildBuyerLine($line, $xml, $recordNode);


        if (count($this->societe) == 0) {
            $societe = new Societe($this->pdo);
            $societe = $societe->fetchAll(['TOP 1 CODE_STE'], [], $this->pdo::FETCH_ASSOC);

            if (count($societe) > 0) {
                $this->societe = $societe[0];
            }
        }

        $arrayToXml = [];

        if (count($this->centre) === 0) {
            $centreRepo = new Centre($this->pdo);
            $centres = $centreRepo->find([
                'CODE_STE' => $this->societe['CODE_STE']
            ], [
                'EMISSION', 'LIVRAISON', 'FACTURAT', 'CODE_CTR', 'RAIS_SOC', 'ADRESSE', 'VILLE', 'PAYS'
            ], [], $this->pdo::FETCH_ASSOC);

            $this->centre = [
                'EMISSION' => Sql::toBool($centres['EMISSION']) ? $centres : [],
                'LIVRAISON' => Sql::toBool($centres['LIVRAISON']) ? $centres : [],
                'FACTURAT' => Sql::toBool($centres['FACTURAT']) ? $centres : [],
            ];
        }


        $arrayToXml['CTR_EMETT'] = $this->centre['EMISSION']['CODE_CTR'];
        $arrayToXml['CTR_LIV'] = $this->centre['LIVRAISON']['CODE_CTR'];
        $arrayToXml['CTR_FACTU'] = $this->centre['FACTURAT']['CODE_CTR'];
        $arrayToXml['NOM_LIV'] = $this->centre['LIVRAISON']['RAIS_SOC'];
        $arrayToXml['ADR_LIV'] = $this->centre['LIVRAISON']['ADRESSE'];
        $arrayToXml['VIL_LIV'] = $this->centre['LIVRAISON']['VILLE'];
        $arrayToXml['PAY_LIV'] = $this->centre['LIVRAISON']['PAYS'];

        foreach ($arrayToXml as $key => $value) {
            $element = $xml->createElement($key, $value);
            $recordNode->appendChild($element);
        }

        $devise = $xml->createElement('DEVISE', $_SESSION['parametrage']['DEVISE_BASE']);
        $recordNode->appendChild($devise);

        $objetCa = $xml->createElement('OBJET_CA', "Chiffre d'affaires, période {$line[4]}");
        $recordNode->appendChild($objetCa);


        if (isset($this->paravrac['TYP_DOC_DEF'])) {
            $cdeStandard = $this->paravrac['TYP_DOC_DEF'];
        } else {
            $cdeStandard = $paravrac->find(['TYPEPARV' => 'PARAMGEN', 'CODEPARV' => 'TYP_DOC_DEF'])['LIB01PARV'] ?? null;
            $this->paravrac['TYP_DOC_DEF'] = $cdeStandard;
        }

        $typDoc = $xml->createElement('TYP_DOC', $cdeStandard);
        $recordNode->appendChild($typDoc);

        $codeSte = $xml->createElement('CODE_STE', $this->societe['CODE_STE']);
        $recordNode->appendChild($codeSte);

        $this->buildAddressLine($line, $xml, $recordNode);

        $typDate = $xml->createElement('TYPDATE', 'D');
        $recordNode->appendChild($typDate);

        $validation = $xml->createElement('Validation', 'true');
        $recordNode->appendChild($validation);

        $impressionFictive = $xml->createElement('ImpressionFictive', 'true');
        $recordNode->appendChild($impressionFictive);

        $this->buildContactCentreLiv($line, $xml, $recordNode);


        $this->buildNodeCdeLine($line, $xml, $recordNode);

        $node->appendChild($recordNode);
    }


    /**
     * @param array<mixed> $line
     * @param \DOMDocument $xml
     * @param \DOMElement $child
     * @return void
     * @throws \DOMException
     */
    private function buildContactFouLine(array $line, \DOMDocument $xml, \DOMElement &$child): void
    {
        $codeFou = $line[0];

        if (isset($this->contactFou[$codeFou])) {
            $contact = $this->contactFou[$codeFou];
        } else {
            $contactFour = new Contfour($this->pdo);
            $contact = $contactFour->find([
                'CODE_FOU' => $codeFou,
                'IND_FOU' => 0
            ], [], [], $this->pdo::FETCH_ASSOC);

            $this->contactFou[$codeFou] = $contact;
        }
        
        if (!isset($contact['CODE_FOU'])) {
            $contact['CODE_FOU']=$codeFou;
        }
        
        $toXml = [
            'CODE_FOU' => 'CODE_FOU',
            'CTCT_FOU' => 'NOM',
            'TEL_CTCT' => 'TEL',
            'FAX_CTCT' => 'FAX',
            'EMA_CTCT' => 'EMAIL',
            'PORTCFOU' => 'TELPORT',
        ];

        foreach ($toXml as $ref => $sql) {
            $element = $xml->createElement($ref, $contact[$sql]);
            $child->appendChild($element);
        }
    }

    /**
     * @param array<mixed> $line
     * @param \DOMDocument $xml
     * @param \DOMElement $recordNode
     * @return void
     */
    private function buildNodeCdeLine(array $line, \DOMDocument $xml, \DOMElement &$recordNode): void
    {
        $lignesCommandes = $xml->createElement('Lignes_commande');

        $lignes = $xml->createElement('Ligne');

        $noPo = $xml->createElement('NO_PO', '1');
        $lignes->appendChild($noPo);

        $libelleSSF = $xml->createElement('DES_SOMM', $line[3] ?? '');
        $lignes->appendChild($libelleSSF);

        $codeSSF = $xml->createElement('SSFAM', $line[2] ?? '');
        $lignes->appendChild($codeSSF);

        $pu = $xml->createElement('PU', $line[5] ?? '');
        $lignes->appendChild($pu);

        $qteComm = $xml->createElement('QTE_COMM', '1');
        $lignes->appendChild($qteComm);

        $unite = $xml->createElement('UNITE', 'U');
        $lignes->appendChild($unite);

        $dteLivCon = $xml->createElement('DTELIVCON', (
        $this->isNotEmpty($line[4])
        )   ? $line[4]
            : (new \DateTime('now'))->format('d/m/Y'));
        $lignes->appendChild($dteLivCon);

        $saisieRec = $xml->createElement('SAISIEREC', 'false');
        $lignes->appendChild($saisieRec);

        $codeSte = $xml->createElement('CODE_STE', $this->societe['CODE_STE']);
        $lignes->appendChild($codeSte);

        $lignesPlanning = $xml->createElement('Lignes_planning');
        $datePlanning = $xml->createElement('Date_planning');
        $dteLiv = $xml->createElement('DTE_LIV', (
            $this->isNotEmpty($line[4])
            )   ? $line[4]
                : (new \DateTime('now'))->format('d/m/Y'));


        $datePlanning->appendChild($dteLiv);
        $datePlanning->appendChild(clone($qteComm));
        $datePlanning->appendChild($codeSte);
        $lignesPlanning->appendChild($datePlanning);
        $lignes->appendChild($lignesPlanning);

        $lignesCommandes->appendChild($lignes);

        $recordNode->appendChild($lignesCommandes);
    }

    /**
     * @param array<mixed> $line
     * @param \DOMDocument $xml
     * @param \DOMElement $child
     * @return void
     */
    private function buildAddressLine(array $line, \DOMDocument $xml, \DOMElement &$child): void
    {
        $codeFou = $line[0];

        $fourniss = new Fourniss($this->pdo);

        $toXml = [
            'ADCDEFOU'  => 'ADR',
            'VILCDEFO'  => 'VILLE',
            'PAYCDEFO'  => 'CODE_PAYS',
            'CODE_LNG'  => 'COD_LNG',
            'CPCDEFO'   => 'CPOSTAL',
            'VILLEFOU'  => 'VILLE1',
            'RS'        => 'RS',
            'SIRET'     => 'NO_SIRET',
            'TAXE2'     => 'TAXE2',
            'TAXE3'     => 'TAXE3',
            'TAXE4'     => 'TAXE4',
            'MODE_PAIE' => 'MODE_PAIE'
        ];

        if (isset($this->fourniss[$codeFou])) {
            $f = $this->fourniss[$codeFou];
        } else {
            $f = $fourniss->find($line[0], array_values($toXml), [], $this->pdo::FETCH_ASSOC);
            $this->fourniss[$codeFou] = $f;
        }

        foreach ($toXml as $ref => $sql) {
            $element = $xml->createElement($ref, $f[$sql]);
            $child->appendChild($element);
        }
    }

    /**
     * @param array<mixed> $line
     * @param \DOMDocument $xml
     * @param \DOMElement $child
     * @return void
     * @throws \DOMException
     */
    private function buildBuyerLine(array $line, \DOMDocument $xml, \DOMElement &$child): void
    {
        $toXml = [
            'NOM_ACH'   => 'NOM',
            'TEL_ACH'   => 'TEL',
            'FAX_ACH'   => 'FAX',
            'PORT_ACH'  => 'GSM',
            'MAIL_ACH'  => 'EMAIL'
        ];

        $codeFou = $line[0];
        if (isset($this->buyer[$codeFou])) {
            $data = $this->buyer[$codeFou];
        } else {
            $hastUtil = new Hastutil($this->pdo);
            $data = $hastUtil->find($this->cs[$codeFou], array_values($toXml), [], $this->pdo::FETCH_ASSOC);
            $this->buyer[$codeFou] = $data;
        }

        foreach ($toXml as $ref => $sql) {
            $element = $xml->createElement($ref, $data[$sql]);
            $child->appendChild($element);
        }
    }

    /**
     * @param array<mixed> $line
     * @param \DOMDocument $xml
     * @param \DOMElement $child
     * @return void
     * @throws \DOMException
     */
    private function buildContactCentreLiv(array $line, \DOMDocument $xml, \DOMElement &$child): void
    {
        $arrayToXml = [
            1 => [
                'NMCTC1L' => 'CTC_NOM',
                'FTCTC1L' => 'CTC_FCT',
                'TLCTC1L' => 'CTC_TEL',
                'FXCTC1L' => 'CTC_FAX',
                'PRCTC1L' => 'CTC_GSM',
                'MLCTC1L' => 'CTC_MAIL',
            ],
            2 => [
                'NMCTC2L' => 'CTC_NOM',
                'FTCTC2L' => 'CTC_FCT',
                'TLCTC2L' => 'CTC_TEL',
                'FXCTC2L' => 'CTC_FAX',
                'PRCTC2L' => 'CTC_GSM',
                'MLCTC2L' => 'CTC_MAIL',
            ],
        ];

        $ctcCentreRepo = new CtcCtr($this->pdo);

        foreach ($arrayToXml as $index => $value) {
            if (isset($this->ctcCtr[$index])) {
                $data = $this->ctcCtr[$index];
            } else {
                $data = $ctcCentreRepo->find([
                    'COD_CTR' => $this->centre['LIVRAISON']['CODE_CTR'],
                    'CTC_IND' => $index
                ], array_values($value));

                $this->ctcCtr[$index] = $data;
            }


            foreach ($value as $ref => $sql) {
                $element = $xml->createElement($ref, $data[$sql]);
                $child->appendChild($element);
            }
        }
    }

    /**
     * @param mixed $data
     * @return bool
     */
    private function isNotEmpty($data): bool
    {
        if ($data !== 'NULL' && !is_null($data) && $data != '0' && $data != '') {
            return true;
        }

        return false;
    }

    /**
     * @param array<mixed> $line
     * @return void
     */
    private function checkCde(array $line, int $index): void
    {
        $codeFou = $line[0];
        $ssf     = $line[2];
        if (trim($codeFou) != "") {
            $periode = $periodeSql = $line[4];
            $montant = $line[5];
            
            Date::dateToSql($periodeSql);
    
            $checkCdeRepo = new Commande($this->pdo);

            $cde = $checkCdeRepo->findExistingCde($codeFou, $periodeSql, $ssf);
            
            $cdeParmadico = $this->paramDico->find([
                'TYPEDICO' => $this->typeDicoKey,
                'ID1' => $codeFou,
                'ID2' => $ssf,
                'ID3' => (string)((float)$montant),
                'ID4' => $periodeSql,
            ]);

            if ($cde) {
                if (((float) $cde['PU'] !== (float) $montant)) {
                    $this->toTreat[] = $index;
                    $this->cde[$index] = [
                        'cde' => $cde,
                        'newPu' => $montant,
                    ];
                } else {
                    $this->cdeFail[$index] = [
                        'cde' => $cde,
                        'newPu' => $montant,
                    ];

                    $this->failInsert[(implode('_', ([
                        'TYPEDICO' => $this->typeDicoKey,
                        'ID1' => $codeFou,
                        'ID2' => $ssf,
                        'ID3' => (string)((float)$montant),
                        'ID4' => $periodeSql,
                    ])))] = 1;
                }
            } elseif (!$cdeParmadico) {
                $this->toTreat[] = $index;
            } else {
                $this->cdeFail[$index] = [
                    'cde' => $cde,
                    'newPu' => $montant,
                ];

                $this->failInsert[(implode('_', ([
                    'TYPEDICO' => $this->typeDicoKey,
                    'ID1' => $codeFou,
                    'ID2' => $ssf,
                    'ID3' => (string)((float)$montant),
                    'ID4' => $periodeSql,
                ])))] = 1;
            }

            //if (($cde || $cdeParmadico) /*&& $this->verify*/) {
              /*  if (((float) $cde['PU'] !== (float) $montant) && !$cdeParmadico) {
                    $this->toTreat[] = $index;
                    $this->cde[$index] = [
                        'cde' => $cde,
                        'newPu' => $montant,
                    ];
                } else {
                    $this->cdeFail[$index] = [
                        'cde' => $cde,
                        'newPu' => $montant,
                    ];

                    $this->failInsert[(implode('_', ([
                        'TYPEDICO' => $this->typeDicoKey,
                        'ID1' => $codeFou,
                        'ID2' => $ssf,
                        'ID3' => (string)((float)$montant),
                        'ID4' => $periodeSql,
                    ])))] = 1;
                }
            } else {
                $this->toTreat[] = $index;
            }*/
    
            if (isset($this->treated[$codeFou][$ssf][$periode])) {
                if ($this->treated[$codeFou][$ssf][$periode] != $montant) {
                    $this->treated[$codeFou][$ssf][$periode] = $montant;
                }
            } else {
                $this->treated[$codeFou][$ssf][$periode] = $montant;
            }
        }
    }

    /**
     * @return void
     */
    private function verifyEntries()
    {
        foreach ($this->content as $index => $line) {
            $this->checkCde((array) $line, $index);
        }
    }


    private function insertParamDicoForExist() : void
    {
        foreach ($this->content as $value) {
            if (trim($value[0]) != '') {
                Date::dateToSql($value[4]);
                $arrayJob = [
                    'TYPEDICO' => (string)$this->typeDicoKey,
                    'ID1' => (string)$value[0],
                    'ID2' => (string)$value[2],
                    'ID3' => (string)((float)$value[5]),
                    'ID4' => $value[4],
                ];
                
                if (!key_exists(
                    implode('_', $arrayJob),
                    $this->failInsert
                ) && !key_exists(
                    implode('_', $arrayJob),
                    $this->duplicatParamDico
                )) {
                    $this->paramDico->merge($arrayJob);
                    $this->duplicatParamDico[implode('_', $arrayJob)] = 1;
                }
            }
        }
    }
    /**
     * @param bool $verify
     * @return array<mixed>
     * @throws \DOMException
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public function transformCsvToXml($verify = true)
    {
        $this->extract($this->file);
        $this->verifyEntries();
        
        if ($verify == true && count($this->cdeFail) > 0) {
           /* if (count($this->cde) > 0) {
                return [
                    'cdeFail' => $this->cde
                ];
            } else */
            return [
                'cdeFail' => $this->cdeFail
            ];
        }

        $this->insertParamDicoForExist();

        return $this->buildXML();
    }
}
