<?php
namespace Modules\RechercheArticles\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Securite\Securite;
use Modules\RechercheArticles\PunchOut\PunchOutOCI;
use Modules\RechercheArticles\PunchOut\PunchOutCXml;
use Modules\RechercheArticles\Repository\Punchout;
use Skeleton\Controller\Controller;

class PunchOutController extends Controller
{
    public function init():void
    {
        Securite::setHeaderContentSecurityPolicyWithoutSelf();
    }
    
    /**
     * @return Response
     */
    public function generatePathAction()
    {
        $idCatalogue = $this->request->getAttribute('idCat');
        $trad = $this->getTranslationService();


        $punChouRepo = new Punchout($this->pdo);
        $infoPO = $punChouRepo->getInfoPunchout($idCatalogue);

        if ($infoPO && $infoPO['SRCDATA'] == 'PC') {
            $punchout = new PunchOutCXml($this->pdo, $this->router, $trad, $idCatalogue);
        } elseif ($infoPO) {
            $punchout = new PunchOutOCI($this->pdo, $this->router, $trad, $idCatalogue);
        }

        if (isset($punchout)) {
            return new Response(200, [], (string) json_encode([
                'url'           => $punchout->getUrlPunchOut(),
                'destination'   => $punchout->getDestination(),
            ]));
        } else {
            return new Response(400);
        }
    }

    /**
     * Summary of createItemsAction
     * @return string|Response
     */
    public function createItemsAction()
    {
        $idCatalogue    = $this->request->getAttribute('idCat');
        $action         = $this->request->getAttribute('action');
        $post           = $this->request->getParsedBody(true);
        $get            = $this->request->getQueryParams();
        $trad           = $this->getTranslationService();

        $punChouRepo = new Punchout($this->pdo);
        $infoPO = $punChouRepo->getInfoPunchout($idCatalogue);

        $array = [];
        if ($infoPO && $infoPO['SRCDATA'] == 'PC') {
            $punchout = new PunchOutCXml($this->pdo, $this->router, $trad, $idCatalogue);
            foreach ($post as $k => $v) {
                $array[strtolower($k)] = $v;
            }
        } elseif ($infoPO) {
            $punchout = new PunchOutOCI($this->pdo, $this->router, $trad, $idCatalogue);
            if ($get) {
                $array = $get;
            } else {
                foreach ($post as $k => $v) {
                    $array[strtoupper($k)] = $v;
                }
            }
        } else {
            error_log('Punchout non reconnu.');
            return new Response(400);
        }

        $punchout->parseRetour($array);
        $punchout->insertListeArticleFromPunchOut($this->getPdoOxaFT(), $action);
        
        return $this->renderer->render('@rechercheArticles/Recherche/retourPunchOut', []);
    }
}
