<?php

namespace Modules\Consultation\Rules;

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

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

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

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

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

    /** @var Fourniss $fournissEntity */
    protected Fourniss $fournissEntity;

    /** @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->consultationEntity   = new AoEntet($pdo);
        $this->fournissEntity       = new Fourniss($pdo);
        $this->droits               = [
            'HA_AO_ADM' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM'),
            'HA_AO_CMV' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV')
        ];
    }

    /**
     * @return bool
     */
    public function creatEdit(): bool
    {
        $idAO           = $this->request->getAttribute('idAO');
        $consultation   = $this->consultationEntity->find($idAO);
        $canEdit        = ($this->droits['HA_AO_ADM'] || ($this->droits['HA_AO_CMV'] && $consultation['ACH'] == $_SESSION["Session_Login"])) && $consultation['DTE_VALID_AO'] == '00000000';

        if (!$canEdit) {
            return false;
        }

        return true;
    }

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

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