<?php

namespace Entity\Model;

use Helpers\QueryBuilder\QueryBuilder;

class CaEvent extends QueryBuilder
{
    protected string $table = 'CA_EVENT with (nolock)';
    protected string $primaryKey = '';
    protected string $libelle = '';

    public function insertEntity(
        string $commandeId,
        string $commandeAvnId,
        string $code,
        string $userCode,
        string $memoId
    ) :void {
        $param = [
            'NO_CDE' => $commandeId,
            'AVNT' => str_pad($commandeAvnId, 2, ' ', STR_PAD_LEFT),
            'DTE' => date('Ymd'),
            'HEURE' => date('His'),
            'CODE' => $code,
            'UTIL' => $userCode,
            'NM_COMME' => $memoId,
            'HAPLUS' => 0x54,
        ];
        $req = 'INSERT INTO CA_EVENT('
            . implode(
                ',',
                array_merge(
                    array_keys($param),
                    ['NUM_ORD']
                )
            )
            . ') VALUES ('
            . implode(
                ',',
                array_merge(
                    array_map(function ($k) {
                        return ':' . $k;
                    }, array_keys($param)),
                    ['(SELECT COALESCE(MAX(CA_EVENT.NUM_ORD)+1, 1) 
                        FROM CA_EVENT WHERE NO_CDE=:numCde)']
                )
            )
            . ')';

        $param += [
            'numCde' => $commandeId,
        ];

        $stmt = $this->pdo->prepare($req);
        foreach ($param as $k => $v) {
            $stmt->bindValue($k, $v, is_int($v) ? \PDO::PARAM_INT : \PDO::PARAM_STR);
        }
        $stmt->execute();
    }
}
