<?php


namespace App\Services\OnlinePayments;

use App\Models\PaymentManagement\PaymentMethod;
use App\Models\PaymentManagement\PaymentTransaction;
use App\Services\OmnipayService;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Storage;
use Omnipay\Omnipay;

class PayPalRest extends OmnipayService{

    use CanSaveResponseInJsonFile;

    const FILE_PATH = "omni-payments/responses/paypal-rest";

    /**
     * PayPalRest constructor.
     * @param PaymentMethod|null $paymentMethod
     */
    public function __construct(PaymentMethod $paymentMethod = null,$disk = "local"){
        parent::__construct("PayPal_Express");

        $this->disk = Storage::disk($disk);
        $client = new \Omnipay\Common\Http\Client(new Client( config('paypal-rest.guzzle.options',[])));

        $this->gateway = Omnipay::create('PayPal_Rest',$client);

        $this->gateway->setClientId(config('paypal-rest.client_id',env('PAYPAL_CLIENT_ID')));
        $this->gateway->setSecret(config('paypal-rest.client_secret',env('PAYPAL_CLIENT_SECRET')));
        $this->gateway->setTestMode(config('paypal-rest.test_mode',env('PAYPAL_CLIENT_SECRET')));

        if ($paymentMethod){
            $config = $paymentMethod->api_config;
            $active = $config['active'] ?? false;
            if ($config and $active){

                if (isset($config['client_id'])){
                    $this->gateway->setClientId($config['client_id']);
                }
                if (isset($config['client_secret'])){
                    $this->gateway->setSecret($config['client_secret']);
                }
                if (isset($config['test_mode'])){
                    $this->gateway->setTestMode($config['test_mode']);
                }
                //  $api = ["active"=> true,'username' => "username" ,"clientId" => "clientId" ,  "clientSecret" => "clientSecret"];
            }
        }
    }

    /** retourne le contu du fichier sur lequel l'api a repondu
     * @param $filePath
     * @return mixed|null
     */
    public function getTransactionStatus($filePath){
        $disk = $this->getDisk();
        if ( !empty($filePath) and $disk->exists($filePath)){
            return json_decode($disk->get($filePath),true);
        }
        return ['active' => "PENDING"];
    }

}
