<?php

namespace Modules\EtatStatistiques\Repository;

use Entity\Model\EtatStat;
use Entity\Model\ReqEnt;
use Entity\Model\ReqFiltres;
use Entity\Model\ReqFiltresDon;
use Entity\Model\ReqFrom;
use Entity\Model\ReqRuptures;
use Entity\Model\ReqSelect;
use Helpers\Outil\ArrayHelper;
use Helpers\Outil\Sql;
use Helpers\QueryBuilder\AbsRepository;

class EtatStatRepo extends AbsRepository
{


    /**
     * Retrieve
     * EtatStat
     * EtatStat.listFilter[]
     * EtatStat.listQuery[]
     * EtatStat.listQuery[].WHERE (MEMOS of NM_WHERE)
     * EtatStat.listQuery[].REQ_LIB (MEMOS of NM_REQ_LIB)
     * EtatStat.listQuery[].listFilter[]
     * EtatStat.listQuery[].listRupture[]
     *
     * @param string $id
     * @return array<mixed>|null
     */
    public function getDetail(string $id)
    {
        $etatstat = (new EtatStat($this->pdo))->find([
            'CODETAT' => $id,
            'SOURCE' => 'OXACHARTS_REQ',
        ]);
        if (empty($etatstat)) {
            return null;
        }

        // Currently not used
        $baseName = 'V_OXACHARTS_'.str_replace(['-', ' '], '_', $etatstat['CODETAT']);
        $time = time();
        $etatstat['viewName'] = $baseName . '_' . $time;
        $etatstat['viewNameTest'] = $etatstat['viewName'] . '_T' . $time;

        

        $etatstat['listFilter'] = array_map(
            function ($filter) {
                return [
                    'FENT_IND_SAISIE_LIBRE' => Sql::toBool($filter['FENT_IND_SAISIE_LIBRE']),
                    'FENT_IND_PERIMETRE' => Sql::toBool($filter['FENT_IND_SAISIE_LIBRE']),
                    '_id' => implode('|', ArrayHelper::filterByKey(
                        $filter,
                        [/*'REQ_ETAT',*/'CODE_FILTRE','TYPE_FILTRE']
                    ))
                ] + $filter;
            },
            $this->listReqFiltre($id)
        );

        $etatstat['listQuery'] = array_map(
            function ($reqEnt) {
            // TODO : optimize query
                return $reqEnt + [
                    'WHERE' => Sql::getMemo($this->pdo, $reqEnt['NM_WHERE']),
                    'REQ_LIB' => Sql::getMemo($this->pdo, $reqEnt['NM_REQ_LIB'])
                ];
            },
            (new ReqEnt($this->pdo))->findAll(['REQ_ETAT' => $id])
        );

        $this->arrayJoinManyToMany(
            $etatstat['listQuery'],
            array_map(
                function ($select) {
                    return [
                        'ELEM_GRP_BY' => Sql::toBool($select['ELEM_GRP_BY']),
                    ] + $select;
                },
                (new ReqSelect($this->pdo))->findAll([
                    'REQ_ETAT' => $id,
                ])
            ),
            'REQ_ID',
            'listSelect'
        );
        $this->arrayJoinManyToMany(
            $etatstat['listQuery'],
            (new ReqFrom($this->pdo))->findAll([
                'REQ_ETAT' => $id,
            ]),
            'REQ_ID',
            'listFrom'
        );

        //$mapFilter = array_column($etatstat['listFilter'], null, '_id');

        $this->arrayJoinManyToMany(
            $etatstat['listQuery'],
            array_map(
                function ($filterDon) /*use($mapFilter)*/ {
                    // $filterId = implode('|', ArrayHelper::filterByKey($mapFilter, [
                    //     /*'REQ_ETAT',*/ 'CODE_FILTRE', 'TYPE_FILTRE',
                    // ]));
                    return [
                        //'Filter' => $mapFilter[ $filterId ] ?? null,
                    ] + $filterDon;
                },
                (new ReqFiltresDon($this->pdo))->findAll(['REQ_ETAT' => $id])
            ),
            'REQ_ID',
            'listFilter'
        );

        $this->arrayJoinManyToMany(
            $etatstat['listQuery'],
            (new ReqRuptures($this->pdo))->findAll([
                'REQ_ETAT' => $id,
            ]),
            'REQ_ID',
            'listRupture'
        );
        $this->arrayJoinManyToMany(
            $etatstat['listQuery'],
            (new ReqRuptures($this->pdo))->findAll([
                'REQ_ETAT' => $id,
            ]),
            'REQ_ID',
            'listRuptureTotaux'
        );

        return $etatstat;
    }

    /**
     * @return string[][]
     */
    public function listReqFiltre(string $codeEtat)
    {
        return $this->fetchAssocAll(
            "SELECT 
                REQ_FILTRES.*,
                FENT_FILT_ENT.*
            FROM REQ_FILTRES with(nolock) 
            LEFT JOIN FENT_FILT_ENT with(nolock) 
                ON FENT_FILT_ENT.FENT_CODE_FILTRE = REQ_FILTRES.CODE_FILTRE
            WHERE REQ_FILTRES.REQ_ETAT = :codeEtat",
            ['codeEtat' => $codeEtat]
        );
    }
}
