<?php

namespace twa\omnipay\controllers;

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

class MollieInPageController
{
    public $data;
    public $provider;

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

        $required_data = ['API_KEY' , 'PARTNER_ID', 'PROFILE_ID', "METHOD"];
        \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)
    {

        $response = Http::withToken($this->data['API_KEY'])->post('https://api.mollie.com/v2/payments', [
            "amount" => ["currency" => $currency, "value" => number_format($value,2,'.',"") ],
            "description" => "Order Attempt #".$id." from ".env("APP_NAME"),
            "redirectUrl" => $url_success,
            "method" => "creditcard",
            "cardToken" => session('inpage_checkout_data')['token'],

        ]);
        if($response->getStatusCode() != 400){
            $response = twaJsonDecode($response->body());
            if(isset($response['_links']['checkout']['href'])){
                Cache::store('file')->put('mollie_id_'.$id,$response['id'],3600);
                return collect(['redirect' => ['link' => $response['_links']['checkout']['href'] ], "id" => $response['id'] ]);
            }else{
                return collect(['status' => 'fail', 'response' => $response]);
            }
        }else{
            return collect(['status' => 'fail', 'response' => "failed" ]);
        }

//        return collect(['redirect' => ['link' => env('APP_URL').'/omnipay/response/unknown/'.$id  ] , 'response' => [
//            'amount' => $value,
//            'currency' => $currency,
//            'url_success' => $url_success,
//            'url_fail' => $url_cancel
//        ]]);

    }

    public function checkPayment($id)
    {

        $id = Cache::store('file')->get('mollie_id_'.$id);
//        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], 400);

    }
}
