<?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');

        $punChouRepo = new Punchout($this->pdo);
        $infoPO = $punChouRepo->getInfoPunchout($idCatalogue);
        
        if ($infoPO && $infoPO['SRCDATA'] == 'PC') {
            $punchout = new PunchOutCXml($this->pdo, $idCatalogue);
        } elseif ($infoPO) {
            $punchout = new PunchOutOCI($this->pdo, $idCatalogue);
        }
        
        if (isset($punchout)) {
            //Pour les retours du Punchout en V1 a supprimer une foi le panier repris en V2
            $_SESSION['cachePunchoutV2'] = [
                'idCat' => $idCatalogue,
                'type'  => $infoPO['SRCDATA'],
            ];
    
            return new Response(200, [], (string) json_encode([
                'url'           => $punchout->getUrlPunchOut(),
                'destination'   => $punchout->getDestination(),
            ]));
        } else {
            return new Response(400);
        }
    }
}
