<?php

namespace Entity\Model;

use Helpers\QueryBuilder\QueryBuilder;

/**
 * Type de filtre d'etat stats définie par l'utilisateur
 */
class FentFiltEnt extends QueryBuilder
{
    protected string $table = 'FENT_FILT_ENT with (nolock)';
    protected string $primaryKey = 'FENT_CODE_FILTRE';
    protected string $libelle = 'FENT_LIB_FILTRE';

    public function update(array $valueUpdate, $id)
    {
        return parent::update($this->processCalculable($valueUpdate), $id);
    }

    public function insert(array $valueInsert = []): bool
    {
        return parent::insert($this->processCalculable($valueInsert));
    }

    /**
     * @param array<mixed> $entity
     * @return array<mixed>
     */
    private function processCalculable(array $entity) :array
    {
        // Calculate flag
        // Note : those flags are useless and probably only used by Magic
        if ($entity['FENT_TYPE_AFFICHAGE'] == 'R'
            && ! empty($entity['FENT_NM_WHERE'])
        ) {
            $entity['FENT_IND_SAISIE_LIBRE'] = true;
        }

        if ($entity['FENT_TYPE_AFFICHAGE'] == 'R') {
            if (! empty($entity['FENT_NM_REQ_LIB'])) {
                $entity['FENT_IND_PERIMETRE'] = true;
            }
            if (! empty($entity['FENT_NOM_CHP_PER_SOC'])
                || ! empty($entity['FENT_NOM_CHP_PER_CONF'])
            ) {
                $entity['FENT_IND_PERIMETRE'] = true;
            }
        }
        return $entity;
    }

    // TODO : factorize with other QueryBuilder
    // Cascade delete MEMOS
    public function delete($id)
    {
        $inTrans = $this->pdo->inTransaction();
        if (!$inTrans) {
            $this->pdo->beginTransaction();
        }
        
        $param = [];
        $this->pdo->prepare(
            "DELETE MEMOS FROM MEMOS 
            JOIN FENT_FILT_ENT 
                ON FENT_FILT_ENT.FENT_NM_REQ_LIB = MEMOS.NODEMEMO
                OR FENT_FILT_ENT.FENT_NM_WHERE = MEMOS.NODEMEMO
            WHERE " . $this->getDeleteWhere($id, $param)
        )
        ->execute($param);

        $res = parent::delete($id);
        
        if (!$inTrans) {
            $this->pdo->commit();
        }

        return $res;
    }
}
