<?php

namespace Modules\Stock\Repository;

use Entity\Model\Sarticle;
use Exception;
use Helpers\QueryBuilder\AbsRepository;

class DilispecRepo extends AbsRepository
{
    /**
     * @param array<string,mixed> $entEntity
     * @param array<string,mixed> $lignEntity
     * @return int
     * @throws Exception
     */
    public function countRubriqueForLigneImputations(array $entEntity, array $lignEntity): int
    {
        $stockArticle = (new Sarticle($this->pdo))->find(['CODE_ART' => $lignEntity['CODE_ART']]);

        $si = $lignEntity['SECTIMP'];
        $codeSte = $entEntity['CODE_STE'];
        $sca = $lignEntity['SSCPTEANA'];
        $rub = $stockArticle['RUBRIQUE'];

        $req = "SELECT COUNT(*) AS NB FROM DILISPEC 
                WHERE TYPEDICO='SEMIMPRUBS'
                AND CODEDICO BETWEEN '$codeSte' AND  trim('$codeSte') + REPLICATE(' ', 7-len(trim('$codeSte'))) + '|9999999999'
                AND (
                    LIB01DICO=trim('$rub') + replicate(' ', 8-len(trim('$rub'))) + ' ' + trim('$si') + replicate(' ', 14-LEN(trim('$si'))) + ' ' + '$sca' OR 
                    LIB01DICO=trim('$rub') + replicate(' ',8-len(trim('$rub'))) + ' ' + '*' + replicate(' ',13) + ' ' + '$sca'
                )
        ";

        return (int) $this->fetchAssocAll($req, [])[0]['NB'];
    }

    /**
     * @param array<string,mixed> $entEntity
     * @param array<string,mixed> $lignEntity
     * @return int
     * @throws Exception
     */
    public function countForLigneImputations(array $entEntity, array $lignEntity): int
    {
        $si = $lignEntity['SECTIMP'];
        $codeSte = $entEntity['CODE_STE'];
        $sca = $lignEntity['SSCPTEANA'];

        $req = "SELECT COUNT(*) AS NB FROM DILISPEC
                WHERE TYPEDICO='SEMIMPLIST'
                AND CODEDICO BETWEEN '$codeSte' AND trim('$codeSte') + REPLICATE(' ',7-len(trim('$codeSte'))) + '|9999999999'
                AND LIB01DICO=trim('$si') + replicate(' ',14-LEN(trim('$si'))) + ' ' + '$sca'
        ";

        return (int) $this->fetchAssocAll($req, [])[0]['NB'];
    }

    /**
     * @param array<string,mixed> $entEntity
     * @param array<string,mixed> $lignEntity
     * @return array<int,array<string,mixed>>
     * @throws Exception
     */
    public function getImputationParametrage(array $entEntity, array $lignEntity): array
    {
        $stockArticle = (new Sarticle($this->pdo))->find(['CODE_ART' => $lignEntity['CODE_ART']]);

        $codeSte = $entEntity['CODE_STE'];
        $rub = $stockArticle['RUBRIQUE'];

        $req = "SELECT LIB01DICO FROM DILISPEC WHERE TYPEDICO='SEMIMPRUBE' AND CODEDICO=trim('$codeSte') + REPLICATE(' ',7-len(trim('$codeSte'))) + '|' + '$rub'";

        return $this->fetchAssocAll($req, []);
    }
}
