<?php

namespace App\Classes\External\Accounting;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

use QuickBooksOnline\API\Data\IPPCustomer;

use App\User;
use App\Classes\External\Accounting as Base;

class Quickbooks extends Base
{
	private $api = NULL;

	public function __construct(User $uo)
	{
		if (Auth::user())
			throw new \Exception('User logged in - *TODO* handle this');

		Auth::loginUsingId($uo->id);

		$this->api = app('Spinen\QuickBooks\Client');
	}

	public function getCustomers($refresh=FALSE): Collection
	{
		if ($refresh)
			Cache::forget(__METHOD__);

		return Cache::remember(__METHOD__,86400,function() {
			return collect($this->api->getDataService()->Query('SELECT * FROM Customer'));
		});
	}

	public function getInvoice(int $id,$refresh=FALSE)
	{
		if ($refresh)
			Cache::forget(__METHOD__.$id);

		return Cache::remember(__METHOD__.$id,86400,function() use ($id) {
			return $this->api->getDataService()->Query(sprintf("SELECT * FROM Invoice where id = '%s'",$id));
		});
	}

	public function getInvoices($refresh=FALSE): Collection
	{
		if ($refresh)
			Cache::forget(__METHOD__);

		return Cache::remember(__METHOD__,86400,function() {
			return collect($this->api->getDataService()->Query('SELECT * FROM Invoice'));
		});
	}

	public function updateCustomer(IPPCustomer $r,array $args)
	{
		$r->sparse = TRUE;

		foreach ($args as $k=>$v)
		{
			$r->{$k} = $v;
		}

		return $this->api->getDataService()->Update($r);
	}
}