<?php

namespace twa\omnipay\controllers;

use Illuminate\Support\Facades\Http;
use twa\ecomcart\models\EcomPurchasesAttemptModel;

class HyperpayController
{
    public $data;
    public $provider;

    public function __construct($data, $provider)
    {
        $this->provider = $provider;

        $required_data = ['entity_id', 'post_url' , 'token' , 'brands' , 'payment_type'];
        \twa\omnipay\controllers\GeneralFunctions::checkRequiredData($data, $required_data);
        $this->data = collect($data);
    }

    public function createPayment($id, $value, $currency, $customer_name, $customer_email, $url_success, $url_cancel){
        $data = [
            "entityId" => $this->data['entity_id'] ,
            "amount"=>$value,
            "currency"=> $currency,
            "paymentType"=> $this->data["payment_type"],
            "merchantTransactionId"=> $id,
            'customer' => [
                "email" => $customer_email,
                "givenName" => $customer_name
            ]
        ];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$this->data['token'],
        ])->post($this->data['url'].'/checkouts', $data);


        if ($response->status() != '200' && $response->status() != '201') {
            dd('Unexpected Error: HyperpayController createPayment() : unable to create order (1)');
        }

        $response = json_decode($response->body());

        if (!isset($response->result->code) || (isset($response->result->code) && $response->result->code != "000.200.100")) {
            dd('Unexpected Error: HyperpayController createPayment() : unable to create order (2)');
        }

        return collect([
            'redirect' => [
                'link' => "",
            ],
            'view' => [
                'name' => 'OmniPayViews::hyperpay.redirect',
                'parameters' => [
                    'checkout_id' => $response->id,
                    'url_success' => $url_success ,
                    'brands' => $this->data['brands'],
                    'url' => $this->data['url'],
                    'country_code' => $this->data['country_code']
                ],
            ],
            'response' => $response,
        ]);
    }

    public function checkPayment($attemptID)
    {
        $attempt = EcomPurchasesAttemptModel::where('id', $attemptID)->where('cancelled', 0)->first();
        $gatewayInit = json_decode($attempt->gateway_init);
        $session_id = isset($gatewayInit->id) ? $gatewayInit->id : null;

        if(!$session_id){
            dd('Unexpected Error: HyperpayController checkPayment() : unable to check order (1)');
        }

        $response = Http::withHeaders([
            'Authorization' => 'Bearer '.$this->data['token'],
        ])->get($this->data['url'].'/checkouts/'.$session_id."/payment?entityId=".$this->data["entity_id"]);


        if ($response->status() != '200' && $response->status() != '201') {
            dd('Unexpected Error: HyperpayController checkPayment() : unable to check order (2)');
        }

        $response = json_decode($response->body());

        if(!isset($response->result->code) || (isset($response->result->code) && preg_match('/^(000\.000\.|000\.100\.1|000\.[36])/', $response->result->code) != 1)){
            return response(['status' => 'fail', 'response' => $response], 400);
        }

        return response(['status' => 'success', 'response' => $response], 200);

    }
}
