<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

use App\Events\ProviderPaymentCreated as Event;
use App\Jobs\AccountingPaymentSync as Job;
use App\Models\{ProviderOauth,Site,User};

class ProviderPaymentCreated
{
	private const LOGKEY = 'LPC';

	/**
	 * Handle the event.
	 *
	 * @param Event $event
	 * @return void
	 */
	public function handle(Event $event)
	{
		$site = Site::findOrFail(1); // @todo This shouldnt be hard coded
		Config::set('site',$site);

		$uo = User::findOrFail(1);	// @todo This shouldnt be hard coded

		$so = ProviderOauth::where('name',$event->provider)->singleOrFail();
		if (! ($to=$so->token($uo)))
			abort(500,sprintf('Unknown Tokens for [%s]',$uo->email));

		$api = $to->API();
		$acc = $api->getPayment($event->paymentData['id']);

		Job::dispatch($to,$acc);
	}
}