<?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'
		.' {siteid : Site ID}'
		.' {supplier : Supplier Name}'
		.' {--f|forceprod : Force Prod API on dev environment}';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
		Config::set('site',Site::findOrFail($this->argument('siteid')));
		$so = Supplier::where('name',$this->argument('supplier'))->singleOrFail();

		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()) {
				//dump($x->suppliers->first());
				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));
			}
		}
    }
}