<?php

namespace Modules\Panier\Validator;

use Entity\Model\OxaUserPanierImputation;
use Entity\Model\Paravrac;
use Entity\Model\TypeAchat;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Panier\Repository\PanierEntete;
use Modules\Panier\Repository\ValidationPanierRepository;
use Modules\Panier\Service\OutilPanierService;
use Modules\Panier\Service\PanierFrsService;
use Modules\RechercheArticles\Service\OutilRechercheService;
use SimpleXMLElement;
use Skeleton\Pdo\DbStatement;

class SoumisionFinalValidator extends Validator
{
    private SimpleXMLElement $xml;
    private mixed $listeDA;
    private mixed $listeCDE;
    private mixed $listeSTOCK;

    public function __construct(\PDO $pdo, ITrad $trad)
    {
        $this->pdo = $pdo;
        $this->trad = $trad;

        $xmlName = $_SESSION['panier']['XML'];
        $xmlContent = Fichier::getContentFile($xmlName);
        $this->xml = new SimpleXMLElement((string)$xmlContent);

        $this->listeDA      = $this->xml->DA;
        $this->listeCDE     = $this->xml->ListCdes->Cde;
        $this->listeSTOCK   = $this->xml->Stock;
    }

    public function controleSignataire():void
    {
        foreach ($this->listeDA as $doc) {
            $this->controle($doc, $this->trad->t('Demande d\'achat'));
        }
        
        $compter = 1;
        foreach ($this->listeCDE as $doc) {
            $this->controle($doc, trad::strBuild($this->trad->t('Commande N°@1@'), $compter));
            $compter++;
        }

        foreach ($this->listeSTOCK as $doc) {
            $this->controle($doc, $this->trad->t('Demande de stock'));
        }
    }

    /**
     * @param mixed $xml
     * @param string $document
     * @return void
     */
    private function controle($xml, $document):void
    {
        $signataire = false;

        if ($xml->ListSignataire->AlgoSpecif === null) {
            $signataire = true;
        }

        $algo = explode('|', $xml->ListSignataire->AlgoSpecif);
        foreach ($algo as $k) {
            $explode = explode(';', $k);
            if ($explode[5] == 'N') {
                $signataire = true;
                break;
            }
        }

        if (!$signataire) {
            $this->setError(trad::strBuild($this->trad->t('Il doit y avoir au moins un signataire pour le document @1@.'), $document));
        }
    }
}
