<?php

namespace App\Classes\Payments;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

use App\Classes\Payments;

class Ezypay extends Payments
{
	protected function connect(string $url,array $args=[])
	{
		if ($x=$this->mustPause()) {
			Log::error('API Throttle, waiting .',['m'=>__METHOD__]);
			sleep($x);
		}

		$client = $this->getClient(config('services.ezypay.base_uri'));

		$result = $client->request('GET',$url.($args ? '?'.http_build_query($args) : ''),[
			'headers' => [
				'Authorization'=>'Basic '.base64_encode(config('services.ezypay.token_user').':'),
				'Accept'=>'application/json',
			],
		]);

		$api_remain = Arr::get($result->getHeader('X-RateLimit-Remaining'),0);
		$api_reset = Arr::get($result->getHeader('X-RateLimit-Reset'),0);

		if ($api_remain == 0) {
			Log::error('API Throttle.',['m'=>__METHOD__]);
			Cache::put('api_throttle',$api_reset,now()->addSeconds($api_reset));
		}

		return json_decode($result->getBody()->getContents());
	}

	public function getCustomer(string $id)
	{
		return Cache::remember(__METHOD__.$id,86400,function() use ($id) {
			return collect($this->connect('accounts/customerid/'.$id));
		});
	}

	public function getCustomers(): Collection
	{
		return Cache::remember(__METHOD__,86400,function() {
			return collect($this->connect('customers?pageSize=100'));
		});
	}

	public function getDebits($opt=[]): Collection
	{
		return Cache::remember(__METHOD__.http_build_query($opt),86400,function() use ($opt) {
			return Collect($this->connect('debits'.($opt ? '?'.http_build_query($opt) : '')));
		});
	}

	public function getSettlements($opt=[]): Collection
	{
		return Cache::remember(__METHOD__.http_build_query($opt),86400,function() use ($opt) {
			return Collect($this->connect('settlements/'.config('services.ezypay.guid').($opt ? '?'.http_build_query($opt) : '')));
		});
	}
}