<?php
namespace Modules\GlobalApplication\Controller;

use Entity\Model\Fourninc;
use Entity\Model\Hastutil;
use GuzzleHttp\Psr7\Response;
use Helpers\Trad\Trad;
use Modules\Ajax\Controller\MailController;

class MailLitigeController extends MailController
{
    public function updateContactLitigeAction() :Response
    {
        $incidId = $this->request->getAttribute('incidId');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $qbFourninc = new Fourninc($this->pdo);

        $incident = $qbFourninc->find($incidId);
        if (empty($incident)) {
            return new Response(404, [], 'Invalid incident #'.$incidId);
        }
        
        $validator = $this->validate($post);

        $validator->zoomListe(
            'Ajax.liste.utilisateur',
            Hastutil::class,
            $post['INCF_USER'],
            $trad->t('Contact responsable de la gestion de l’incident'),
            $this->pdo,
        );

        if (! $validator->isValid()) {
            return $this->createJsonResponse([
                'statut' => 'E',
                'erreur' => $validator->getError()
            ]);
        }

        $envoiMail = \Modules\Ajax\Controller\MailController::envoiMail($post);

        if ($envoiMail->Retour != "O") {
            return $this->createJsonResponse([
                'statut' => 'E',
                'erreur' => (string) $envoiMail->MsgErreur
            ]);
        }

        //______________________
        // Post processes

        $incident['INCF_USER'] = $post['INCF_USER'];
        $qbFourninc->merge($incident);
        
        \Modules\Facture\Controller\AjaxFactureController::mailEvenementFactureAction($post);

        return $this->createJsonResponse([
            'statut' => 'O',
            'message' => Trad::strBuild(
                $trad->t("Votre mail a bien été envoyé à @1@"),
                $post['destinataires']
            ),
        ]);
    }
}
