<?php

namespace Modules\Additional\Specifique\Client164\Modules\Suivi\Repository;

use Helpers\QueryBuilder\AbsRepository;

class EtatCommandeSpecifiqueRepository extends AbsRepository
{
    /**
     * Summary of getMaxDteLivCon
     * @param string|int $idCommande
     * @return array<mixed>
     */
    public function getMaxDteLivCon(string|int $idCommande)
    {
        $query = "select MAX(DTELIVCON) as MAXDTELIVCON from CA_LIGNE where NO_CDE = :noCde";
        return $this->fetchAssocOne($query, [':noCde' => $idCommande]);
    }

    /**
     * Summary of getAllSignataireFromCaEvent
     * @param string $idCommande
     * @return string[][]
     */
    public function getAllSignataireFromCaEvent(string $idCommande): array
    {
        $query = "select
                        evt.*
                    from
                        CA_EVENT evt
                    join CA_ENTET ent on evt.NO_CDE = ent.NO_CDE
                    where evt.NO_CDE = :noCde
                        and ent.SIGNEE = 'T'
                        and evt.CODE IN ('SIG', 'SPC')
                        and evt.NUM_ORD >= ent.EVE_VAL
                ";
        return $this->fetchAssocAll($query, [':noCde' => $idCommande]);
    }

    /**
     * Summary of getAssociatedDemAchat
     * @param string $numCde
     * @return string[][]
     */
    public function getAssociatedDemAchat(string $numCde): array
    {
        return $this->fetchAssocAll(
            'SELECT DISTINCT DA_ENTET.NO_DA, 
                Demandeur.NOM as Demandeur_NOM
            FROM DA_ENTET with (nolock)
            JOIN CA_LIGNE with(nolock) 
                ON CA_LIGNE.NO_DA = DA_ENTET.NO_DA
                AND CA_LIGNE.NO_CDE = :commandeId
            LEFT JOIN HASTUTIL as Demandeur with(nolock) 
                ON Demandeur.CODE = DA_ENTET.NO_DEM',
            ['commandeId' => $numCde],
        );
    }

    /**
     * Summary of getAllSignataireSignatairesFromDemAchat
     * @param array<mixed> $listDemAchatId
     * @return string[][]
     */
    public function getAllSignataireSignatairesFromDemAchat(array $listDemAchatId): array
    {
        return $this->fetchAssocAll(
            "select
                        evt.*
                    from
                        DA_EVENT evt
                    join DA_ENTET ent on evt.NO_DA = ent.NO_DA
                    where evt.NO_DA IN ( :{$this->mapDA($listDemAchatId)} )
                        and ent.SIGNEE = 'T'
                        and evt.CODE IN ('SDA', 'SPC')
                        and evt.NUM_ORD >= ent.EVE_VAL
                ",
            $listDemAchatId,
        );
    }

    /**
     * Summary of mapDA
     * @param array<mixed> $liste
     * @return string
     */
    private function mapDA(array $liste): string
    {
        return \implode(', :', $liste);
    }
}
