<?php

namespace Modules\Additional\Specifique\Client155\Modules\Fournisseur\Controller;

use Entity\Model\Fourniss;
use Entity\Model\StePeri;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Ariane\ArianeSub;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Outils;
use Helpers\Outil\Roles;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Additional\Specifique\Client155\Modules\Fournisseur\Outil\ImportReporting;
use Modules\Additional\Specifique\Client155\Modules\Fournisseur\Outil\SysuFouReportingValidator;
use Modules\Additional\Specifique\Client155\Modules\Fournisseur\Repository\SysuFourReportPerf;
use Skeleton\Controller\Controller;
use Tamtamchik\SimpleFlash\Flash;
use Helpers\Parametres\Constante;
use Modules\Additional\Specifique\Client155\Modules\Fournisseur\MenuContextuel\ImportMenuContextuel;

class ReportingPerformanceController extends Controller
{
    /**
     * @return string
     */
    // TODO: Créer un helper pour créer des TABLES
    public function indexAction(): string
    {
        $post = $this->request->getParsedBody();
        $id = $this->request->getAttribute('id');

        $fournis = new Fourniss($this->pdo);
        $fournis = $fournis->find($id);

        $repository = new SysuFourReportPerf($this->pdo);

        if (!isset($post['filter_CODE_PERIODE'])) {
            $currentYear = (new \DateTime('now'))->format('Y');
            $post['filter_CODE_PERIODE'] = $currentYear;
        }
        $trad = $this->getTranslationService();

        $paginator = new \Helpers\Pagination\PaginatorGestion();
        $paginator->generate(20, 'DATE_APPLICATION');

        $reportingPerformance = $repository->find($id, $post);
        $infoPagination = PaginatorGestion::getInfoPagination();

        $menuContextuel = new ImportMenuContextuel($this->pdo, $this->router, $this->getTranslationService(), []);
        foreach ($reportingPerformance as &$report) {
            $report['menuContextuel'] = $menuContextuel->generate($report, $id);
        }

        ArianeSub::generate(1, 0, $trad->t('Reporting performance'), $_SERVER['REQUEST_URI'], 1, $post);

        $flash = new Flash();

        return $this->renderer->render('@Specifique155.Fournisseur/reporting/index', [
            'menuActive'                => 'Fournisseur',
            'menuLeft'                  => 'GestionFournisseur',
            'id'                        => $id,
            'fournisseur'               => $fournis,
            "code_fournisseur"          => $id,
            "libelle_fournisseur"       => $fournis["RS"],
            "listeReportingPerformances"=> $reportingPerformance,
            'infoPagination'            => $infoPagination,
            'post'                      => $post,
            'path'                      => $this->router->generateUri('Specifique155.reportingPerformance.index', ['id' => $id]),
            'flash'                     => $flash,
            'droitMod'                  => Roles::droitsUtilisateur($this->pdo, 'HA_FOU_MOD'),
            'hasDroitFouAdmn' => Roles::droitsUtilisateur($this->pdo, 'SpeSYSU001'),
            'devise'                    => $_SESSION['parametrage']['DEVISE_BASE']
        ]);
    }

    /**
     * @return string
     */
    public function newReportAction(): string
    {
        $post           = $this->request->getParsedBody();
        $id             = $this->request->getAttribute('id');
        $trad = $this->getTranslationService();

        $fournis        = new Fourniss($this->pdo);
        $fournis        = $fournis->find($id);

        $repository     = new SysuFourReportPerf($this->pdo);

        ArianeSub::generate(2, 0, $trad->t('Création reporting performance'), $_SERVER['REQUEST_URI'], 1);

        $urlValidForm = $this->router->generateUri('Specifique155.reportingPerformance.createReport', [
            'id' => $id,
            'action' => 'creation',
        ]);

        return $this->renderer->render('@Specifique155.Fournisseur/reporting/creation', [
            'menuActive' => 'Fournisseur',
            'menuLeft' => 'GestionFournisseur',
            'id' => $id,
            'fournisseur' => $fournis,
            "code_fournisseur" => $id,
            "libelle_fournisseur" => $fournis["RS"],
            'canalList' => $repository->getArrayAssocListeCanal(),
            'action' => 'creation',
            'post' => $post,
            'urlValidForm' => $urlValidForm,
            'hasDroitFouAdmn' => Roles::droitsUtilisateur($this->pdo, 'SpeSYSU001'),
        ]);
    }

    /**
     * @return Response|string
     */
    public function editReportAction()
    {
        $post       = $this->request->getParsedBody();
        $id         = $this->request->getAttribute('id');
        $periode    = $this->request->getAttribute('periode');
        $ssf        = $this->request->getAttribute('ssf');

        $fournis = new Fourniss($this->pdo);
        $fournis = $fournis->find($id);

        $trad = $this->getTranslationService();


        ArianeSub::generate(2, 0, $trad->t('Modification reporting performance'), $_SERVER['REQUEST_URI'], 1);

        $repository = new SysuFourReportPerf($this->pdo);

        $reportPerf = $repository->checkExist($id, $periode, $ssf);
        if (count($reportPerf) > 0) {
            $urlValidForm = $this->router->generateUri('Specifique155.reportingPerformance.createReport', [
                'id' => $id,
                'action' => 'modification',
                'periode' => $periode,
                'ssf' => $ssf,
            ]);

            return $this->renderer->render('@Specifique155.Fournisseur/reporting/creation', [
                'menuActive' => 'Fournisseur',
                'menuLeft' => 'GestionFournisseur',
                'id' => $id,
                'fournisseur' => $fournis,
                "code_fournisseur" => $id,
                "libelle_fournisseur" => $fournis["RS"],
                'canalList' => $repository->getArrayAssocListeCanal(),
                'action' => 'modification',
                'post' => $post,
                'report' => $reportPerf,
                'urlValidForm' => $urlValidForm,
                'hasDroitFouAdmn' => Roles::droitsUtilisateur($this->pdo, 'SpeSYSU001'),
            ]);
        }

        return $this->redirect($this->router->generateUri('Specifique155.reportingPerformance.index', ['id' => $id]));
    }

    /**
     * @return Response
     */
    public function createReportAction()
    {
        $post   = $this->request->getParsedBody();
        $action = $this->request->getAttribute('action');
        $id     = $this->request->getAttribute('id');
        $ssf    = $this->request->getAttribute('ssf');
        $periode = $this->request->getAttribute('periode');
        $trad = $this->getTranslationService();


        //_________________

        $qb = new SysuFourReportPerf($this->pdo);
        $validator = new SysuFouReportingValidator(
            $this->getPdo(),
            $this->getTranslationService()
        );
        $validator->validateReport($post);
        if ($action == 'modification') {
            $exists = $qb->checkExist($id, $periode, $ssf);
        } else {
            $exists = $qb->checkExist($id, $post['CODE_PERIODE'], $post['CODE_SOUS_FAMILLE']);
        }

        if (count($exists) > 0 && $action == 'creation') {
            $validator->setError($trad->t('Le reporting performance existe déjà pour ce fournisseur avec la période et la sous famille'));
        }

        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        //_____________________

        // Droit FOUR ADMIN required
        if (! Roles::droitsUtilisateur($this->pdo, 'SpeSYSU001')) {
            unset($post['OBJECTIF_NE']);
            unset($post['OBJECTIF_NE_PERCENT']);
            unset($post['MONTANT_CA_PREVI']);
        }
        $entity = array_intersect_key(
            $post,
            array_flip($qb->listColumn())
        );
        $entity['CODE_FOURNISSEUR'] = $id;
        if ($action == 'modification' && count($exists) > 0) {
            $qb->update([
                'CODE_FOURNISSEUR' => $id,
                'CODE_PERIODE' => $periode,
                'CODE_SOUS_FAMILLE' => $ssf,
            ], $entity);
        } else {
            $qb->insert($entity);
        }

        return $this->createJsonResponse([
            'droit_validation' => Roles::droitsUtilisateur($this->pdo, 'HA_FOU_MOD'),
            'statut' => 'O',
            'path' => $this->router->generateUri(
                'Specifique155.reportingPerformance.index',
                ['id' => $id]
            ),
            'post' => ['filter_CODE_PERIODE' => $post['CODE_PERIODE']],
        ]);
    }

    public function chiffAffUpdateAction() :Response
    {
        $post = $this->request->getParsedBody();
        return $this->createJsonResponse([
            'chiffAffPrev' =>
                empty($post['CODE_PERIODE']) || empty($post['CODE_SOUS_FAMILLE'])
                ? '0.0'
                : Outils::formatMontant(
                    (new SysuFourReportPerf($this->pdo))->getChiffAff(
                        intval($post['CODE_PERIODE']) - 1,
                        $this->request->getAttribute('id'),
                        $post['CODE_SOUS_FAMILLE'],
                    )
                ),
        ]);
    }

    /**
     * @return mixed
     */
    public function importMultipleAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        Ariane::generate(0, $trad->t('Import multiple reporting'), $post, PaginatorGestion::getNbrArticle());
        ArianeSub::init();

        $flash = new Flash();

        return $this->renderer->render('@Specifique155.Fournisseur/reporting/import', [
            'menuActive' => 'Fournisseur',
            'menuLeft' => 'ImportReportPerf',
            'typeImport' => 'multi',
            'flash'      => $flash,
            "urlDownloadPattern"   => $this->router->generateUri('Specifique155.reportingPerformance.downloadPattern', ['type' => 'multi']),
        ]);
    }

    /**
     * @return mixed
     */
    public function importAction()
    {
        $id = $this->request->getAttribute('id');

        $fournis = new Fourniss($this->pdo);
        $fournis = $fournis->find($id);

        $trad = $this->getTranslationService();

        ArianeSub::generate(2, 0, $trad->t('Import reporting'), $_SERVER['REQUEST_URI'], 1);

        return $this->renderer->render('@Specifique155.Fournisseur/reporting/import', [
            'menuActive' => 'Fournisseur',
            'menuLeft' => 'importperf',
            'fournisseur' => $fournis,
            "code_fournisseur" => $id,
            "libelle_fournisseur" => $fournis["RS"],
            "urlDownloadPattern"   => $this->router->generateUri('Specifique155.reportingPerformance.downloadPattern', ['type' => 'mono']),
        ]);
    }

    /**
     * @return Response|void
     */
    public function deleteAction()
    {
        $id         = $this->request->getAttribute('id');
        $periode    = $this->request->getAttribute('periode');
        $ssf        = $this->request->getAttribute('ssf');

        $report = new SysuFourReportPerf($this->pdo);

        $exists = $report->checkExist($id, $periode, $ssf);

        if (count($exists) > 0) {
            $report->delete($id, $periode, $ssf);
            $flash = new Flash();
            $flash->success("Le reporting performance a bien été supprimé.");

            return $this->redirect($this->router->generateUri('Specifique155.reportingPerformance.index', ['id' => $id]));
        }
    }

    /**
     * @return void
     */
    public function downloadPatternAction()
    {
        $type = $this->request->getAttribute('type') ?? 'mono';
        $trad = $this->getTranslationService();

        $importReport = new ImportReporting($type, $trad);
        $generate = $importReport->generatePattern();

        // @phpstan-ignore-next-line
        Fichier::DownloadWithURL($generate->urlExcel);
    }
}
