<?php

namespace Modules\Signature\Repository;

use Entity\Model\Hastutil;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\QueryBuilder\AbsRepository;

class DASignRepository extends AbsRepository
{
    private int $nivConf;

    private function getNivConf(): int
    {
        if ($_SESSION["Session_Login"] == 'OXAUSER') {
            $this->nivConf = 99;
        } else {
            /** @phpstan-ignore-next-line */
            if (!isset($this->nivConf)) {
                $hastutil = new Hastutil($this->pdo);
                $infoUser = $hastutil->find($_SESSION["Session_Login"]);
                $this->nivConf = (int)$infoUser['NIV_CONF'];
            }
        }
        return $this->nivConf;
    }

    /**
     * @param array<mixed> $post
     * @param string $signataire
     * @return array<array<mixed>>
     */
    public function listTobeSigned(array $post = [], $signataire = '')
    {
        $siSecto = Roles::droit($this->pdo, 'SISECTOR', 'PARAMSTE');

        $req = "SELECT  DA_ENTET.NO_DA, DA_ENTET.DTE_EMISS, DA_ENTET.DTE_VAL, 
                        DA_ENTET.NO_DEM, DA_ENTET.FOU, DA_ENTET.TOTAL_DA, 
                        DA_ENTET.TOTAL_DA_TTC, DA_ENTET.DEVISE, SIG_DA.SIGNAT,
                        HASTUTIL.NOM demandeur, FOURNISS.RS ,
                        DA_ENTET.CODE_STE, SOCIETE.RAIS_SOC,
                        DA_ENTET.SECTIMP ,SECTIMPU.LIBELLE LIB_SI,
                        DA_ENTET.SIGNEE, DA_ENTET.REFUSEE, DA_ENTET.VALIDITE,
                        ( select count(*) from DOC_ATT  with (nolock) where NO_DA='DA_ENTET' AND COD_ENR = right('000000000' + cast(DA_ENTET.NO_DA as varchar), 9) ) DOC_ATT,
                        ( select count(*) from DA_PIJO  with (nolock) where DA_PIJO.NO_DA = DA_ENTET.NO_DA ) PJ
                FROM DA_ENTET with (nolock)
                INNER JOIN SIG_DA with (nolock) ON SIG_DA.NO_DA = DA_ENTET.NO_DA 
                LEFT JOIN HASTUTIL with (nolock) ON HASTUTIL.CODE = DA_ENTET.NO_DEM
                LEFT JOIN FOURNISS with (nolock) ON FOURNISS.CODE = DA_ENTET.FOU 
                left join TYPDOC with (nolock) on DA_ENTET.TYP_DOC = TYPDOC.TYPE
                left join SOCIETE with (nolock) on SOCIETE.CODE_STE = DA_ENTET.CODE_STE
                LEFT JOIN SECTIMPU with (nolock) on SECTIMPU.CODE_SI = DA_ENTET.SECTIMP and SECTIMPU.CODE_STE = " . ($siSecto ? 'DA_ENTET.CODE_STE' : "''") . " 
                WHERE TYPDOC.NIV_CONF <= :nivConf and DA_ENTET.SIGNEE = " . Sql::setBoolSql(0) . " 
                " . Roles::getClauseSocieteOuvert('SOCIETE') . "
                AND SIG_DA.SIGNAT = :user 
                AND SIG_DA.INFORME	 = 0x46
                AND SIG_DA.SIGNABLE = " . Sql::setBoolSql(1) . "";



        if ($signataire) {
            $signat = $signataire;
        } else {
            $signat = $_SESSION['Session_Login'];
        }
        $arrayReq = [':user' => $signat];
        $arrayReq[':nivConf'] = $this->getNivConf();

        $req .= Roles::getClausePerimetreSociete('DA_ENTET.CODE_STE', $arrayReq);

        if ($post['filter_NO_DA'] ?? '') {
            $post['filter_DA_ENTET.NO_DA'] = $post['filter_NO_DA'];
            unset($post['filter_NO_DA']);
        }

        if ($post['filter_egal_CODE_STEdebut-----finRAIS_SOC'] ?? '') {
            $post['filter_egal_DA_ENTET.CODE_STEdebut-----finSOCIETE.RAIS_SOC'] = $post['filter_egal_CODE_STEdebut-----finRAIS_SOC'];
            unset($post['filter_egal_CODE_STEdebut-----finRAIS_SOC']);
        }

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

    /**
     * signataireAttendu
     *
     * @param  int $da
     * @return array<mixed>
     */
    public function signataireAttendu(int $da)
    {
        $req = "select * from SIG_DA with (nolock)
                left join HASTUTIL with (nolock) on HASTUTIL.CODE = SIG_DA.SIGNAT
                where NO_DA = :da";

        $arrayReq[':da'] = $da;

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

    /**
     * @param string $code
     * @return array<mixed> $array
     */
    public function listeSignat(string $code)
    {
        $req =
            "SELECT * FROM SIG_DA WITH (NOLOCK) 
        LEFT JOIN HASTUTIL WITH (NOLOCK) ON HASTUTIL.CODE = SIG_DA.SIGNAT
        WHERE NO_DA = :value
        ORDER BY ORDRE";

        $arrayReq = [':value' => $code];

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

    /**
     * @param array<mixed> $array
     * @return void
     */
    public function insertNewSignat($array)
    {
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $req =
            "INSERT INTO SIG_DA (SIGNAT, NO_DA, DTE_MISE, ORDRE, SIGNABLE, DAROLES, INFORME)
        VALUES(:value1, :value2, :value3, " . $array['ORDRE'] . ", " . sql::setBoolSql($array['SIGNABLE']) . ", :value6, " . sql::setBoolSql($array['INFORME']) . ")";

        $arrayReq = [
            ':value1' => $array['SIGNAT'],
            ':value2' => $array['NO_DA'],
            ':value3' => $array['DTE_MISE'],
            ':value6' => $array['DAROLES'],
        ];

        $requete = $this->pdo->prepare($req);
        $requete->execute($arrayReq);
    }

    /**
     *
     * @param  int $numDA
     * @return array<mixed>
     */
    public function getCommentaireSignataire(int $numDA)
    {
        $req = "select HASTUTIL.NOM, HASTUTIL.CODE, CONTMEMO
                from DA_EVENT with (nolock)
                left join MEMOS with (nolock) on MEMOS.NODEMEMO = DA_EVENT.NM_COMME
                left join HASTUTIL with (nolock) on HASTUTIL.CODE = DA_EVENT.UTIL
                where DA_EVENT.CODE = 'SDA' AND NO_DA = :numDA and CONTMEMO != ''
                order by NUM_ORD";

        $arrayReq[':numDA'] = $numDA;

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