<?php

namespace App\Microsoft\Dynamics;

use App\Modules\Clients\Customer;
use App\Modules\Clients\SiteUser;
use App\Modules\Clients\Site;
use Illuminate\Support\Facades\Log;

class Contact
{
	/**
	* All properties used by default.
	*
	* @var array
	*/
	protected $attributes = [
		'contactid'           => null,
		'firstname'           => null,
		'lastname'            => null,
		'emailaddress1'       => null,
		'telephone1'          => null,
		'mobilephone'         => null,
		'telephone2'          => null,
		'address1_line1'      => null,
		'address1_line2'      => null,
		'address1_county'     => null,
		'address1_city'       => null,
		'address1_postalcode' => null,
		'new_seraph_id'       => null,
		'new_seraph_model'    => null,
	];

	/**
	* Create a new instance of the Contact entity.
	*
	* @param array $attributes
	*/
	public function __construct($attributes = [])
	{
		$this->attributes = array_merge($this->attributes, $attributes);
	}

	/**
	* Creates a new instance of a customer.
	*
	* @return \App\Modules\Clients\Customer
	*/
	public function toCustomer()
	{
		Log::info("INCOMING === Dynamics toCustomer route hit. Attributes:");
		Log::info($this->attributes);

		$customer = null;
		$siteUser = null;
		//If sent with model (after creation from scratch, find it based on model and id)
		if (isset($this->attributes['new_seraph_model'])) {
			if ($this->attributes['new_seraph_model'] == 'customer') {
				Log::info("new_seraph_model == customer");
				$customer = Customer::where('dynamics_id', $this->attributes['contactid'])
				->orWhere('id', $this->attributes['new_seraph_id'])
				->first();
			}

			if ($this->attributes['new_seraph_model'] == 'siteuser') {
				Log::info("new_seraph_model == siteuser");
				$siteUser = SiteUser::where('dynamics_id', $this->attributes['contactid'])
				->orWhere('id', $this->attributes['new_seraph_id'])
				->first();
			}
		}
		else {
			//Not sent with model, probably updating an existing customer or siteuser. search both models to find the unique id.
			// Log::info("not set new serpah model CUSTOMER ");
			$customer = Customer::where('dynamics_id', $this->attributes['contactid'])
			->orWhere('id', $this->attributes['new_seraph_id'])
			->first();

		}


		if (! $customer) {
			// Still not found. Create a new custoenmr.
			Log::info("customer NOT found");
			$customer = new Customer;

			// Log::info("not set new_seraph_model SITEUSER");
			$siteUser = SiteUser::where('dynamics_id', $this->attributes['contactid'])
			->orWhere('id', $this->attributes['new_seraph_id'])
			->first();

			// if (!$siteUser && $this->attributes['parentcustomerid']) {
			// 	$siteUser = new SiteUser;
			//
			// 	$siteUser->fill([
			// 		'first_name'  => $this->attributes['firstname'],
			// 		'last_name'   => $this->attributes['lastname'],
			// 		'email'       => $this->attributes['emailaddress1'],
			// 		'phone'       => $this->attributes['telephone1'],
			// 		'mobile'      => $this->attributes['mobilephone'],
			// 		'phone2'      => $this->attributes['telephone2'],
			// 		'address'     => $this->attributes['address1_line1'],
			// 		'address2'    => $this->attributes['address1_line2'],
			// 		'county'      => $this->attributes['address1_county'],
			// 		'town'        => $this->attributes['address1_city'],
			// 		'postcode'    => $this->attributes['address1_postalcode'],
			// 		'dynamics_id' => $this->attributes['contactid'],
			// 	]);
			// }
			// else
			if ($siteUser) {
				Log::info("siteUser found");
				Log::info("logging siteuser before filling the siteUser");
				Log::info($siteUser);

				// get site associated with users
				$userSite = Site::find($siteUser->site_id);
				Log::info("logging userSite");
				Log::info($userSite);

				// fill any changes here
				$userSite->fill([
					'address'  		=> ($this->attributes['address1_line1'] == null) ? $userSite->address : $this->attributes['address1_line1'],
					'address2'  	=> ($this->attributes['address1_city'] == null) ? $userSite->address2 : $this->attributes['address1_city'],
					'postcode'  	=> ($this->attributes['address1_postalcode'] == null) ? $userSite->postcode : $this->attributes['address1_postalcode'],
					'primary_phone' => ($this->attributes['telephone1'] == null) ? $userSite->primary_phone : $this->attributes['telephone1'],
				]);
				$userSite->save();

				$siteUser->fill([
					'first_name'  => ($this->attributes['firstname'] == null) ? $siteUser->first_name : $this->attributes['firstname'],
					'last_name'   => ($this->attributes['lastname'] == null) ? $siteUser->last_name : $this->attributes['lastname'],
					'email'       => ($this->attributes['emailaddress1'] == null) ? $siteUser->email : $this->attributes['emailaddress1'],
					'phone'       => ($this->attributes['telephone2'] == null) ? $siteUser->phone : $this->attributes['telephone2'],
					'mobile'      => ($this->attributes['mobilephone'] == null) ? $siteUser->mobile : $this->attributes['mobilephone'],
					'dynamics_id' => ($this->attributes['contactid'] == null) ? $siteUser->dynamics_id : $this->attributes['contactid'],
				]);
				
				Log::info("logging returned siteuser before return");
				Log::info($siteUser);
				return $siteUser;
			}
			else {
				Log::info("customer NOT and site user NOT found");
				$customer = new Customer;
			}

		}
		else {
			Log::info("customer found with this id:" . $customer->id);
		}


		//$updateArray= array_filter($this->attributes, 'strlen');
		// Log::info($this->attributes );
		// foreach ($this->attributes as $key => $value) {
 	// 		$this->{$key} = empty($value) ? unset($this->{$key}) : $value;
		// 	Log::info($key);
        // }
		// $this->attributes = array_filter($this->attributes, function($var){return !is_null($var);} );
		Log::info("logging customer");

		Log::info($customer);
		Log::info("logging attibutes");

		Log::info($this->attributes);

		// the customer has to be split due inconstent object parameters from dynamics
		// (see the comment above 2 if statements below)
		$customer->fill([
			'first_name'  => ($this->attributes['firstname'] == null) ? $customer->first_name : $this->attributes['firstname'],
			'last_name'   => ($this->attributes['lastname'] == null) ? $customer->last_name : $this->attributes['lastname'],
			'email'       => ($this->attributes['emailaddress1'] == null) ? $customer->email : $this->attributes['emailaddress1'],
			'phone'       => ($this->attributes['telephone1'] == null) ? $customer->phone : $this->attributes['telephone1'],
			'mobile'      => ($this->attributes['mobilephone'] == null) ? $customer->mobile : $this->attributes['mobilephone'],
			'phone2'      => ($this->attributes['telephone2'] == null) ? $customer->phone2 : $this->attributes['telephone2'],
			'address'     => ($this->attributes['address1_line1'] == null) ? $customer->address : $this->attributes['address1_line1'],
			'address2'    => ($this->attributes['address1_line2'] == null) ? $customer->address2 : $this->attributes['address1_line2'],
			'town'        => ($this->attributes['address1_city'] == null) ? $customer->town : $this->attributes['address1_city'],
			'postcode'    => ($this->attributes['address1_postalcode'] == null) ? $customer->postcode : $this->attributes['address1_postalcode'],
			'dynamics_id' => ($this->attributes['contactid'] == null) ? $customer->dynamics_id : $this->attributes['contactid'],
		]);

		// don't ask me why but sometimes dynamics sends address1_stateorprovince and at other times address1_county
		// these 2 if statements handle that
		// the results are shoved back into $customer
		if(array_key_exists('address1_stateorprovince', $this->attributes)) {
			$customer->fill([
			'county'      => ($this->attributes['address1_stateorprovince'] == null) ? $customer->county : $this->attributes['address1_stateorprovince']
			]);
		}
		if(array_key_exists('address1_county', $this->attributes)) {
			$customer->fill([
			'county'      => ($this->attributes['address1_county'] == null) ? $customer->county : $this->attributes['address1_county'],
			]);
		}
		Log::info("customer");
		Log::info($customer);
		Log::info("customer filtered");
		Log::info($customer);
		return $customer;
	}
}
