<?php

namespace Modules\Additional\Specifique\Client64\Modules\Panier\Service;

use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Modules\Ajax\Repository\InitCS;

class UpdateCdcBySi
{
    /**
     * @param string $codeSte
     * @param string $si
     */
    public static function updateCdcBySI(\pdo $pdo, $codeSte = '', $si = ''):string
    {
        $sisecto = \Helpers\Outil\Roles::droit($pdo, 'SISECTOR', 'PARAMSTE');
        if ($sisecto) {
            $prefix_code_dir = str_pad($codeSte, 7, ' ', STR_PAD_RIGHT);
        } else {
            $prefix_code_dir = '       ';
        }

        $req = "SELECT 
                    VALEUR
                from CS_DON with (nolock) 
                WHERE COD_TAB='SECTIMPU' AND COD_ENR = :codeEnr 
                AND NUM_FIX = (SELECT LIB01DICO FROM DILISPEC with(nolock) WHERE TYPEDICO='PARAMSKEMA' AND CODEDICO='NCS_SECTIMPU_CODECOMP') ";
        
        $arrayReq = [
            ':codeEnr' => $prefix_code_dir . $si,
        ];

        $champSupp = $pdo->prepare($req);
        $champSupp->execute($arrayReq);
        
        return $champSupp->fetch()['VALEUR'];
    }

    /**
     * @param \pdo $pdo
     * @param \Helpers\Trad\ITrad $trad
     * @param string $codeSte
     * @param string $cdc
     * @param string $si
     * @return string|null
     */
    public static function controleCDCBySi(\pdo $pdo, ITrad $trad, $codeSte = '', $cdc = '', $si = '')
    {
        $sisecto = \Helpers\Outil\Roles::droit($pdo, 'SISECTOR', 'PARAMSTE');
        if ($sisecto) {
            $prefix_code_dir = str_pad($codeSte, 7, ' ', STR_PAD_RIGHT);
        } else {
            $prefix_code_dir = '       ';
        }

        $numCS = Sql::dilispec($pdo, 'PARAMSKEMA', 'NCS_CODECOMP_SECTIMPU');
        if ($numCS) {
            $SICs = ChampSupp::getValueCS('CODECOMP', $prefix_code_dir . $cdc, $numCS, $pdo);
    
            if ($SICs) {
                if ($si != $SICs) {
                    return $trad->t('le CDC saisi n\'existe pas, veuillez vérifier');
                }
            }
        }
        
        return null;
    }
}
