<?php

namespace App\Jobs;

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

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

	/**
	 * Execute the job.
	 *
	 * @return void
	 */
	public function handle()
	{
		Log::info("Queue job hit sendCustomerToDynamicsContact");
		
		try {
			$customer = $this->customer;
			Log::info($customer);
			$crmDynamics = app('MicrosoftDynamics');

			$data = [
				'firstname'           => $customer->first_name,
				'lastname'            => $customer->last_name,
				'emailaddress1'       => $customer->email,
				'telephone1'          => $customer->phone,
				'mobilephone'         => $customer->mobile,
				'telephone2'          => $customer->phone2,
				'address1_line1'      => $customer->address,
				'address1_line2'      => $customer->address2,
				'address1_stateorprovince'     => $customer->county,
				'address1_city'       => $customer->town,
				'address1_postalcode' => $customer->postcode,
				'new_seraph_id'       => $customer->id,
				'new_seraph_model'    => 'customer',
			];

			//Call update or create? Do we have a dynamics_id already?
			$newCustomer = true;
			if($customer->dynamics_id != null)
			{
				$data['contactid'] = $customer->dynamics_id;
				$newCustomer = false;
			}

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

			if($newCustomer == true) {
				$dynamics_id = $crmDynamics->contacts->createContact($data, $typeOverrides);
				// If this is a new customer, then store
				// the dynamics_id locally
				if (! $customer->dynamics_id) {
					$customer->dynamics_id = $dynamics_id;
					$customer->save();
				}
				Log::info("Customer synced to Dynamics CRM successfully", ['customer_id' => $customer->id, 'dynamics_id' => $dynamics_id]);
			}
			else {
				$success = $crmDynamics->contacts->updateContact($data, $typeOverrides);
				Log::info("Customer updated in Dynamics CRM successfully", ['customer_id' => $customer->id]);
			}

		} catch (\Exception $e) {
			Log::error("Failed to sync customer to Dynamics CRM", [
				'customer_id' => $this->customer->id,
				'error' => $e->getMessage(),
				'trace' => $e->getTraceAsString()
			]);
		}
	}
}
