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

class Computop3DSV2Response extends Common
{
    public $stepToAttempt;

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

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

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

        $offerUrl = Request::getOfferUrl();

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

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

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

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

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

    }

}

