<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;

use App\Models\{Site,Supplier,User};

class SupplierAccountSync extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'supplier:account:sync'
		.' {supplier : Supplier Name}'
		.' {--f|forceprod : Force Prod API on dev environment}'
		.' {--s|site : Site ID}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Sync accounts with a supplier';

	/**
	 * Execute the console command.
	 *
	 * @return int
	 * @note Suppliers are now associated with accounts, so this needs to be updated
	 */
	public function handle()
	{
		Config::set(
			'site',
			$this->option('site')
				? Site::findOrFail($this->option('site'))
				: Site::where('url',config('app.url'))->sole()
		);

		$so = Supplier::where('name','ilike',strtolower($this->argument('supplier')))->sole();

		foreach ($so->API($this->option('forceprod'))->getCustomers(['fetchall'=>true]) as $customer) {
			// Check if we have this customer already (by ID)
			if ($so->users->where('pivot.id',$customer->id)->count()) {
				$this->info(sprintf('User already linked (%s:%s)',$customer->id,$customer->email));

			} elseif ($x=User::where('email',$customer->email)->single()) {
				if ($x->suppliers->count()) {
					$this->alert(sprintf('User [%d:%s] already linked to this supplier with ID (%s)',$customer->id,$customer->email,$x->suppliers->first()->pivot->id));

				} else {
					$this->warn(sprintf('User [%d:%s] has same email (%s:%s) - Linked',$x->id,$x->email,$customer->id,$customer->email));

					$so->users()->syncWithoutDetaching([
						$x->id => [
							'id'=>$customer->id,
							'site_id'=>$x->site_id,				// @todo See if we can have this handled automatically
							'created_at'=>Carbon::create($customer->date_added),
						]
					]);
				}

			} else {
				$this->error(sprintf('User doesnt exist with email (%s:%s)',$customer->id,$customer->email));
			}
		}

		return self::SUCCESS;
	}
}