<?php
namespace Modules\Fournisseur\Controller;

use Entity\Model\Paramnum;
use Entity\Model\Societe;
use Helpers\Ariane\ArianeSub;
use Helpers\Pagination\Paginator;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Session\Session;
use Modules\Fournisseur\Repository\Societe as SocieteRepo;
use Skeleton\Controller\Controller;

class SocieteController extends Controller
{
    public function societeAction() : string
    {
        $post = $this->request->getParsedBody();
        $id = $this->request->getAttribute('id');
        $trad = $this->getTranslationService();
        $codeDemande = $this->request->getAttribute('codeDemande');

        $value=[
            "Langue" => $_SESSION['Session_Langue'],
            "Login" => $_SESSION['Session_Login'],
            "no_ao" => $_SESSION["Session_SocUsr"],
            "codeFrs" => $id=='noId'? '':$id,
            'codeDemande' => $codeDemande,
            'affDemande' => '',
            'mode' => 'V',
        ];
        
        $xmlResult = new \Modules\Fournisseur\WebService\Fournisseur();
        $xmlResult= $xmlResult->ficheFournisseur($value);
        
        $ficheFourniss = new \SimpleXMLElement($xmlResult->responseData);

        $listeSocieteSession = [];
        foreach ($ficheFourniss->Fournisseur->ListSocietes->CODE_STE as $value) {
            if (strval($value) != '') {
                array_push($listeSocieteSession, [
                    'CODE_STE' => strval($value),
                    'libSte'   => (new Societe($this->pdo))->find(strval($value), ['RAIS_SOC'])['RAIS_SOC']??'',
                    'Etat'     => strval($value->attributes()->Etat)
                ]);
            }
        }


        if ($codeDemande) {
            ArianeSub::generate(0, 2, $trad->t('Societe'), $_SERVER['REQUEST_URI'], 1, $post);
        } else {
            ArianeSub::generate(1, 0, $trad->t('Societe'), $_SERVER['REQUEST_URI'], 1, $post);
        }

        return $this->renderer->render('@Fournisseur/societe/societe', [
            "code_fournisseur" => $id,
            "libelle_fournisseur" => $ficheFourniss->Fournisseur->Identity->RS,
            "motsClef" => true,
            "listeSociete" => $listeSocieteSession,
            'listeEtat' => ['A' => $trad->t('Nouveau'),'S' => $trad->t('Supprimer')],
            'suiviDemande' => $codeDemande? true:false,
        ]);
    }

    public function ajaxTableauSocieteAction() : string
    {
        $post = $this->request->getParsedBody();
        $type = $this->request->getAttribute('type');

        if ($type) {
            $sessionFournisseur = new Session($type);
        } else {
            $sessionFournisseur = new Session('FournisseurSimplie');
        }

        $lockModif = (($sessionFournisseur->getSessionArray('droitInteraction'))['Societe'] ?? '' )=='0'? true:false;

        return $this->renderer->render('@Fournisseur/CreationFournisseur/_bloc_societe', [
            'lockModifSociete' => $lockModif,
            'listeSociete' => $sessionFournisseur->getSession('societe'),
        ]);
    }

    public function popupAjoutSocieteAction() : string
    {
        $post = $this->request->getParsedBody();
        $div = $this->request->getAttribute('div');
        $type = $this->request->getAttribute('type');
        
        if ($type) {
            $session = new Session($type);
        } else {
            $session = new Session('Fournisseur');
        }
        $societeSession = $session->getSessionArray('societe');

        (new PaginatorGestion())->generate(8);
        $societeRepo = new SocieteRepo($this->pdo);
        $societes = $societeRepo->listeAllSociete($societeSession, $post);

        return $this->renderer->render('@Fournisseur/Societe/popup-societe', [
            'listeSociete' => $societes,
            "infoPagination" => PaginatorGestion::getInfoPagination(),
            'id' => $session->getSession('CODE'),
            'div' => $div,
            'type' => $type
        ]);
    }

    public function ajaxAjoutSocieteAction() : string
    {
        $post = $this->request->getParsedBody();

        $type = $this->request->getAttribute('type');

        
        if ($type) {
            $session = new Session($type);
        } else {
            $session = new Session('Fournisseur');
        }
        $societeSession = $session->getSessionArray('societe');
        
        $EstPresent=false;
        foreach ($societeSession as &$societe) {
            if ($societe['CODE_STE']==$post['entity']) {
                $societe['Etat']='A';
                $EstPresent=true;
                break;
            }
        }
        
        if (!$EstPresent) {
            array_push($societeSession, [
                'CODE_STE' => $post['entity'],
                'libSte'   => (new Societe($this->pdo))->find(strval($post['entity']), ['RAIS_SOC'])['RAIS_SOC']??'',
                'Etat' => 'A'
            ]);
        }

        
        $session->setSession('societe', $societeSession);
        return '';
    }

    public function ajaxSuppresionSocieteAction() : string
    {
        $post = $this->request->getParsedBody();
        $type = $this->request->getAttribute('type');

        
        if ($type) {
            $session = new Session($type);
        } else {
            $session = new Session('Fournisseur');
        }
        
        $societeSession = $session->getSessionArray('societe');
        
        for ($i=0; $i<count($societeSession); $i++) {
            if ($societeSession[$i]['CODE_STE']==$post['entity']) {
                if ($societeSession[$i]['Etat']=='A') {
                    unset($societeSession[$i]);
                } else {
                    $societeSession[$i]['Etat']='S';
                }
            }
        }
        
        $session->setSession('societe', $societeSession);
        
        if ($type) {
            return (string)json_encode(
                [
                    'path' => $this->router->generateUri('Fournisseur.societe.ajaxTableauSociete', ['type'=>$type]),
                    'pathOnlyRedirect' => false
                
                ]
            );
        }
        return '';
    }
}
