<?php

namespace Modules\Additional\Specifique\Client92\Modules\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Fichier\Fichier;
use Helpers\Pagination\Paginator;
use Helpers\Parametres\Constante;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Additional\Specifique\Client92\Modules\Outil\Budget;
use Modules\Additional\Specifique\Client92\Modules\Repository\ImportBudget;
use Skeleton\Controller\Controller;
use Entity\Model\Hastutil;
use Entity\Model\Periodes;
use Entity\Model\Societe;
use Helpers\Outil\Roles;
use Modules\Ajax\Repository\Listes;

class ConsultationBudgetController extends Controller
{
    public function listeBudgetAction()
    {
        $post = $this->request->getParsedBody();

        $periode = new Periodes($this->pdo);
        $currentPeriode = $periode->find(['DATE_DEB' => date('Y').'0101']);

        if (!$post) {
            $post['tri_CODE_STE'] = 'asc';
            $post['tri_CODE_PER'] = 'desc';
            $post['tri_CENTRE_COUT'] = 'asc';

            $post['filter_egal_CODE_PER'] = $currentPeriode['CODE_PER'];
        }

        $trad = $this->getTranslationService();

        $importBudget = new ImportBudget($this->pdo);
        $listeBudget = $importBudget->getListeConsomation($post);
        $societe = new Societe($this->pdo);

        foreach ($listeBudget as &$buget) {
            $buget['DEVISE']           = $societe->find($buget['CODE_STE'], ['DEVISE'])['DEVISE'];

            $buget['TOTAL']             = ((float) $buget['MNT_CONS_CA']) + ((float) $buget['MNT_CONS_BR']) + ((float) $buget['MNT_CONS_FA']);
            $buget['DISPO']             = (float) $buget['MNT_BUDGET'] - (float) $buget['TOTAL'];
        }
        
        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($listeBudget, 0, $post, $this->renderer);

        Ariane::generate(0, $trad->t('Consultation budgétaire'));
        
        return $this->renderer->render('@Specifique92/Modules/views/Budget/listeBudget', [
            'menuActive'        => 'Specifique',
            'menuLeft'          => 'consultation',
            'listeBudget'       => $listeBudget,
            'droitEdit'         => Roles::droitsUtilisateur($this->pdo, 'SpeABUDGET', $_SESSION["Session_Login"]),
            'post'              => $post,
            'infoPagination'    => $infopagination,
            'user'              => $_SESSION["Session_Login"],
        ]);
    }


    public function ajaxDetailBudgetAction()
    {
        $codeSte        = $this->request->getAttribute('codeSte');
        $periode        = $this->request->getAttribute('periode');
        $centreCout     = $this->request->getAttribute('centreCout');
        $ordreInterne   = $this->request->getAttribute('ordreInterne');
        $domaneActiv    = $this->request->getAttribute('domaneActiv');
        $pays           = $this->request->getAttribute('pays');
        $gamme          = $this->request->getAttribute('gamme');

        $importBudget = new ImportBudget($this->pdo);
        $listeBudget = $importBudget->getDetailBudget($codeSte, $periode, $centreCout, $ordreInterne, $domaneActiv, $pays, $gamme);

        return $this->renderer->render('@Specifique92/Modules/views/Budget/ajaxDetailBudget', [
            'listeBudget' => $listeBudget,
        ]);
    }

    public function ajaxUpdateBudgetAction()
    {
        $post = $this->request->getParsedBody();

        $explode = explode(Constante::spliter, $post['chps']);

        $post['value'] = str_replace(' ', '', $post['value']);

        $arrayFinal = [
            'CODE_STE'          => $explode[1],
            'CODE_PER'          => $explode[2],

            'CENTRE_COUT'       => $explode[3],
            'ORDRE_INTERNE'     => $explode[4],
            'DOMANE_ACTIVITE'   => $explode[5],
            'PAYS_LIVRE'        => $explode[6],
            'GAMME'             => $explode[7],
            'MNT_BUDGET'        => $post['value'],
        ];

        $importBudget = new ImportBudget($this->pdo);
        $importBudget->updateLigneBudget($arrayFinal);


        return new response(200);
    }

    public function deleteBudgetAction()
    {
        $codeSte        = $this->request->getAttribute('codeSte');
        $periode        = $this->request->getAttribute('periode');
        $centreCout     = $this->request->getAttribute('centreCout');
        $ordreInterne   = $this->request->getAttribute('ordreInterne');
        $domaneActiv    = $this->request->getAttribute('domaneActiv');
        $pays           = $this->request->getAttribute('pays');
        $gamme          = $this->request->getAttribute('gamme');

        $arrayFinal = [
            'CODE_STE'          => $codeSte,
            'CODE_PER'          => $periode,

            'CENTRE_COUT'       => $centreCout,
            'ORDRE_INTERNE'     => $ordreInterne,
            'DOMANE_ACTIVITE'   => $domaneActiv,
            'PAYS_LIVRE'        => $pays,
            'GAMME'             => $gamme,
        ];

        $importBudget = new ImportBudget($this->pdo);
        $importBudget->deleteLigneBudget($arrayFinal);

        return new response(200);
    }

    public function addLigneBudgetAction()
    {

        $trad = $this->getTranslationService();

        Ariane::generate(1, $trad->t('Ajout ligne budgétaire'));
        
        return $this->renderer->render('@Specifique92/Modules/views/Budget/addBudget', [
            'menuActive'        => 'Specifique',
            'menuLeft'          => 'consultation',
        ]);
    }

    public function ajaxLigneBudgetAction()
    {
        
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $validator = $this->createValidator();

        //todo add controle unicité
        $validator->zoom('Societe', $post['SOCIETE'], $trad->t('Société'), $this->pdo, false);
        $validator->zoom('Periodes', $post['PERIODE'], $trad->t('Période'), $this->pdo, false);
        $validator->zoom('Sectimpu', $post['CENTRE_COUT'], $trad->t('Section d\'imputation'), $this->pdo, false, ['filter_egal_CODE_STE' => $post['SOCIETE']]);
        $validator->zoom('Codecomp', $post['ORDRE_INTERNE'], $trad->t('Code complémentaire'), $this->pdo, false, ['filter_egal_CODE_STE' => $post['SOCIETE']]);
        $validator->zoom('Sscptana', $post['DOMANE_ACTIVITE'], $trad->t('Sous-compte d\'analyse'), $this->pdo, false, ['filter_egal_CODE_STE' => $post['SOCIETE']]);
        $validator->zoom('Pays', $post['PAYS_LIVRE'], $trad->t('Pays livré'), $this->pdo, false);
        $validator->validatorTSDON($trad->t('Gamme'), $post['GAMME'], 'GAMME', $this->pdo, false, $post['SOCIETE']);
        $validator->isFloat($trad->t('Montant budget'), $post['MNT_BUDGET'], constante::formatMontant);
        $validator->zoom('Hastutil', $post['RESPONSABLE'], $trad->t('Responsable'), $this->pdo, false);
        
        if ($validator->isValid()) {
            $post['CODE_STE'] = $post['SOCIETE'];
            $post['CODE_PER'] = $post['PERIODE'];

            $importBudget = new ImportBudget($this->pdo);
            $importBudget->insertLigneBudget($post);

            return new Response(443, [

            ], (string) \json_encode([
                'statut' => 'O',
                'path' => $this->router->generateUri('Specifique92.ConsultationBudget.listeBudget'),
            ]));
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]);
        }
    }

    public function ajaxUpdateSocieteAction()
    {
        $post = $this->request->getParsedBody();

        $socEntity = new Societe($this->pdo);
        $societe = $socEntity->find($post['codeSte']);

        if ($societe) {
            return $societe['DEVISE'];
        } else {
            return $_SESSION['parametrage']['DEVISE_BASE'];
        }
    }

    public function exportConsoBudgetAction()
    {
        $post = $this->request->getParsedBody();
        $outilBudget = new Budget($this->pdo, $this->getTranslationService());
        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_consomation_budgetaire'.random_int(0, 999999999),
            $outilBudget->exportBudget($_SESSION["Session_Login"], $post),
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $outilBudget->getExportCol()
        );
        return 'ok';
    }
}
