<?php

namespace Mtc\Plugins\Realex\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;
use Mtc\Plugins\Realex\Classes\Realex;
use Mtc\Plugins\Realex\Classes\OrderRealex;
use Mtc\Plugins\Realex\Classes\RealexLog;

use GlobalPayments\Api\ServiceConfigs\Gateways\GpEcomConfig;
use GlobalPayments\Api\ServicesContainer;
use GlobalPayments\Api\Entities\Transaction;
use GlobalPayments\Api\Entities\Exceptions\ApiException;
use GlobalPayments\Api\HostedPaymentConfig;
use GlobalPayments\Api\Entities\HostedPaymentData;
use GlobalPayments\Api\Entities\Enums\HppVersion;
use GlobalPayments\Api\Services\HostedService;


class RealexController extends BaseController
{

    public function callback()
    {
        if (! request()->input('hppResponse')) {
            header("HTTP/1.0 400 Bad Request");
            exit();
        }

        if (! request()->input('order_id')) {
            header("HTTP/1.0 400 Bad Request");
            exit();
        }

        $response = request()->input('hppResponse');

        RealexLog::saveResponse($response, request()->input('order_id'), 'callback_raw');

        $realex = new Realex();
        $output = $realex->parseCallbackResponse($response, request()->input('order_id'));

        if ($output['success']) {
            $order = new \Order($output['order_id']);
            $order->markPaid();
            $order->saveRealex();

            OrderRealex::where('order_id', $output['order_id'])
                ->firstOrCreate([
                    'order_id' => $output['order_id'],
                    'amount_paid' => $order->getTotalCost(),
                    'tnx_id' => $output['transaction_id'],
                ]);


            $redirect_to = $this->get_order_complete_url($output['order_id']);
        } else {
            $redirect_to = "/shop/checkout/basket_overview.php?error=payment_declined&response_code={$output['response_code']}";
        }

        return redirect()->to($redirect_to);
    }


    private function get_order_complete_url($order_id)
    {
        $url = HTTPS_SITE_URL . '/shop/checkout/order_complete.php';
        $data = [
            'order_id' => $order_id,
            'payment_gateway' => 'realex',
        ];
        $data += $_GET;

        $url .= '?' . http_build_query($data);

        return $url;
    }

}
