<?php

namespace Modules\Stock\Validator;

use Entity\Model\Paravrac;
use Exception;
use Helpers\Trad\ITrad;
use Helpers\Validator\Validator;
use Modules\Ajax\Repository\Listes;
use Modules\Stock\Enum\CodeParametreVracEnum;
use Modules\Stock\Enum\SoldeDemandeServiceEnum;
use Modules\Stock\Enum\TypeParametreVracEnum;
use Modules\Stock\Repository\BonTransfertRepo;
use Modules\Stock\Service\ParametrageService;
use Modules\Stock\Trait\Validator\BonValidatorTrait;
use Modules\Stock\Trait\Validator\EnteteValidatorTrait;
use Modules\Stock\Trait\Validator\ValidatorTrait;
use PDO;
use Helpers\Outil\Sql;

class BonTransfertValidator extends Validator
{
    use ValidatorTrait;
    use BonValidatorTrait;
    use EnteteValidatorTrait;

    /** @phpstan-ignore-next-line */
    private readonly Listes $listes;
    /** @phpstan-ignore-next-line */
    private readonly BonTransfertRepo $enteteRepo;
    /** @phpstan-ignore-next-line */
    private readonly Paravrac $paravrac;

    public function __construct(PDO $pdo, ITrad $trad)
    {
        parent::__construct($pdo, $trad);
        $this->listes = new Listes($pdo);
        $this->enteteRepo = new BonTransfertRepo($pdo);
        $this->paravrac = new Paravrac($pdo);
    }

    /**
     * @param array<string,mixed> $bonTransfert
     * @return self
     */
    public function validateNoDs(array $bonTransfert): self
    {
        if ($bonTransfert['NO_DS'] === "") {
            return $this;
        }

        $this->zoom(
            'SdsEnte',
            $bonTransfert['NO_DS'],
            $this->trad->t('N° DS'),
            $this->pdo,
            false,
            [
                'filter_egal_NO_DS' => $bonTransfert['NO_DS'],
                'filter_egal_SOLDE_DS' => SoldeDemandeServiceEnum::E->name,
                'filter_egal_SITE' => $bonTransfert['SITE'],
            ]
        );

        return $this;
    }

    /**
     * @param array<string,mixed> $bonTransfert
     * @return $this
     * @throws Exception
     */
    public function validateSiteDestinataire(array $bonTransfert): self
    {
        $parameters = [
            'opened_only' => 'true',
            'site_origine' => $bonTransfert['SITE'],
            'filter_egal_SSITESTO#point#SITE' => $bonTransfert['SITE_DEST'],
            'is_bon_transfert_multisociete' => (new ParametrageService($this->pdo))->isBonTransfertMultisociete() ? 'true' : 'false'
        ];

        $this->isObligatoire($bonTransfert['SITE_DEST'], $this->trad->t('Site destinataire'));
        if (empty((new Listes($this->pdo))->listSitesStockAccessibles($parameters, false))) {
            $this->setError($this->trad->t('Le code saisi ' . $bonTransfert['SITE_DEST'] . 'n \'est pas présent
            dans la liste des sites'));
        }

        if ($bonTransfert['SITE'] === $bonTransfert['SITE_DEST']) {
            $this->setError($this->trad->t('Le site d\'origine et le site destinataire doivent être différents'));
        }

        return $this;
    }
}
