<?php

namespace Modules\Commande\Rules;

use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Modules\DemandeAchat\Repository\DemandeAchat;
use Psr\Http\Message\ServerRequestInterface;

class CreationCommande
{
    protected ServerRequestInterface $request;
    protected \PDO $pdo;
        
    /**
     * __construct
     *
     * @param  ServerRequestInterface $request
     * @return void
     */
    public function __construct(ServerRequestInterface  $request, \PDO $pdo)
    {
        $this->request  = $request;
        $this->pdo      = $pdo;
    }
    
    /**
     * init
     *
     * @return bool
     */
    public function init() : bool
    {
        if (Roles::droitsUtilisateur($this->pdo, 'HA_CA_CMV')) {
            return true;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function creation()
    {
        $type = $this->request->getAttribute('typeCde') ?? null;
        $id = $this->request->getAttribute('numType') ?? null;

        if ($type === 'DA') {
            $repo = new DemandeAchat($this->pdo);
            $da = $repo->demandeAchatEntete($id);

            if (!($da['CHIF_EXEC'] == 'E' && !Sql::toBool($da['TRAITEE']))) {
                return false;
            }
        }

        return true;
    }


    /**
     * @return bool
     */
    public function validation(): bool
    {
        return true;
    }
}
