<?php

namespace App\Jobs;

use App\Jobs\Job;
use App\Modules\Clients\SiteUser;
use App\Modules\Clients\Site;
use App\Modules\Clients\Client;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class sendClientToDynamicsAccount extends Job implements ShouldQueue
{
	use InteractsWithQueue, SerializesModels;
	protected $client;
	/**
	 * Create a new job instance.
	 *
	 * @return void
	 */
	public function __construct(Client $client)
	{
		$this->client = $client;
	}

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{
		$client = $this->client;
		$crmDynamics = app('MicrosoftDynamics');

		$data   = [
			'name'          => $client->name,
			'websiteurl'    => $client->website,
			'new_seraph_id' => $client->id,
		];


		if ($site = $client->sites()->has('users')->first()) {
			$data = array_merge($data, [
				'address1_line1'      => $site->address,
				'address1_city'       => $site->address2,
				'address1_postalcode' => $site->postcode,
				'address1_telephone1' => $site->primary_phone,
				'telephone1'          => $site->primary_phone,
			]);
		}

		if ($site && $siteUser = $site->users()->first()) {
			$data = array_merge($data, [
				'emailaddress1' => $siteUser->email,
			]);
		}
		//Call update or create? Do we have a dynamics_id already?
		$newClient = true;
		if($client->dynamics_id != null)
		{
			$data['accountid'] = $client->dynamics_id;
			$newClient = false;


		}

		$typeOverrides = array('new_seraph_id' => 'int');

		if($newClient == true)
		{
			// dd($data);
			Log::info("sending data to new account");
			Log::info($data);
			$dynamics_id = $crmDynamics->accounts->createAccount($data, $typeOverrides);
			// If this is a new customer, then store
			// the dynamics_id locally
			if (! $client->dynamics_id) {
				$client->dynamics_id = $dynamics_id;
				//   $susers = $this->getSiteUsers($client);
				//   Log::info("\n logging susers | array returned from getSiteUsers()");
				//   Log::info($susers);
				//   $this->sendSiteusersAsContactsToDynamics($this->getSiteUsers($client), $client, $crmDynamics);
				$client->save();
				$sites = $client->sites()->has('users')->get();
				foreach($sites as $site){
					if ($site && $siteUsers = $site->users()->get()) {
						Log::info("logging site users");
						Log::info($siteUsers);
						//   dd($siteUsers);
						foreach ($siteUsers as $user) {
							$site = $user->site;
							Log::info("Syncing site users");
							Log::info("Getting account for " . $user->first_name . " " . $user->last_name . " at " . $client->name);
							$data = [
								'firstname'           => $user->first_name,
								'lastname'            => $user->last_name,
								'emailaddress1'       => $user->email,
								'telephone1'          => $user->phone,
								'mobilephone'         => $user->mobile,
								'new_seraph_id'       => $user->id,
								'new_seraph_model'    => 'siteuser',
								'parentcustomerid'    => $dynamics_id,
								'telephone2'          => $site->primary_phone,
								'address1_line1'      => $site->address,
								'address1_city'       => $site->address2,
								'address1_postalcode' => $site->postcode,
							];
							$typeOverrides = array('new_seraph_id' => 'int', 'parentcustomerid' => 'lookup');
							$siteUserDynamicsId = $crmDynamics->contacts->createContact($data, $typeOverrides);
							$user->dynamics_id = $siteUserDynamicsId;
							$user->save();
						}
					}
				}
			}
		}
		else {
			$success = $crmDynamics->accounts->updateAccount($data, $typeOverrides);

		}


	}
}
