<?php

namespace Modules\DemandeAchat\Repository;

use Entity\Model\CaClaus;
use Entity\Model\CaEntet;
use Entity\Model\CaEvent;
use Entity\Model\CaLigne;
use Entity\Model\CaPijo;
use Entity\Model\CsDon;
use Entity\Model\DocCde;
use Entity\Model\Paravrac;
use Entity\Model\TacPijo;
use Entity\Model\Docatt;
use Entity\Model\TermPaie;
use Helpers\CaracCompl\CaracCompl;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Date;
use Helpers\Outil\Sql;
use \Entity\Model\Memos;
use Helpers\Outil\ArrayHelper;
use Helpers\QueryBuilder\AbsRepository;
use Modules\Commande\Service\CreationCommandeService;
use Modules\GlobalApplication\Outil\InitAxesImpCde;
use Psr\Container\ContainerInterface;

class DuplicationDemandeRepo extends AbsRepository
{
    /**
     * @return array<mixed>|null
     */
    public function getDemandeForFormDuplicate(string $idDA) :?array
    {
        
        $row = $this->fetchAssocOne(
            'SELECT '
            . $this->generateFieldList([
                'DA_ENTET' => ['NO_DA','DTE_EMISS','CHIF_EXEC','REFUSEE','TRAITEE','SIGNEE'],
                'SOCIETE' => ['CODE_STE','RAIS_SOC'],
                'Demandeur' => ['CODE','NOM'],
                'FOURNISS' => ['CODE','RS'],
                'CentreEmet' => ['CODE_CTR','RAIS_SOC'],
                'CentreLivr' => ['CODE_CTR','RAIS_SOC'],
                'TYPDOC' => ['TYPE','LIBELLE'],
            ])
            . '
            FROM DA_ENTET with(nolock)
            LEFT JOIN HASTUTIL as Demandeur with(nolock) ON Demandeur.CODE = DA_ENTET.NO_DEM
            LEFT JOIN SOCIETE with(nolock) ON SOCIETE.CODE_STE = DA_ENTET.CODE_STE
            LEFT JOIN FOURNISS with(nolock) ON FOURNISS.CODE = DA_ENTET.FOU
            LEFT JOIN CENTRE as CentreEmet with(nolock) ON CentreEmet.CODE_CTR = DA_ENTET.DAENT_CENTRE_EMETTEUR
            LEFT JOIN CENTRE as CentreLivr with(nolock) ON CentreLivr.CODE_CTR = DA_ENTET.CTR_LIV
            JOIN TYPDOC with(nolock) ON TYPDOC.TYPE = DA_ENTET.TYP_DOC
            WHERE DA_ENTET.NO_DA = :idDA
            ',
            ['idDA' => $idDA]
        );

        if (empty($row)) {
            return null;
        }

        $split = $this->splitRowByTable($row);
        return $split['DA_ENTET'] + [
            'Societe' => $split['SOCIETE'],
            'Demandeur' => $split['Demandeur'],
            'Fournisseur' => $split['FOURNISS'],
            'CentreEmet' => !empty($split['CentreEmet']['CODE_CTR']) ?
                $split['CentreEmet'] : null,
            'CentreLivr' => !empty($split['CentreLivr']['CODE_CTR']) ?
                $split['CentreLivr'] : null,
            'TypeDoc' => $split['TYPDOC'],
        ];
    }
}
