<?php
namespace Modules\Panier\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Roles;
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', [
            'menuActive'                => 'eproc',
            'droit'     => [
                'OX_MOD_ADL'            => roles::droitsUtilisateur($this->pdo, 'OX_MOD_ADL'),
                'HA_CCTR_CM'            => Roles::droitsUtilisateur($this->pdo, 'HA_CCTR_CM'),
                'HA_DA_TTCT'            => roles::droitsUtilisateur($this->pdo, 'HA_DA_TTCT'),
            ],
            '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'     => [
                'OX_MOD_ADL'    => roles::droitsUtilisateur($this->pdo, 'OX_MOD_ADL'),
                'HA_CCTR_CM'            => Roles::droitsUtilisateur($this->pdo, 'HA_CCTR_CM'),
                'HA_DA_TTCT'            => roles::droitsUtilisateur($this->pdo, 'HA_DA_TTCT'),

            ],
            '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,
            ]));
        }
    }
}
