<?php

namespace Entity\Model;

use Helpers\QueryBuilder\QueryBuilder;

class DaEvent extends QueryBuilder
{
    protected string $table = 'DA_EVENT with (nolock)';
    protected string $primaryKey = '';
    protected string $libelle = '';
    public function insertEntity(
        int $purchaseRequest,
        string $code,
        string $userCode,
        string $comment = ''
    ) :void {
        $param = [
            'NO_DA'       => $purchaseRequest,
            'DTE'         => date('Ymd'),
            'HEURE'       => date('His'),
            'CODE'        => $code,
            'UTIL'        => $userCode,
            //'GERE_HAP' => ???,
            'NM_COMME'    => $comment,
        ];
        $req = 'INSERT INTO DA_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(DA_EVENT.NUM_ORD)+1, 1) 
                        FROM DA_EVENT WITH (NOLOCK) WHERE NO_DA=:prNumber)']
                )
            )
            . ')';

        $param += [
            'prNumber' => $purchaseRequest,
        ];

        $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();
    }
}
