<?php

namespace Modules\DemandeAchat\Controller;

use Entity\Model\DaEntet;
use Skeleton\Controller\Controller;
use Helpers\Trad\Trad;
use Modules\DemandeAchat\Repository\DemandeAchat;
use Helpers\Outil\Sql;

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

        $demandeAchat = (new DaEntet($this->pdo))
            ->find(['NO_DA' => $numDA]);
        $commentaire = (new DemandeAchat($this->pdo))
            ->getCommentaire($numDA);

        if ($this->request->getMethod() == 'POST' && isset($post['commentaire'])) {
            $daEntet = new \Entity\Model\DaEntet($this->pdo);
            if ($post['NM_COMMEN'] == '0') {
                // creation commentaire dans MEMOS et mise à jour entete DA
                $codeMemo = sql::updateMemo($this->pdo, '', $post['commentaire']);
                $daEntet->update(['NM_DCOMP' => $codeMemo], $numDA);
            } elseif (trim($post['commentaire']) != '') {
                // MAJ du commentaire
                $codeMemo = Sql::updateMemo($this->pdo, $post['NM_COMMEN'], $post['commentaire']);
            } else {
                // suppression du commentaire et mise à 0 du code commentaire dans entete DA
                sql::deleteMemos($this->pdo, $post['NM_COMMEN']);
                $daEntet->update(['NM_COMMEN' => 0], $numDA);
            }
        }

        $trad = $this->getTranslationService();
        $libelle = Trad::strBuild($trad->t("Commentaire pour la DA n° @1@"), $numDA);

        return $this->renderer->render('@DemandeAchat/Popup/commentaire', [
            'commentaire' => $commentaire,
            'id' => $numDA,
            'Libelle' => $libelle,
            'path' => $this->router->generateUri('DemandeAchat.PopupCommentaireDemandeAchat.commentaire', ['idDA' => $numDA]),
            'editable' => $demandeAchat['DTE_VAL'] != '00000000'
                ? false
                : true
        ]);
    }
}
