<?php

namespace twa\omnipay\controllers;

use twa\ecomcart\models\EcomPurchasesAttemptModel;

class CoinbaseController
{
    public $data;

    public function __construct($data, $provider)
    {
        $required_data = ['api_key'];
        \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)
    {
        $mdata = [
            'name' => $customer_name,
            'description' => $customer_name.' '.$customer_email,
            'local_price' => [
                'amount' => number_format($value, 8, '.', ''),
                'currency' => $currency,
            ],
            'pricing_type' => 'fixed_price',
            'metadata.purchase_attempt_id' => $id,
            'metadata' => [
                'customer_name' => $customer_name,
                'customer_email' => $customer_email,
            ],
            'redirect_url' => $url_success,
            'cancel_url' => $url_cancel,
        ];

        $curl_post_data = json_encode($mdata);
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://api.commerce.coinbase.com/charges',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_VERBOSE => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => http_build_query($mdata),
            CURLOPT_HTTPHEADER => [
                'X-CC-Api-Key: '.$this->data['api_key'],
            ],
        ]);

        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response);

        if (! isset($response->data->hosted_url)) {
            return response(['status' => 'fail', 'response' => $response], 400);
        }

        return collect(['redirect' => ['link' => $response->data->hosted_url], 'response' => $response]);
    }

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

        if (! isset($gatewayInit->data->code)) {
            return response(['status' => 'fail', 'response' => ['message' => 'wrong format']], 400);
        }

        $charge_code = $gatewayInit->data->code;

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://api.commerce.coinbase.com/charges/'.$charge_code,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_VERBOSE => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => [
                'X-CC-Api-Key: '.$this->data['api_key'],
            ],
        ]);

        $response = curl_exec($curl);
        curl_close($curl);

        $response = collect(json_decode($response, 1));

        if (! isset($response['data']['timeline'])) {
            return response(['status' => 'fail', 'response' => $response], 400);
        }

        foreach ($response['data']['timeline'] as $timeline) {
            if ($timeline['status'] == 'COMPLETED') {
                return response(['status' => 'success', 'response' => $response], 200);
            }
        }

        return response(['status' => 'fail', 'response' => $response], 400);
    }
}
