<?php

namespace Modules\DemandeAchat\Controller;

use GuzzleHttp\Psr7\Response;
use Skeleton\Controller\Controller;
use Helpers\Trad\Trad;
use Modules\DemandeAchat\WebService\DemandeAchat as WebServiceDemandeAchat;

class SolderDemandeAchatController extends Controller
{
    public function solderAction(): string
    {
        $purchaseRequestId = $this->request->getAttribute('idDA');

        return $this->renderer->render('@DemandeAchat/Solder/popupSolde', [
            'idDA' => $purchaseRequestId,
            'type' => 'solde',
        ]);
    }


    public function desolderAction(): string
    {
        $purchaseRequestId = $this->request->getAttribute('idDA');

        return $this->renderer->render('@DemandeAchat/Solder/popupSolde', [
            'idDA' => $purchaseRequestId,
            'type' => 'desolde',
        ]);
    }
    
    /**
     * confirmationSolderAction
     *
     * @return Response|string
     */
    public function confirmationSolderAction()
    {
        $numDA = $this->request->getAttribute('idDA');
        $trad = $this->getTranslationService();
        $post = $this->request->getParsedBody();

        $xmlResult = (new WebServiceDemandeAchat())
            ->solderDemande($numDA, 'S', $post['commentaire'] ?? '');
        $xml = new \SimpleXMLElement($xmlResult->responseData);

        if ($xml->Statut == "O") {
            return $this->createJsonResponse([
                'path' => $this->router->generateUri('DemandeAchat.GestionDemandeAchat.index')
            ], 443);
        } else {
            $xmlErreur = str_replace('"', '\'', $xmlResult->responseData);
            $xmlErreur = preg_replace("#[\n\t\r]#", "", $xmlErreur);

            return $this->renderer->render('@popup-erreur/ErreurXml', [
                'ErreurValid' => $xml,
            ]);
        }
    }
    
    /**
     * confirmationDesolderAction
     *
     * @return Response|string
     */
    public function confirmationDesolderAction()
    {
        $numDA = $this->request->getAttribute('idDA');
        $trad = $this->getTranslationService();

        $xmlResult = (new WebServiceDemandeAchat())
            ->solderDemande($numDA, 'D', '');
        $xml = new \SimpleXMLElement($xmlResult->responseData);

        if ($xml->Statut == "O") {
            return $this->createJsonResponse([
                'path' => $this->router->generateUri('DemandeAchat.GestionDemandeAchat.index')
            ], 443);
        } else {
            $xmlErreur = str_replace('"', '\'', $xmlResult->responseData);
            $xmlErreur = preg_replace("#[\n\t\r]#", "", $xmlErreur);

            return $this->renderer->render('@popup-erreur/ErreurXml', [
                'ErreurValid' => $xml,
            ]);
        }
    }
}
