<?php

namespace Modules\ProjetAchat\Rules;

use Entity\Model\AoEntet;
use Entity\Model\Doa;
use Entity\Model\Fourniss;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Psr\Http\Message\ServerRequestInterface;

class GestionProjetAchat
{
    /** @var ServerRequestInterface $request */
    protected ServerRequestInterface $request;

    /** @var \PDO $pdo */
    protected \PDO $pdo;

    /** @var string|mixed $currentUser */
    protected $currentUser;

    /** @var AoEntet $consultationEntity */
    protected Doa $doaEntity;

    /** @var array<mixed> $droits */
    protected array $droits;

    public function __construct(ServerRequestInterface $request, \PDO $pdo)
    {
        $this->request              = $request;
        $this->pdo                  = $pdo;
        $this->currentUser          = $_SESSION['Session_Login'];
        $this->doaEntity            = new Doa($pdo);
        $this->droits               = [
            'DOA_DOA_CM' => Roles::droitsUtilisateur($this->pdo, 'DOA_DOA_CM'),
            'DOA_DOA_TT' => Roles::droitsUtilisateur($this->pdo, 'DOA_DOA_TT')
        ];
    }

    /**
     * @return bool
     */
    public function popupTransfere(): bool
    {
        $projetAchatId  = $this->request->getAttribute('idProjetAchat');
        $typeObjet      = $this->request->getAttribute('typeObjet');

        $pa = $this->doaEntity->find($projetAchatId, [], [], $this->pdo::FETCH_ASSOC);
        if (($pa['STATUT'] !== 'I' && $pa['STATUT'] !== 'P') &&
            $typeObjet !== 'D' && Sql::toBool($pa['SUSPENDU'])
        ) {
            return false;
        }

        return true;
    }

    /**
     * @return bool
     */
    public function ajaxTransmettre(): bool
    {
        return $this->popupTransfere();
    }

    /**
     * @return bool
     */
    public function devalider(): bool
    {
        $projetAchatId  = $this->request->getAttribute('idProjetAchat');
        $typeObjet      = $this->request->getAttribute('typeObjet');

        $pa = $this->doaEntity->find($projetAchatId, [], [], $this->pdo::FETCH_ASSOC);

        if ($pa['STATUT'] !== 'E' &&
            ((!$this->droits['DOA_DOA_CM'] && $pa['PROPRIETAIRE'] !== $this->currentUser) || !$this->droits['DOA_DOA_TT']) &&
            $pa['ActionTerminer'] !== 0 && $pa['donneeSaisie'] !== 0
        ) {
            return false;
        }

        return true;
    }
}
