<?php

namespace App\Console\Commands\Intuit;

use Illuminate\Console\Command;
use Intuit\Exceptions\NotTokenException;
use Intuit\Traits\ProviderTokenTrait;

use App\Models\Product;

/**
 * Return a list of products and their accounting id
 */
class ItemList extends Command
{
	use ProviderTokenTrait;

	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'accounting:item:list'
		.' {user? : User Email}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Synchronise items with accounting system';

	/**
	 * Execute the console command.
	 *
	 * @return int
	 * @throws NotTokenException
	 */
	public function handle()
	{
		$to = $this->providerToken($this->argument('user'));

		// Current Products used by services
		$products = Product::select(['products.*'])
			->distinct('products.id')
			->join('services',['services.product_id'=>'products.id'])
			->where('services.active',TRUE)
			->get();

		foreach ($products as $po) {
			if (! $x=$po->provider_ref($to->provider))
				$this->error(sprintf('Product [%03d](%s) doesnt have accounting set',$po->id,$po->name));

			else
				$this->info(sprintf('Product [%03d](%s) set to accounting [%s]',$po->id,$po->name,$x));
		}

		return self::SUCCESS;
	}
}