<?php

namespace App\Jobs;

use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

use App\Classes\External\Payments;
use App\Models\{Account,Checkout,Payment};

/**
 * Import payments from payment providers
 *
 * @package App\Jobs
 */
final class PaymentsImport implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	private const LOGKEY = 'JPI';

	protected Payments $o;			// The payment provider we are updating from
	private $class_prefix = 'App\Classes\External\Payments\\';

	public function __construct(Payments $o)
	{
		$this->o = $o;
	}

	public function handle()
	{
		Log::info(sprintf('%s:Importing Payment Date from [%s]',self::LOGKEY,get_class($this->o)));

		// Get our checkout IDs for this plugin
		$cos = Checkout::where('plugin',config('services.ezypay.plugin'))->pluck('id');

		foreach ($this->o->getCustomers() as $c) {
			if ($c->BillingStatus == 'Inactive') {
				Log::debug(sprintf('%s:Ignoring INACTIVE: [%s] %s %s',self::LOGKEY,$c->EzypayReferenceNumber,$c->Firstname,$c->Surname));

				continue;
			}

			// Load Account Details from ReferenceId
			$ao = Account::where('site_id',(int)substr($c->ReferenceId,0,2))
				->where('id',(int)substr($c->ReferenceId,2,4))
				->first();

			if (! $ao) {
				Log::error(sprintf('%s:Missing: [%s] %s %s (%s)',self::LOGKEY,$c->EzypayReferenceNumber,$c->Firstname,$c->Surname,$c->ReferenceId));
				continue;
			}

			// Find the last payment logged
			$last = Carbon::create(Payment::whereIN('checkout_id',$cos)->where('account_id',$ao->id)->max('paid_at'));

			$o = $this->o->getDebits([
				'customerId'=>$c->Id,
				'dateFrom'=>$last->format('Y-m-d'),
				'dateTo'=>$last->addQuarter()->format('Y-m-d'),
				'pageSize'=>100,
			]);

			Log::info(sprintf('%s:Loaded [%d] payments for account: [%s]',self::LOGKEY,$o->count(),$ao->id));

			// Load the payments
			if ($o->count()) {
				foreach ($o->reverse() as $p) {
					$pd = Carbon::createFromTimeString($p->Date);

					// If not success, ignore it.
					if ($p->Status != 'Success') {
						Log::alert(sprintf('%s:Payment not successful: [%s] %s %s (%s) [%s]',self::LOGKEY,$pd->format('Y-m-d'),$ao->id,$p->Id,$p->Amount,$p->Status));
						continue;
					}

					$lp = $ao->payments->last();

					if ($lp AND (($pd == $lp->paid_at) OR ($p->Id == $lp->checkout_data))) {
						Log::alert(sprintf('%s:Payment Already Recorded: [%s] %s %s (%s)',self::LOGKEY,$pd->format('Y-m-d'),$ao->id,$p->Id,$p->Amount));
						continue;
					}

					// New Payment
					$po = new Payment;
					$po->active = TRUE;
					$po->site_id = 1; // @todo
					$po->paid_at = $pd;
					$po->checkout_id = '999'; // @todo
					$po->checkout_data = $p->Id;
					$po->total_amt = $p->Amount;
					$ao->payments()->save($po);

					Log::info(sprintf('%s:Recorded: Payment for [%s] %s %s (%s) on %s',self::LOGKEY,$c->EzypayReferenceNumber,$c->Firstname,$c->Surname,$po->id,$pd));
				}
			}
		}
	}
}