<?php

namespace Modules\Contrat\Controller;

use Entity\Model\Marches;
use Skeleton\Controller\Controller;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Modules\Contrat\Repository\Societe;
use Helpers\Fichier\Fichier;
use Helpers\Parametres\Constante;

class SocieteController extends Controller
{

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

        //$accEntity       = new \Entity\Model\Acccadre($this->pdo);
        $societe = new \Modules\Contrat\Repository\Societe($this->pdo);
        $marches = new Marches($this->pdo);

        if ($_SESSION['Session_UsrMultiSoc'] == 1 || $_SESSION['Session_UsrPluriSoc'] != '') {
            $societes = $societe->detailSociete($id, $post);
        } else {
            $societes = $societe->listeSocieteByCodeUser($id);
        }

        $trad = $this->getTranslationService();
        $marcheTitre = $marches->find(['CODE' => $id]);

        $paginator      = new \Helpers\Pagination\Paginator();
        $infoPagination = $paginator->generate($societes, 0, $post);

        $listeTypeCtrl =
            [
                ' ' => $trad->t('Pas de contrôle'),
                'B' => $trad->t('Bloquant'),
                'N' => $trad->t('Non Bloquant')
            ];

        $listeAutorise = array(
            '' => '',
            "Oui" => $trad->t("Oui"),
            "Non" => $trad->t("Non"),
        );

        \Helpers\Ariane\Ariane::generate(2, $trad->t('Sociétés Autorisées'), $post);

        return $this->renderer->render('@Contrat/societe/societes', [
            'listeAutorise'  => $listeAutorise,
            'societes'       => $societes,
            'idMarche'       => $id,
            
            'marchTitre'     => $marcheTitre,
            'infoPagination' => $infoPagination,
            'menuActive'     => 'Contrats',
            'menuLeft'       => 'Contrat.marche.index',
            'marche'         => $id,
            'listeTypeCtrl'  => $listeTypeCtrl,
            'post'           => $post

        ]);
    }
    public function modifierSocieteAction()
    {
        $post = $this->request->getParsedBody();
        $codemarche = $this->request->getAttribute('codemarch');
        $codeste = $this->request->getAttribute('codeste');
        $validator = $this->createValidator();
        $trad = $this->getTranslationService();
        $listeTypeCtrl = [
            ' ' => $trad->t('Pas de contrôle'),
            'B' => 'B',
            'N' => 'N'
        ];

        if (isset($post['autorise'])) {
            $validator = $this->createValidator();
            $validator->isFloat($trad->t('Montant Mini'), $post['MNTPREMIN'], Constante::formatMontant);
            $validator->isFloat($trad->t('Montant Maxi'), $post['MNTPREMAX'], Constante::formatMontant);
            $societe = new \Modules\Contrat\Repository\Societe($this->pdo);

            $devise = $societe->deviseParam();

            if ($validator->getError() != '') {
                return new Response(200, [], substr(str_replace('<br />', '<br /><img src="' . $this->contenaire->get('baseUrl') . 'IconeV2/Gestion/Error.svg"/>', $validator->getError()), 6));
            }
            $societeModifier = new \Entity\Model\Marchsoc($this->pdo);

            if (!$post['autorise'] || ($codeste == '' && $codemarche == '')) {
                $deleteMarchSoc = [
                        'CODEMARCH' => trim($codemarche),
                        'CODESOC' => trim($codeste),
                    ];
                $societeModifier->delete($deleteMarchSoc);
                //On revoie une reponse pour que la popup se ferme
                return new Response(200, [], '');
            } else {
                $myarray = ['CODEMARCH' => $codemarche, 'CODESOC' => $codeste];
                $isExist = $societeModifier->find($myarray);

                if ($isExist) {
                    $modifier = [
                        'MNTPREMIN' => $post['MNTPREMIN'],
                        'MNTPREMAX' => $post['MNTPREMAX'],
                        'TYPCTRBUD' => $post['typecontrole']
                    ];

                    $codemarche = [
                        'CODEMARCH' => $codemarche,
                        'CODESOC' => $codeste
                    ];

                    $societeModifier = $societeModifier->update($modifier, $codemarche);

                    return new Response(200, [], '');
                } else {
                    $societeModifier = new \Entity\Model\Marchsoc($this->pdo);

                    $insert = [
                            'CODEMARCH' => $codemarche,
                            'CODESOC'   => $codeste,
                            'MNTPREMIN' => $post['MNTPREMIN'],
                            'MNTPREMAX' => $post['MNTPREMAX'],
                            'CUMULCDE'  => 0,
                            'TYPCTRBUD' => $post['typecontrole']
                        ];

                    $societeModifier->insert($insert);

                    return new Response(200, [], '');
                }
            }
        } else {
            $societe = new \Modules\Contrat\Repository\Societe($this->pdo);
            $devise = $societe->deviseParam();

            $societeindex = $societe->detailSocieteModification($codemarche, $codeste);
        }


        return $this->renderer->render('@Contrat/societe/popup-societes-autorisees', [
            'listeTypeCtrl' => $listeTypeCtrl,
            
            'societes'      => $societeindex,
            'marche'        => $codemarche,
            'devise'        => $devise,
            'codeste'       => $codeste,
            'post'          => $post,
        ]);
    }
    public function exportSocieteAction(): string
    {
        $code = $this->request->getAttribute('id');

        $bdd = new Societe($this->pdo);
        $listeBdd = $bdd->detailSociete($code, $_SESSION['ariane'][2]['post']);

        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_bdd_',
            $listeBdd,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService()
        );

        return 'ok';
    }
}
