<?php

namespace Entity\Model;

use Helpers\Filter\FilterTable;
use Helpers\QueryBuilder\QueryBuilder;
use Helpers\Trad\Trad;

class Modepaie extends QueryBuilder
{
    protected string $table = 'MODEPAIE with (nolock)';
    protected string $primaryKey = 'CODE_MDP';
    protected string $libelle = 'LIBELLE';
    public string $titre;

    public function getArchitecture(\Helpers\Trad\ITrad $trad)
    {
        return  [
            'CODE_MDP' =>
            [
                'nomChamp' => $trad->t('Code Mode De paiement'),
                'type' => 'TEXTE',
                'taille' => 7,
                'obligatoire' => true
            ],
            'LIBELLE' =>
            [
                'nomChamp' => $trad->t('Libelle'),
                'type' => 'TEXTE',
                'taille' => 20,
                'obligatoire' => true

            ],
            'CTRLDONSAI' =>
            [
                'nomChamp' => $trad->t('Controle Don sai'),
                'type' => 'RADIO',
                'taille' => 1,
                'obligatoire' => true

            ]
        ];
    }

    
    /**
     * @return array<mixed>|null
     */
    public function find($id, array $selectTables = [], $post = [], $option = null)
    {
        // We use a custom query in order to return a translated LIBELLE

        $req = "SELECT 
            MODEPAIE.CODE_MDP, 
            MODEPAIE.CTRLDONSAI,
            CASE 
                WHEN ISNULL(t.LIBELLE,'') = ''
                THEN MODEPAIE.LIBELLE
                ELSE t.LIBELLE 
            END LIBELLE
        FROM MODEPAIE WITH(nolock)
        LEFT JOIN TRAD_MDP t WITH(NOLOCK) 
            ON t.CODE_MDP = MODEPAIE.CODE_MDP AND COD_LNG = :langue";
        $arraySelect = [
            'langue' => $_SESSION['Session_Langue'],
        ];

        if (is_array($id)) {
            $req .= ' WHERE ' . $this->makeWhereFromArray($id, $arraySelect);
        } else {
            if (empty($this->primaryKey)) {
                throw new \Exception('Invalid primary key for "'.self::class.'"');
            }
            // TODO : return false if $id is empty ?
            $req .= ' WHERE MODEPAIE.CODE_MDP = :id';
            $arraySelect += [':id' => $id];
        }

        $whereArray = FilterTable::splitFilter($post, 1, 0, 1);
        if (!empty($whereArray[0])) {
            $req .= $whereArray[0];
            
            if (!empty($whereArray[1])) {
                $arraySelect = array_merge($arraySelect, $whereArray[1]);
            }
        }

        $stmt = $this->pdo->prepare($req);
        $stmt->execute($arraySelect);

        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        if (empty($row)) {
            return null;
        }

        return $row;
    }
}
