<?php

namespace Modules\DemandeAchat\Controller;

use Entity\Model\DaClaus;
use Entity\Model\Memos;
use Skeleton\Controller\Controller;
use Helpers\Outil\Sql;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Helpers\Trad\Trad;
use Modules\DemandeAchat\Repository\ModificationDemandeAchat;

class ModificationClauseDemandeAchatController extends Controller
{
    public function ajaxAjoutLigneAction(): string
    {
        $idDA = $this->request->getAttribute('idDA');
        $post = $this->request->getParsedBody();

        $ligne['NO_ORDRE'] = $post['index'] + 1;

        return $this->renderer->render('@DemandeAchat/Creation/clause', [
            'idDA' => $idDA,
            'ligne' => $ligne,
            'open' => true,
        ]);
    }

    public function ajaxModificationLigneAction(): string
    {
        $idDA = $this->request->getAttribute('idDA');
        $post = $this->request->getParsedBody();
        $idLigne = $post['index'];

        $repository = new ModificationDemandeAchat($this->pdo);
        $ligne = $repository->allDetailClause($idDA, $idLigne);

        return $this->renderer->render('@DemandeAchat/Creation/clause', [
            'ligne' => $ligne,
            'idDA' => $idDA,
            'open' => true,
        ]);
    }

    public function validationLigneAction()
    {
        $idDA = $this->request->getAttribute('idDA');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $validator = $this->createValidator();
        $validator->isStringAvecEspace(
            $trad->t('Clause'),
            $post['clause_CONTMEMO'],
            1,
            3000
        );

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

        $idOrdre = $post['CLAUSE_NO_ORDRE_MODIF'];

        if ($validator->isValid()) {
            if (!empty($repository->allDetailClause($idDA, $idOrdre))) {
                $majOK = sql::updateMemo($this->pdo, $post['clause_NM_PARAG'], $post['clause_CONTMEMO']);
            } else {
                // creation dans MEMOS et dans DA_CLAUS
                if ($codeMemo = sql::updateMemo($this->pdo, '', $post['clause_CONTMEMO'])) {
                    $insertValue = [
                        'NO_DA' => $idDA,
                        'NO_ORDRE' => $idOrdre,
                        'NM_PARAG' => $codeMemo,
                        'VERR_MOD' => false,
                        'ISSU_TAC' => false,
                        'CLAU_FIX' => false,
                    ];

                    $majOK = (new DaClaus($this->pdo))
                        ->insert($insertValue);
                }
            }

            if (!$majOK) {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $trad->t("Erreur lors de l'enregistrement"),
                    'titrePopup' => $trad->t("Erreur sur la clause") . $trad->colon() . $idOrdre,
                ]);
            }

            $ligne = $repository->allDetailClause($idDA, $idOrdre);

            return new Response(
                443,
                [],
                $this->renderer->render(
                    '@DemandeAchat/Creation/clauseNonModifiable',
                    ['ligne' => $ligne]
                )
            );
        } else {
            $params = [
                'alerte' => $validator->getError(),
                'titrePopup' => $trad->t("Erreur sur la clause") . $trad->colon() . $idOrdre,
            ];
            return $this->renderer->render(
                '@popup-erreur/erreurAlerteEtAvertissement',
                ['params' => $params]
            );
        }
    }

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

        $idOrdre = $post['CLAUSE_NO_ORDRE_MODIF'];
        $ligne = (new ModificationDemandeAchat($this->pdo))
            ->allDetailClause($idDA, $idOrdre);

        if ($ligne) {
            return $this->renderer->render('@DemandeAchat/Creation/clauseNonModifiable', [
                'ligne' => $ligne,
            ]);
        } else {
            return '';
        }
    }

    public function suppressionLigneAction()
    {
        $idDA = $this->request->getAttribute('idDA');
        $post = $this->request->getParsedBody();

        $daClaus = new DaClaus($this->pdo);

        $idLigne = $post['index'];
        $ligne = $daClaus->find(
            [
                'NO_DA' => $idDA,
                'NO_ORDRE' => $idLigne
            ]
        );
        $codeMemo = $ligne['NM_PARAG'];

        if ($majOK = $daClaus
            ->delete(['NO_DA' => $idDA, 'NO_ORDRE' => $idLigne])
        ) {
            // suppression du commentaire
            (new Memos($this->pdo))
                ->delete(['NODEMEMO' => $codeMemo]);
        }

        if ($majOK) {
            return new Response(200, [], '');
        } else {
            $trad = $this->getTranslationService();
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $trad->t("Erreur lors de la suppression de la clause")
                    . $trad->colon()
                    . $idLigne,
                'titrePopup' => $trad->t("Erreur"),
            ]);
        }
    }

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

        $newPosition = $post['newPosition'];
        $oldPosition = $post['oldPosition'];

        $moveUp = false;
        if ($newPosition < $oldPosition) {
            $moveUp = true;
        }

        (new ModificationDemandeAchat($this->pdo))
            ->modificationOrdreClause(
                $idDA,
                $newPosition,
                $oldPosition,
                $moveUp
            );

        return '';
    }
}
