<?php

namespace Modules\GlobalApplication\Repository;

use Helpers\Outil\Sql;
use Helpers\QueryBuilder\AbsRepository;

class Signature extends AbsRepository
{
    // phpcs:ignore
    public function ReplaceSqlPointeur(&$utf8str)
    {
        $result = str_replace('\'', '\'\'', $utf8str);
        return $result;
    }

    /**
     * getListeDelegateurs
     * @param array<string> $post
     * @return array<mixed>
     */
    public function getListeDelegateurs(array $post) : ?array
    {
        $today = Date('Ymd');
        
        // Spec 3523
        $req = "SELECT distinct SIGNAT, DELEG, DTE_DEB, DTE_FIN, hasig.NOM, 'ABS' as TYPEDEL
		FROM SIG_DELEG with(nolock)
		LEFT JOIN HASTUTIL hasig with(nolock) on SIG_DELEG.SIGNAT = hasig.CODE and (hasig.SIG_DA = 0x54 or hasig.SIG_CDE = 0x54 or hasig.SIG_BAP = 0x54 or hasig.SIG_REF = 0x54)
		WHERE DELEG = :user
		AND DTE_DEB <= $today
		AND (DTE_FIN >= $today or DTE_FIN = '00000000')";
        
        $arrayReq = [':user' => $_SESSION['Session_Login']];
        
        if (Sql::boolSql(Sql::paravrac($this->pdo, 'PARAMSIG', 'DELEG_AUTO_SUP_HIER'))) {
            $req .= " UNION
            SELECT CODE, SUPHIER as DELEG, '00000000', '00000000', NOM, 'HIE' as TYPEDEL
			FROM HASTUTIL with(nolock)
			WHERE SUPHIER = '".$_SESSION['Session_Login']."' AND (SIG_DA = 0x54 OR SIG_CDE = 0x54 OR SIG_BAP = 0x54 OR SIG_REF = 0x54)";
        }
        
        if (Sql::boolSql(Sql::paravrac($this->pdo, 'PARAMSIG', 'DELEG_AUTO_RESP_UO'))) {
            $req .= " UNION
            SELECT CODE, '".$_SESSION['Session_Login']."' as DELEG, '00000000', '00000000', NOM, 'HIE' as TYPEDEL
			FROM HASTUTIL with(nolock)
			WHERE CODE_UO in (SELECT CODE_UO FROM UO with(nolock) WHERE RESP_HIER = '".$_SESSION['Session_Login']."')
			AND (SIG_DA = 0x54 OR SIG_CDE = 0x54 OR SIG_BAP = 0x54 OR SIG_REF = 0x54)";
        }
        
        $whereArray = \Helpers\Filter\FilterTable::splitFilter($post, 0, 0, 1);
        $filtreAvance = new \Helpers\Filter\FiltreAvance\Generator($post);
        $req .= $filtreAvance->generateSql(1);
        $filtreAvance->pushArray($arrayReq);
        
        if (count($whereArray)>  0) {
            $req .= $whereArray[0].$whereArray['tri'];
            
            if (count($whereArray[1]) != 0) {
                $arrayReq = array_merge($arrayReq, $whereArray[1]);
            }
        }

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

    /**
     * @return array<mixed>
     */
    public function countDelegABS()
    {
        $req = "select COUNT(*) count from SIG_DELEG with (nolock)
                where SIGNAT = :user and DTE_DEB <= '".date('Ymd')."'
                AND (DTE_FIN >= '".date('Ymd')."' or DTE_FIN = '00000000')";

        $arrayReq = [
            ':user' => $_SESSION["Session_Login"]
        ];

        return $this->fetchAssocOne($req, $arrayReq);
    }
}
