<?php
namespace Modules\Panier\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Modules\Panier\Repository\PanierEntete;
use Modules\Panier\Service\PanierEnteteService;
use Modules\Panier\Validator\CentreLivraisonValidator;
use Skeleton\Controller\Controller;

class CentreLivraisonController extends Controller
{
    public function ficheAction() : string
    {
        $trad = $this->getTranslationService();
        
        Ariane::generate(1, $trad->t('Centre de livraison'));

        return $this->renderer->render('@Panier/CentreLivraison/fiche', [
            'droit'     => [
                'GLOB_AuthModAdrLiv' => $_SESSION['GLOB_AuthModAdrLiv'],
            ],
            'panier'    => (new PanierEntete($this->pdo))->getEntetePanier($_SESSION['id_panier'], $_SESSION['id_user']),
        ]);
    }

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

        return $this->renderer->render('@Panier/CentreLivraison/fiche', [
            'droit'     => [
                'GLOB_AuthModAdrLiv' => $_SESSION['GLOB_AuthModAdrLiv'],
            ],
            'panier'    => (new PanierEntete($this->pdo))->getInfoCentre($post['LIV_CTR']),
        ]);
    }

    /**
     * @return Response
     */
    public function validateAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $infoEntete = (new PanierEntete($this->pdo))->getEntetePanier($_SESSION['id_panier'], $_SESSION['id_user']);
        
        $validator = new CentreLivraisonValidator($this->pdo, $trad);
        $validator->centreLivraisonPanier($post, $infoEntete['CODE_STE']);

        if ($validator->isValid()) {
            (new PanierEnteteService($this->pdo))->changeCentreLivraison($post);

            $backPath = Ariane::getBackPath();
            $backPost = Ariane::getBackPost();

            return new Response(443, [], (string) json_encode(['path' => $backPath, 'post' => $backPost]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }
}
