<?php

namespace Modules\ProjetAchat\Repository;

use Entity\Model\DoaActionsRACI;
use Helpers\Outil\Date;
use Helpers\Outil\Roles;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Parametres\Constante;
use Helpers\QueryBuilder\AbsRepository;
use Modules\ProjetAchat\Service\DoublonsService;
use Modules\GlobalApplication\Outil\UOService;

class ProjetAchatEventRepo extends AbsRepository
{
    /**
     * @param array<mixed> $arrayReq
     */
    private function getMainRequest(array &$arrayReq) :string
    {
        return "SELECT 
            DOA_EVT.*, 
            " . $this->selectTrad('DOAR_TYPE_EVT.LIB', 'LIB_EVENT') .",
            HASTUTIL.NOM as Auteur_NOM, 
            DOA.REF as Proj_REF, 
            DOA.LIB as Proj_LIB
        FROM DOA_EVT with(nolock)
        LEFT JOIN DOAR_TYPE_EVT with(nolock) ON DOAR_TYPE_EVT.CODE_EVT = DOA_EVT.CODE_EVT
        " . $this->joinTrad('DOAR_TYPE_EVT.LIB', $arrayReq) . "
        LEFT JOIN DOA with(nolock) ON DOA.ID = DOA_EVT.ID_DOA
        LEFT JOIN HASTUTIL with(nolock) ON HASTUTIL.CODE = DOA_EVT.CODE_USER
        WHERE 1=1 ";
    }

    /**
     * @param array<mixed> $post
     * @param array<mixed> $arrayReq
     */
    private function applyMainFilter(array $post, array &$arrayReq) :string
    {
        $req = '';
        if (!empty($post['ID'])) {
            $req .= " AND ID_DOA = :idDoa";
            $arrayReq[':idDoa'] = $post['ID'];
        } else {
            $req .= " AND REF is not null";
        }
        
        if (isset($post['filter_HEURE_EVT']) && $post['filter_HEURE_EVT'] != '') {
            $post['filter_HEURE_EVT'] = str_replace(':', '', $post['filter_HEURE_EVT']);
        }

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

    /**
     * @param array<string> $post
     * @return array<array<mixed>>
    */
    public function listEvent(array $post = []): ?array
    {
        $paginator = new PaginatorGestion();
        $paginator->generate(0, 'DATE_EVT', 'DESC');

        $arrayReq = [];
        $req = $this->getMainRequest($arrayReq)
            . $this->applyMainFilter($post, $arrayReq);
        
        $paginator->injecterSqlCount($req, $post, $arrayReq, $this->pdo);

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

    /**
     * @param array<string> $post
    */
    public function export(array $post = []): \PDOStatement
    {
        $arrayReq = [];
        return $this->createStatement(
            $this->getMainRequest($arrayReq)
            . $this->applyMainFilter($post, $arrayReq),
            $arrayReq
        );
    }
}
