<?php
namespace Modules\Catalogue\Controller;

use Entity\Model\ArtEquiv;
use Entity\Model\CCataSrc;
use Entity\Model\EquivArt;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Sql;
use Modules\Catalogue\MenuContextuel\ArticleEquivalentMenuContextuel;
use Modules\Catalogue\Repository\ControleRepository;
use Skeleton\Controller\Controller;

class ArticleEquivalentController extends Controller
{
    public function listeEquiArticleAction():mixed
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $idClass = $this->request->getAttribute('idClass');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        Ariane::generate(3, $trad->t('Articles de Classe'));

        $listeEquiv = (new ControleRepository($this->pdo))->listeEquivalenceClass($idClass, $post);
        
        if (!$listeEquiv) {
            return $this->redirect('Catalogue.ArticleEquivalent.createEquivalent', ['idLigne' => $idLigne]);
        }

        $menuContextuel = (new ArticleEquivalentMenuContextuel($this->pdo, $this->router, $trad));
        foreach ($listeEquiv as &$article) {
            $article['menuContextuel'] = $menuContextuel->generate($article, count($listeEquiv));
        }

        return $this->renderer->render('@catalogue/ArticleEquivalent/listeEquiArticle', [
            'idLigne' => $idLigne,
            'idClass' => $idClass,
            'listeEquiv' => $listeEquiv,
            'infoEquiv' => (new EquivArt($this->pdo))->find($idClass),
            'post' => $post,
        ]);
    }

    public function dissocierAction():response
    {
        $codeArt    = $this->request->getAttribute('codeArt')   =='noID'? '':$this->request->getAttribute('codeArt');
        $codeFou    = $this->request->getAttribute('codeFou')   =='noID'? '':$this->request->getAttribute('codeFou');
        $artFou     = $this->request->getAttribute('artFou')    =='noID'? '':$this->request->getAttribute('artFou');
        $codeFab    = $this->request->getAttribute('codeFab')   =='noID'? '':$this->request->getAttribute('codeFab');
        $artFab     = $this->request->getAttribute('artFab')    =='noID'? '':$this->request->getAttribute('artFab');
        $idClass    = $this->request->getAttribute('idClass')   =='noID'? '':$this->request->getAttribute('idClass');

        $prefArt = (new EquivArt($this->pdo))->find($idClass);

        $keyPath = implode('|', [$codeArt, $codeFou, $artFou, $codeFab, $artFab]);
        $keyPref = implode('|', [$prefArt['ART_REF'], $prefArt['COD_FOURN'], $prefArt['REF_FOURN'], $prefArt['COD_FAB'], $prefArt['REF_FAB']]);

        // on supprime l'article équivalent
        (new ArtEquiv($this->pdo))->delete([
            'CODEART'   => $codeArt,
            'CODEFOUR'  => $codeFou,
            'ARTFOUR'   => $artFou,
            'CODEFAB'   => $codeFab,
            'ARTFAB'    => $artFab,
            'CLASSNUM'  => $idClass,
        ]);

        // on vérifie que l'article supprimé était pas le préférentiel
        // si c'est le cas, on vérifie si il reste un article équivalent, si c'est le cas, on le passe en préférentiel
        // sinon on supprime le préférentiel
        if ($keyPath == $keyPref) {
            $lastEquiv = (new ArtEquiv($this->pdo))->find(['CLASSNUM' => $idClass]);

            if (!$lastEquiv) {
                (new EquivArt($this->pdo))->delete([
                    'NUM_CLEQ'  => $idClass,
                ]);
            } else {
                (new EquivArt($this->pdo))->merge([
                    'NUM_CLEQ'  => $idClass,
                    'ART_REF'   => $lastEquiv['CODEART'],
                    'COD_FOURN' => $lastEquiv['CODEFOUR'],
                    'REF_FOURN' => $lastEquiv['ARTFOUR'],
                    'COD_FAB'   => $lastEquiv['CODEFAB'],
                    'REF_FAB'   => $lastEquiv['ARTFAB'],
                ]);

                (new ArtEquiv($this->pdo))->update([
                    'REFERENCE' => true,
                ], [
                    'CODEART'   => $lastEquiv['CODEART'],
                    'CODEFOUR'  => $lastEquiv['CODEFOUR'],
                    'ARTFOUR'   => $lastEquiv['ARTFOUR'],
                    'CODEFAB'   => $lastEquiv['CODEFAB'],
                    'ARTFAB'    => $lastEquiv['ARTFAB'],
                    'CLASSNUM'  => $idClass,
                ]);
            }
        }

        $back = Ariane::getBackPath();
        return new Response(200, [], (string)json_encode(['path' => $back]));
    }

    public function referentAction():response
    {
        $codeArt    = $this->request->getAttribute('codeArt');
        $codeFou    = $this->request->getAttribute('codeFou');
        $artFou     = $this->request->getAttribute('artFou');
        $codeFab    = $this->request->getAttribute('codeFab');
        $artFab     = $this->request->getAttribute('artFab');
        $idClass     = $this->request->getAttribute('idClass');

        (new ArtEquiv($this->pdo))->update([
            'REFERENCE' => false,
        ], [
            'CLASSNUM'  => $idClass =='noID'? '':$idClass
        ]);

        (new ArtEquiv($this->pdo))->update([
            'REFERENCE' => true,
        ], [
            'CODEART'   => $codeArt =='noID'? '':$codeArt,
            'CODEFOUR'  => $codeFou =='noID'? '':$codeFou,
            'ARTFOUR'   => $artFou  =='noID'? '':$artFou,
            'CODEFAB'   => $codeFab =='noID'? '':$codeFab,
            'ARTFAB'    => $artFab  =='noID'? '':$artFab,
            'CLASSNUM'  => $idClass =='noID'? '':$idClass,
        ]);

        (new EquivArt($this->pdo))->merge([
            'NUM_CLEQ'  => $idClass =='noID'? '':$idClass,
            'ART_REF'   => $codeArt =='noID'? '':$codeArt,
            'COD_FOURN' => $codeFou =='noID'? '':$codeFou,
            'REF_FOURN' => $artFou  =='noID'? '':$artFou,
            'COD_FAB'   => $codeFab =='noID'? '':$codeFab,
            'REF_FAB'   => $artFab  =='noID'? '':$artFab,
        ]);

        return new Response(200);
    }

    public function gestionPreferenceAction():Response
    {
        $idClass     = $this->request->getAttribute('idClass');

        $equiVart = (new EquivArt($this->pdo))->find($idClass);

        (new EquivArt($this->pdo))->update([
            'ARTPRACT' => !Sql::boolSql($equiVart['ARTPRACT'])
        ], [
            'NUM_CLEQ' => $idClass
        ]);

        return new Response(200, [], (string)json_encode(['statut' => 'O', 'etat' => !Sql::boolSql($equiVart['ARTPRACT'])]));
    }

    public function ajaxAddArticleAction():Response
    {
        $idClass    = $this->request->getAttribute('idClass');
        $post       = $this->request->getParsedBody();

        list($idCata, $codeArt, $codeFou, $artFou, $codeFab, $artFab) = explode('|', $post['id']);

        (new ArtEquiv($this->pdo))->insert([
            'CODEART'   => $codeArt,
            'CODEFOUR'  => $codeFou,
            'ARTFOUR'   => $artFou,
            'CODEFAB'   => $codeFab,
            'ARTFAB'    => $artFab,
            'CLASSNUM'  => $idClass,
            'COEFCONV'  => 1,
            'REFERENCE' => false,
        ]);

        return new Response(200, [], (string)json_encode(['statut' => 'O']));
    }

    public function createEquivalentAction():string
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $trad = $this->getTranslationService();

        Ariane::generate(3, $trad->t('Création d\'une équivalence'));

        return $this->renderer->render('@catalogue/ArticleEquivalent/createEquivalence', [
            'idLigne' => $idLigne,
            'newIdClass' => (int)(new EquivArt($this->pdo))->getMaxOrdre(null, 'NUM_CLEQ')+1,
            'article' => (new CCataSrc($this->pdo))->find($idLigne),
        ]);
    }

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

        return $this->renderer->render('@catalogue/ArticleEquivalent/createEquivalence', [
            'articleCompare' => (new CCataSrc($this->pdo))->find($post['id']),
        ]);
    }

    public function validateEquivAction():Response
    {
        $idLigne = $this->request->getAttribute('idLigne');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $validator = $this->createValidator();

        $validator->isObligatoire($post['ARTICLE'], $trad->t('Code article'));
        $validator->isFloat($trad->t('Coefficient de conversion'), $post['COEFF'], 13.2, true);

        if ($validator->isValid()) {
            $idClass = (int) (new EquivArt($this->pdo))->getMaxOrdre(null, 'NUM_CLEQ')+1;

            $article = (new CCataSrc($this->pdo))->find($idLigne);
            $articleCompare = (new CCataSrc($this->pdo))->find($post['ARTICLE']);

            (new ArtEquiv($this->pdo))->insert([
                'CODEART'   => $article['CODEARTI'],
                'CODEFOUR'  => $article['CODEFOUR'],
                'ARTFOUR'   => $article['REFARTFOU'],
                'CODEFAB'   => $article['FABRICANT'],
                'ARTFAB'    => $article['REFARTFAB'],
                'CLASSNUM'  => $idClass,
                'COEFCONV'  => 1,
                'REFERENCE' => true,
            ]);

            (new ArtEquiv($this->pdo))->insert([
                'CODEART'   => $articleCompare['CODEARTI'],
                'CODEFOUR'  => $articleCompare['CODEFOUR'],
                'ARTFOUR'   => $articleCompare['REFARTFOU'],
                'CODEFAB'   => $articleCompare['FABRICANT'],
                'ARTFAB'    => $articleCompare['REFARTFAB'],
                'CLASSNUM'  => $idClass,
                'COEFCONV'  => 1,
                'REFERENCE' => false,
            ]);

            (new EquivArt($this->pdo))->insert([
                'NUM_CLEQ'  => $idClass,
                'ART_REF'   => $article['CODEARTI'],
                'COD_FOURN' => $article['CODEFOUR'],
                'REF_FOURN' => $article['REFARTFOU'],
                'COD_FAB'   => $article['FABRICANT'],
                'REF_FAB'   => $article['REFARTFAB'],
                'ARTPRACT'  => true
            ]);

            return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Catalogue.ArticleEquivalent.listeEquiArticle', ['idLigne' => $idLigne, 'idClass' => $idClass])]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }
}
