<?php

namespace twa\omnipay\controllers;

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

class StripeController
{
    public $data;
    public $provider;

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

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



    public function createSession($id,$value,$currency)
    {
        return true;
    }

    public function createPayment($id, $value, $currency, $customer_name, $customer_email, $url_success, $url_cancel)
    {
        $stripe = new \Stripe\StripeClient($this->data['secretKey']);
        $product = $stripe->products->create([
            'name' => 'Your Purchase from '.env('APP_NAME').' id # '.$id,
        ]);
        $productID = $product['id'];
        $price = $stripe->prices->create([
            'unit_amount' => $value*100,
            'currency' => $currency,
            'product' => $productID,
        ]);
        Stripe::setApiKey($this->data['secretKey']);
        $response = \Stripe\Checkout\Session::create([
            'line_items' => [[
                # Provide the exact Price ID (e.g. pr_1234) of the product you want to sell
                'price' => $price['id'],
                'quantity' => 1,
            ]],
            'mode' => 'payment',
            'success_url' => env('APP_URL').'/omnipay/response/success/'.$id,
            'cancel_url' =>  ecom('url')->prefix(true).'/cart',
        ]);
        if(isset($response['url']) && $response['url']){
            return collect(['redirect' => ['link' => $response['url'] ], "id" => $response['payment_intent'] ]);
        }else{
            return collect(['status' => 'fail', 'response' => $response]);
        }

    }

    public function checkPayment($attemptID)
    {
        $purchase_attempt = EcomPurchasesAttemptModel::find($attemptID);
        $intent = twaJsonDecode($purchase_attempt['gateway_init'])['id'];

        $stripe = new \Stripe\StripeClient($this->data['secretKey']);

        $response = $stripe->paymentIntents->retrieve($intent, []);

        if(isset($response['status']) && $response['status'] == "succeeded"){
            return response(['status' => 'success', 'response' => $response], 200);
        }else{
            return response(['status' => 'fail', 'response' => $response], 400);
        }
    }
}
