<?php

namespace App\Jobs;

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

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

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{
		Log::info('Queued job hit - Sending Site User to Contact in Dynamics');
		$crmDynamics = app('MicrosoftDynamics');
		
		// Skip if Dynamics authentication failed (not in use)
		if (!$crmDynamics || !$crmDynamics->crmAuth->authHeader) {
			Log::info('Skipping Dynamics sync - authentication failed or not configured');
			return;
		}
		$user = $this->user;
		$site = Site::find($user->site_id);
		Log::info('loggiing site');
		Log::info($site);

		$client = Client::find($site->client_id);
		Log::info('loggiing client');
		Log::info($client);


		$fillable = ['site_id', 'first_name', 'last_name', 'email', 'phone', 'mobile', 'position', 'authority', 'dynamics_id'];

		$contactData = [
			'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'      => $client->dynamics_id,
			'telephone2'            => $user->phone2,
			'address1_line1'        => $site->address,
			'address1_city'         => $site->address2,
			'address1_postalcode'   => $site->postcode,
			'contactid'             => $user->dynamics_id,
		];

		$accountData = [
			'emailaddress1'       => $user->email,
			'accountid'           => $client->dynamics_id,
		];

		Log::info('logging siteUser data that will be sent to dynamics');
		Log::info($contactData);


		$typeOverrides = array('new_seraph_id' => 'int', 'parentcustomerid' => 'lookup');

		$success = $crmDynamics->accounts->updateAccount($accountData, $typeOverrides);
		$success = $crmDynamics->contacts->updateContact($contactData, $typeOverrides);

		Log::info('logging success');
		Log::info($success);



	}
}
