<?php

namespace Modules\Ajax\Repository;

use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Parametres\Constante;
use Helpers\QueryBuilder\AbsRepository;

class Autocomplete extends AbsRepository
{
    /**
     * fournisseurFacture
     * @param string $value
     * @param string $valid
     * @return array<mixed>
     */
    public function fournisseurFacture(string $value, $valid = '') : ?array
    {
        $value = strtoupper($value);
        $req ="select distinct TOP 5  CODE,RS from FOURNISS F with (nolock) where (upper(CODE) like :value1 OR upper(RS) like :value2 OR upper(NO_SIRET) like :value3 OR upper(TAXE2) like :value4 OR upper(TAXE3) like :value5 OR upper(TAXE4) like :value6 OR upper(ENSCOMM) like :value7)";

        if ($valid=='VALIDE') {
            $req .=" and ((F.DTEVALMIN<'".date('Ymd')."' and F.DTEVALMAX>'".date('Ymd')."') or (F.DTEVALMIN<'".date('Ymd')."' and F.DTEVALMAX='00000000')) ";
        }
        if ($valid=='NON_VALIDE') {
            $req .=" and ((F.DTEVALMAX!='00000000' and F.DTEVALMAX<'".date('Ymd')."'))";
        }
        
        $arrayReq = [
            ':value1' => '%'.$value.'%',
            ':value2' => '%'.$value.'%',
            ':value3' => '%'.$value.'%',
            ':value4' => '%'.$value.'%',
            ':value5' => '%'.$value.'%',
            ':value6' => '%'.$value.'%',
            ':value7' => '%'.$value.'%',
        ];
        
        return $this->fetchAssocAll($req, $arrayReq);
    }

    /**
     * @param string $value
     * @return array<mixed>
     */
    public function fournisseurSociete(?string $value = null)
    {
        $req = "select distinct TOP 5 CODE,RS from FOURNISS with (nolock) where 1=1";

        $arrayReq = [];
        if ((Sql::paravrac($this->pdo, 'PARAMFOU', 'LIEN_FOU_STE_ACTIF') == 'O') && !Roles::droitsUtilisateur($this->pdo, 'HA_FOU_TST')) {
            $req .= " and (
                exists (select * from LIENFOUGRPSTE lien with (nolock) where lien.TYPE_FG = 'F' and lien.CODE_FOUGR = FOURNISS.CODE and lien.CODE_STE = :codeSte)
                or not exists (select * from LIENFOUGRPSTE lien with (nolock) where lien.TYPE_FG = 'F' and lien.CODE_FOUGR = FOURNISS.CODE)
            ) ";

            $arrayReq[':codeSte'] = $_SESSION["Session_SocUsr"];
        }

        $post['filter_CODE'.Constante::spliter.'RS'] = $value;

        $whereArray = \Helpers\Filter\FilterTable::splitFilter($post, 0, 0, 1);
        
        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);
    }
}
