<?php

namespace twa\omnipay\controllers;

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

class TelrController
{
    public $data;
    public $provider;

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

        $required_data = ['auth_key','storeID','testing'];
        \twa\omnipay\controllers\GeneralFunctions::checkRequiredData($data, $required_data);
        $this->data = collect($data);
    }

    public function createSession()
    {
//        $response = Http::withHeaders([
//            'x-client-id' => $this->data['client_id'],
//            'x-api-key' => $this->data['api_key'],
//        ])->post('https://api.mollie.com/v2/payments/tr_WDqYK6vllg', []);

    }

    public function createPayment($id, $value, $currency, $customer_name, $customer_email, $url_success, $url_cancel)
    {
        $purchase=EcomPurchasesAttemptModel::query()->find($id);
  
        $params = array(
            'ivp_method'  => 'create',
            'ivp_store'   => $this->data['storeID'],
            'ivp_authkey' => $this->data['auth_key'],
            'ivp_cart'    => $id,
            'ivp_test'    => $this->data['testing'],
            'ivp_amount'  => $value,
            'ivp_currency'=> $currency,
            'ivp_desc'    => 'Purchase'.$id,
            'return_auth' => $url_success,
            'return_can'  => $url_cancel,
            'return_decl' => $url_cancel,
            'bill_fname' => $purchase['billing_address_details']['first_name'],
            'bill_sname' => $purchase['billing_address_details']['last_name'],
            'bill_addr1' => $purchase['billing_address_details']['country']['name'].', '.$purchase['billing_address_details']['state_info']['label'].', '.$purchase['billing_address_details']['city'].', '.$purchase['billing_address_details']['street'].', '.$purchase['billing_address_details']['building'].', '.$purchase['billing_address_details']['floor'],
            'bill_phone' => $purchase['billing_address_details']['phone'],
            'bill_city' => $purchase['billing_address_details']['city'],
            'bill_country' => $purchase['billing_address_details']['country']['code'],
            'bill_email' => $customer_email,
            'bill_custref' => $purchase['ecom_users_id'],
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://secure.telr.com/gateway/order.json");
        curl_setopt($ch, CURLOPT_POST, count($params));
        curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        $results = curl_exec($ch);
        curl_close($ch);
        $results = json_decode($results,true);

        $ref= trim($results['order']['ref']);
        $url= trim($results['order']['url']);
        if (empty($ref) || empty($url)) {
            return collect(['status' => 'fail', 'response' => "failed" ]);
        }else{
            return collect(['redirect' =>["link"=>$url], "id" => $ref, ]);
        }

    }

    public function checkPayment($attemptID)
    {

        $id = Cache::store('file')->get('telr_id_'.$attemptID);
//        Cache::forget('mollie_id_'.$attemptID);
//        $response = Http::withToken($this->data['API_KEY'])->get('https://api.mollie.com/v2/payments/'.$id);
//        if($response->getStatusCode() != 400){
//            $response = twaJsonDecode($response->body());
//            if(isset($response['status']) && $response['status'] == "paid"){
//                return response(['status' => 'success', 'response' => $response], 200);
//            }
//        }
//        return response(['status' => 'fail', 'response' => $response->body()], 400);
        $attempt=EcomPurchasesAttemptModel::query()->find($attemptID);

        $params = array(
            'ivp_method'  => 'check',
            'ivp_store'   => $this->data['storeID'],
            'ivp_test' => $this->data['testing'],
            'ivp_authkey' => $this->data['auth_key'],
            'order_ref'    => json_decode($attempt['gateway_init'])->id,

        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://secure.telr.com/gateway/order.json");
        curl_setopt($ch, CURLOPT_POST, count($params));
        curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        $results = curl_exec($ch);
        curl_close($ch);
        $results = json_decode($results,true);
        if(isset($results['order']['status']['text']) && $results['order']['status']['text']=='Paid'){
            return response(['status' => 'success', 'response' => $results], 200);
        }else{
            return response(['status' => 'fail', 'response' => $results['error']], 400);
        }

    }
}
