<?php

namespace Modules\Utilisateur\Repository;

use Helpers\QueryBuilder\AbsRepository;

class UserBackupRepo extends AbsRepository
{

    /**
     * @return array<mixed>
     */
    public function findByUser(string $userCode) :array
    {
        return $this->fetchAssocAll(
            'SELECT USRBACK.*, HASTUTIL.NOM
                FROM USRBACK with(nolock)
                LEFT JOIN HASTUTIL with(nolock) ON HASTUTIL.CODE = USRBACK.COD_USR
                WHERE USRBACK.COD_BAC = :user',
            [':user' => $userCode]
        );
    }

    /**
     * @return array<mixed>
     */
    public function getBackup()
    {
        $req = 'select USRBACK.*, usr.NOM, usr.CODE_STE, soc.RAIS_SOC from USRBACK with (nolock)
                left join HASTUTIL usr with (nolock) on usr.CODE = USRBACK.COD_BAC
                left join SOCIETE soc with (nolock) on soc.CODE_STE = usr.CODE_STE
                where COD_USR = :user';

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

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

    /**
     * @param array<mixed> $post
     * @return array<mixed>
     */
    public function listeBackupDispo($post)
    {
        $req = "select CODE, NOM, FONCTION, ADMLOCAL, ADMCENTR, EMAIL, UTIMULTI, HASTUTIL.CODE_STE, DEMAND, USRSUPHIE, SOCIETE.RAIS_SOC
                from  HASTUTIL with(nolock)
                left outer join SOCIETE with(nolock) on SOCIETE.CODE_STE  = HASTUTIL.CODE_STE
                where HASTUTIL.CODE !=:user1
                and (HASTUTIL.CODE_STE = (select tb_user.CODE_STE from HASTUTIL tb_user with(nolock) where tb_user.CODE=:user2) or UTIMULTI = 0x54)
                and  HASTUTIL.CODE not in (select COD_BAC from USRBACK with(nolock) where COD_USR = :user3 AND USRBACK.COD_BAC = HASTUTIL.CODE) 
                and  HASTUTIL.ACCOXAPR  = 0x54 
                and (HASTUTIL.DTE_FERM = '00000000' or HASTUTIL.DTE_FERM >= '".date('Ymd')."')
                and (HASTUTIL.DTE_OUV  = '00000000' or HASTUTIL.DTE_OUV  <= '".date('Ymd')."')";

        $arrayReq = [
            ':user1' => $_SESSION["Session_Login"],
            ':user2' => $_SESSION["Session_Login"],
            ':user3' => $_SESSION["Session_Login"],
        ];

        $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);
    }
}
