<?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 ThreeDs extends Common
{
    public $stepToAttempt;

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

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

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

        if(Session::get('customer.cardType') =='klarna' || CrmPayload::get('paySource')=='PAYPAL'){
            return;
        }

        

        $offerUrl = Request::getOfferUrl();
        Session::set('extensions.konnektiveutilpack.crmPayload', CrmPayload::all());

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

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

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

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

        $response = CrmResponse::all();
        
        if (!$response['success'] && !empty($response['isMerchantRedirection'])) {
            if($response['redirect']){
                Response::send(array(
                    'success'         => true,
                    'skipQueryParams' => true,
                    'redirect'        => CrmResponse::get('redirect'),
                ));
            }
            else{
                $response['new_script'] = sprintf('<body><script>%s</script></body>', $response['script']);
                Response::send(
                    array(
                        'success' => true,
                        'errors'  => array(),
                        'html'    => $response['new_script'],
                        'is_html' => true,
                    )
                );
            }
            
        }
    }

    public function threeDsResponse()
    {
        
        $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');

                $message = sprintf(
                    '%s | %s', Request::getOfferUrl(), Request::headers()->get('HTTP_USER_AGENT')
                );
                Session::set(
                    'extensions.konnektiveUtilPack.customerNote.crmPayload',
                    array(
                        'customerId' =>  $orderData['customerId'],
                        'message'    => $message,
                    )
                );

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

                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 threeDsResponseError()
    {
        
        $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;

    }

}

