<?php

namespace Extension\KonnektiveUtilPack;

use Application\Config;
use Application\Request;
use Application\Response;
use Application\CrmResponse;
use Application\CrmPayload;
use Application\Lang;
use Application\Session;
use Application\Extension;

class KlarnaResponse extends Common
{
    public $stepToAttempt;
    

    public function __construct()
    {
        $this->stepToAttempt     = (int) Session::get('steps.current.id');     
    }

    public function updateCrmPayload()
    {  
        $klarna = Config::extensionsConfig(
            'KonnektiveUtilPack.klarna_stripe'
        );

        if (
            Request::attributes()->get('action') === 'prospect' || empty($klarna)
        ) {
            return;
        }

        $offerUrl = Request::getOfferUrl();

        if(Session::get('customer.cardType') !=='klarna')

        return;

        if(CrmPayload::get('paySource')=='PAYPAL')
        return;

        CrmPayload::set("cardType",'PREPAID');
        CrmPayload::set("paySource",'PREPAID');
        CrmPayload::set("prepaidType",'KLARNA');
        CrmPayload::set("forceMerchantId",Config::extensionsConfig('KonnektiveUtilPack.klarna_stripe_merchant_id'));
        
        //$payload['forceGatewayId']  = Config::extensionsConfig('KonnektiveUtilPack.klarna_stripe_merchant_id');

        $payload['redirectsTo']      = $offerUrl . 'extensions/KonnektiveUtilPack/KlarnaPostResponse.php';
        $payload['errorRedirectsTo'] = $offerUrl . AJAX_PATH . 'extensions/konnektiveutilpack/klarna-response-error';
        CrmPayload::update($payload);

        //Session::set('extensions.konnektiveutilpack.crmPayload', CrmPayload::all());
        
        
    }

    public function captureCrmResponse()
    {  
        $klarna = Config::extensionsConfig(
            'KonnektiveUtilPack.klarna_stripe'
        );

        if (
            Request::attributes()->get('action') === 'prospect' || empty($klarna)
        ) {
            return;
        }

        $response = CrmResponse::all();

       Session::set('extensions.konnektiveutilpack.klarna.crmPayload', CrmPayload::all());
        
        if (!$response['success']) {
            if($response['redirect']){
                Response::send(array(
                    'success'         => true,
                    'skipQueryParams' => true,
                    'redirect'        => CrmResponse::get('redirect'),
                ));
            }
            else{
                Response::send(
                    array(
                        'success' => true,
                        'errors'  => array(),
                    )
                );
            }
            
        }
    }

    public function klarnaResponse()
    {
        
        $response     = Request::query()->all();
        $instancePath = Request::getInstancePath();


        if (!empty($response['orderData'])) {
            $orderData = json_decode($response['orderData'], true);
            if ($orderData['orderStatus'] == 'COMPLETE') {
                Session::set(
                    sprintf('steps.%d.orderId', $this->stepToAttempt), $orderData['orderId']
                );
                Session::set(
                    sprintf('steps.%d.customerId', $this->stepToAttempt), $orderData['customerId']
                );
                Session::set('queryParams.order_id', $orderData['orderId']);
                Session::set('queryParams.customer_id', $orderData['customerId']);
                $queryParams = Session::get('queryParams');
                $url         = rtrim($instancePath, '/') . '/' . Session::get('steps.next.link');


                CrmResponse::replace(
                    array('success' => true, 'orderId' => $orderData['orderId'], 'customerId' => $orderData['customerId'])
                );
 
                //CrmPayload::replace(Session::get('extensions.konnektiveutilpack.crmPayload'));
                $this->setNecessarySessionData();

                Extension::getInstance()->performEventActions('afterAnyCrmRequest');

                //Session::remove('extensions.konnektiveutilpack.crmPayload');

                header(sprintf('Location: %s?%s', $url, http_build_query($queryParams)));
                exit;
            }
        }

        $errorMessage = Lang::get('exceptions.generic_error');

        foreach ($response as $key => $value) {
            if (preg_match("/errorMsg=?.*/i", $value, $match)) {
                $errorMessageParts = explode('=', $match[0]);
                if (!empty($errorMessageParts[1])) {
                    $errorMessage = $errorMessageParts[1];
                    break;
                }
            }
        }

        $queryParams          = Session::get('queryParams');
        $queryParams['error'] = $errorMessage;
        $url                  = rtrim($instancePath, '/') . '/' . Session::get('steps.current.link');
        header(sprintf('Location: %s?%s', $url, http_build_query($queryParams)));
        exit;

    }

    public function klarnaResponseError()
    {
        
        $response     = Request::query()->all();
        $instancePath = Request::getInstancePath();
        
        if(!empty($response['errorMsg'])) {
            $errorMessage = $response['errorMsg'];
        } else {
            $errorMessage = Lang::get('exceptions.generic_error');
        }

        $queryParams          = Session::get('queryParams');
        $queryParams['error'] = $errorMessage;
        $url                  = rtrim($instancePath, '/') . '/' . Session::get('steps.current.link');
        header(sprintf('Location: %s?%s', $url, http_build_query($queryParams)));
        exit;

    }

    private function setNecessarySessionData()
    {
        $crmPayloadData = Session::get('extensions.konnektiveutilpack.klarna.crmPayload');
            
        CrmPayload::replace($crmPayloadData);
        
        //Session::set('steps.' . $this->stepToAttempt . '.gatewayId', CrmResponse::get('gatewayId'));
        Session::set(sprintf('steps.%d.products', $this->stepToAttempt), CrmPayload::get('products', array()));
    }

}

