<?php

namespace twa\omnipay\controllers;

use Illuminate\Support\Facades\Http;

class TapController
{
    private $data;

    private $provider;

    public function __construct($data, $provider)
    {
        $this->provider = $provider;
        $required_data = ['secret_api_key'];
        \twa\omnipay\controllers\GeneralFunctions::checkRequiredData($data, $required_data);
        $this->data = collect($data);
    }

    public function createPayment($id, $value, $currency, $customer_name = null, $customer_email = null, $url_success = null, $url_cancel = null)
    {
        $purchase_attempt = \twa\ecomcart\models\EcomPurchasesAttemptModel::find($id);
        $cms_attributes = $purchase_attempt->cms_attributes;
        $cms_attributes['init_value'] = $value;
        $purchase_attempt->cms_attributes = $cms_attributes;
        $purchase_attempt->save();

        return collect(['redirect' => ['link' => env('APP_URL').'/omnipay/redirect/tap/'.$id.'/'.$this->provider.'/'.$value.'/'.$currency.'/'.md5($id.$this->provider.$value.$currency.env('APP_KEY')).'?lang='.app()->getLocale().'&url_success='.urlencode($url_success)]]);
    }

    public function checkPayment($attemptID)
    {
        $attempt = \twa\ecomcart\models\EcomPurchasesAttemptModel::where('id', $attemptID)->where('cancelled', 0)->first();
        $init_value = is_array($attempt->cms_attributes) ? $attempt->cms_attributes['init_value'] : json_decode($attempt->cms_attributes)->init_value;
        if (! request()->has('tap_id') || empty($init_value)) {
            return response([], 400);
        }
        $charge_id = request()->input('tap_id');

        $response = Http::withHeaders([
            'content-type' => 'application/json',
            'Authorization' => 'Bearer '.$this->data['secret_api_key'],
        ])->get('https://api.tap.company/v2/charges/'.$charge_id, []);

        if (request()->input('debug')) {
            dd(['debug' => true, 'response' => $response->body()]);
        }

        if ($response->status() != '200' && $response->status() != '201') {
            return response([], 400);
        }

        $response = collect(json_decode($response->body(), 1));

        $attempt->response_gateway = $response;
        $attempt->save();

        if (! isset($response['status']) || $response['status'] != 'CAPTURED') {
            return response([], 400);
        }

        if ($response['amount'] != $init_value) {
            return response([], 200);
        }

        return response([], 200);
    }
}
