<?php

namespace Modules\Contrat\Controller;

use Entity\Model\Acccadre;
use Entity\Model\AcdRFA;
use Entity\Model\AcdRFALig;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Date;
use Helpers\Outil\Sql;
use Helpers\Pagination\PaginatorGestion;
use Modules\Contrat\Enum\BaseCalculEnum;
use Modules\Contrat\Enum\TypeRFAEnum;
use Modules\Contrat\MenuContextuel\RFAContextuel;
use Modules\Contrat\Repository\RFARepository;
use Modules\Contrat\Validator\RFAValidator;
use Skeleton\Controller\Controller;

class RFAController extends Controller
{
    public function listeAction():string
    {
        $idAcd = $this->request->getAttribute('idacc');
        $type = $this->request->getAttribute('type');
        $trad = $this->getTranslationService();
        $post = $this->request->getParsedBody();

        
        (new PaginatorGestion())->generate(0, 'ACD_RFA.DTE_DEBUT');
        $listeRFA = (new RFARepository($this->pdo))->getListe($idAcd, $post);
        $nombreArticle  = PaginatorGestion::getNbrArticle();
        $infopagination = PaginatorGestion::getInfoPagination();
        Ariane::generate($type == 'ALL'? 1:2, $trad->t('Liste RFA'), $post, $nombreArticle);
        
        $menuContextuel = (new RFAContextuel($this->pdo, $this->router, $trad));

        foreach ($listeRFA as &$rfa) {
            $rfa['menuContextuel'] = $menuContextuel->generate($rfa, $type, $idAcd);
        }

        return $this->renderer->render('@Contrat/RFA/liste', [
            'acd' => (new Acccadre($this->pdo))->find($idAcd, ['CODE_ACD', 'LIBELLE','AVENANT']),
            'listeRFA' => $listeRFA,
            'post' => $post,
            'infoPagination'        => $infopagination,

            'idacc' => $idAcd,
            'type'  => $type,
            
            'droit' => [
                'HA_ACD_CM'     => \Helpers\Outil\Roles::droitsUtilisateur($this->pdo, 'HA_ACD_CM'),
                'HA_ACD_ADM'    => \Helpers\Outil\Roles::droitsUtilisateur($this->pdo, 'HA_ACD_ADM'),
            ],

            'typeRFA' => [...TypeRFAEnum::getAsAssoc($trad)],
            'baseCalcul' => [...BaseCalculEnum::getAsAssoc($trad)],
            'ouiNon' => ['T' => $trad->t('Oui'), 'F' => $trad->t('Non')],
            'devise' => $_SESSION['parametrage']['DEVISE_BASE'],
        ]);
    }

    public function createEditAction():string
    {
        $idAcd = $this->request->getAttribute('idacc');
        $idRFA = $this->request->getAttribute('idRFA');
        $type = $this->request->getAttribute('type');
        $trad = $this->getTranslationService();

        if ($idRFA) {
            $rfa = (new RFARepository($this->pdo))->getRFA($idRFA);
        }

        Ariane::generate($type == 'ALL'? 2:3, $idRFA? $trad->t('Modification RFA'):$trad->t('Création RFA'));

        return $this->renderer->render('@Contrat/RFA/createEdit', [
            'acd' => (new Acccadre($this->pdo))->find($idAcd, ['CODE_ACD', 'LIBELLE','AVENANT']),
            'typeRFA' => [...TypeRFAEnum::getAsAssoc($trad)],
            'baseCalcul' => [...BaseCalculEnum::getAsAssoc($trad)],
            'devise' => $_SESSION['parametrage']['DEVISE_BASE'],
            'rfa' => $rfa??[],

            'idacc' => $idAcd,
            'type'  => $type,
            'idRFA' => $idRFA,
        ]);
    }

    public function validateAction():Response
    {
        $idAcd = $this->request->getAttribute('idacc');
        $idRFA = $this->request->getAttribute('idRFA');
        $post = $this->request->getParsedBody();

        $validator = (new RFAValidator($this->pdo, $this->getTranslationService(), $this->contenaire));
        $validator->entete($post);

        if ($validator->isValid()) {
            if ($idRFA) {
                (new AcdRFA($this->pdo))->update([
                    'CODE_ACD'      => $idAcd,
                    'LIBELLE'       => $post['LIBELLE'],
                    'DTE_DEBUT'     => $post['DTE_DEBUT'],
                    'DTE_FIN'       => $post['DTE_FIN'],
                    'BASE_CALCUL'   => $post['BASE_CALCUL'],
                    'TACITE_RECOND' => Sql::toBool($post['TACITE_RECOND']),
                    'SOLDE'         => Sql::toBool($post['SOLDE']),
                    'COMMENTAIRE'   => $post['COMMENTAIRE']
                ], [
                    'CODE_ACD'      => $idAcd,
                    'RFA_ID'        => $idRFA,
                ]);

                (new AcdRFALig($this->pdo))->update([
                    'TYPE_RFA'      => $post['TYPE_RFA'],
                    'VALEUR_RFA'    => $post['VALEUR_RFA']
                ], [
                    'CODE_ACD'      => $idAcd,
                    'RFA_ID'        => $idRFA,
                ]);
            } else {
                $acdRFA = new AcdRFA($this->pdo);
                $maxID = $acdRFA->getMaxOrdre(null, 'RFA_ID');
                $maxID = (int)$maxID+1;
                $acdRFA->insert([
                    'CODE_ACD'      => $idAcd,
                    'RFA_ID'        => $maxID,
                    'LIBELLE'       => $post['LIBELLE'],
                    'DTE_DEBUT'     => $post['DTE_DEBUT'],
                    'DTE_FIN'       => $post['DTE_FIN'],
                    'BASE_CALCUL'   => $post['BASE_CALCUL'],
                    'TACITE_RECOND' => Sql::toBool($post['TACITE_RECOND']),
                    'SOLDE'         => Sql::toBool($post['SOLDE']),
                    'COMMENTAIRE'   => $post['COMMENTAIRE']
                ]);

                $acdRafLig = new AcdRFALig($this->pdo);
                $acdRafLig->insert([
                    'CODE_ACD'      => $idAcd,
                    'RFA_ID'        => $maxID,
                    'TYPE_RFA'      => $post['TYPE_RFA'],
                    'VALEUR_RFA'    => $post['VALEUR_RFA']
                ]);
            }

            return new Response(443, [], (string) json_encode([
                'path' => Ariane::getBackPath(),
                'post' => Ariane::getBackPost(),
            ]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }

    public function deleteAction():Response
    {
        $idAcd = $this->request->getAttribute('idacc');
        $idRFA = $this->request->getAttribute('idRFA');

        (new AcdRFA($this->pdo))->delete([
            'CODE_ACD'      => $idAcd,
            'RFA_ID'        => $idRFA,
        ]);

        (new AcdRFALig($this->pdo))->delete([
            'CODE_ACD'      => $idAcd,
            'RFA_ID'        => $idRFA,
        ]);

        return new Response(200);
    }

    public function exportAction():string
    {
        $idacc = $this->request->getAttribute('idacc');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $this->getEmailCsvService()->sendCsv(
            'export__' . date('Ymd'),
            (new RFARepository($this->pdo))->getListe($idacc, $post),
            function (array $row) {
                $trad = $this->getTranslationService();
                return [
                    $row['CODE_ACD'],
                    $row['RFA_ID'],
                    $row['LIBELLE'],
                    Date::dateConverte($row['DTE_DEBUT']),
                    Date::dateConverte($row['DTE_FIN']),
                    $row['BASE_CALCUL'],
                    (Sql::boolSql($row['TACITE_RECOND'])? $trad->t('Oui'):$trad->t('Non')),
                    (Sql::boolSql($row['SOLDE'])? $trad->t('Oui'):$trad->t('Non')),
                    $row['COMMENTAIRE'],
                    $row['TYPE_RFA'],
                    $row['VALEUR_RFA'],
                ];
            },
            [
                $trad->t('Code accord-cadre'),
                $trad->t('ID RFA'),
                $trad->t('Libelle'),
                $trad->t('Date de début'),
                $trad->t('Date de fin'),
                $trad->t('Base calcul'),
                $trad->t('Tacite reconduction'),
                $trad->t('Soldée ?'),
                $trad->t('Commentaire'),
                $trad->t('Type RFA'),
                $trad->t('Valeur'),
            ]
        );
        return 'ok';
    }
}
