<?php
class Client
{
	// Properties of the class:
	var $hddnClientId, $edtClientName, $edtClientSurname, $txtAddressId, $edtClientCell, $edtClientPhone, 
	$edtClientEmail, $addressLng, $addressLat, $selAddressId, $buildingList, $distance, $traveltime, $txtAddressNote, 
	$txtClientNotes, $txtClientBookingNote;
	
	function __construct(){}
	function __destruct(){}

	function addClient($silent = false)
	{
		global $sableDB;
		/**
		if (!SableValidationFunctions::validateEmail($this->edtClientEmail)) 
				SableSystem::ajaxResponse(false, "", "The email address provided does not seem to be valid.", 5, "edtClientEmail", false, "edtClientEmail");
		**/
		if (empty($this->edtClientCell) && empty($this->edtClientPhone) && empty($this->edtClientEmail))
		{
			if (!SableValidationFunctions::validateEmail($this->edtClientEmail)) 
					SableSystem::ajaxResponse(false, "", "Either a phone no. or email should at least be provided.", 5, "edtClientCell", false, "edtClientCell");		
		}
		
		$this->selAddressId = SableDBFunctions::storeAddress($this->txtAddressId, $this->addressLng, $this->addressLat);
		if ($this->selAddressId)
		{
			//get coords for the company:
			$coyAddressId = $sableDB->getValue('select address.address_id
										from company 
										inner join address on address.address_id = company.address_id 
										where company.company_id = '.COMPANY_ID);
			$distanceMatrix		= SableGeneralFunctions::getDistanceMatrix($coyAddressId, $this->selAddressId);
			$this->distance		= $distanceMatrix['distance']; //value in meters 7771 = 7.8km's!
			$this->traveltime	= $distanceMatrix['duration']; //value in seconds 722 = 12 minutes!
		}
		
		$this->edtClientEmail	= strtolower($this->edtClientEmail);
		$this->edtClientName	= SableGeneralFunctions::formatName($this->edtClientName);
		$this->edtClientSurname	= SableGeneralFunctions::formatName($this->edtClientSurname);
		$this->edtClientPhone	= SableGeneralFunctions::getNumericPhoneNo($this->edtClientPhone);
		$this->edtClientCell	= SableGeneralFunctions::getNumericPhoneNo($this->edtClientCell);
		
		if (empty($this->hddnClientId))
		{
			if ($this->checkClientExists())
				SableSystem::ajaxResponse(false, "", "This Client has already been added.", 5, "edtClientName", false, "edtClientName");
			$this->loadClient();
		}
		else
		{
			$this->updateClient($silent);
		}
	}

	function loadClient()
	{
		global $sableDB;
		$this->hddnClientId = 0;
		$insertQuery = "INSERT INTO client (
						client_name, client_surname, address_id, client_distance, client_travel_time, client_cell, client_phone, 
						client_email, client_address_note, client_booking_note
						) VALUES (
						'".addslashes($this->edtClientName)."',
						'".addslashes($this->edtClientSurname)."',
						'".$this->selAddressId."', 
						".intval($this->distance).", 
						".intval($this->traveltime).",
						'".$this->edtClientCell."',
						'".$this->edtClientPhone."',
						'".$this->edtClientEmail."', 
						'".addslashes(strip_tags($this->txtAddressNote))."',
						'".addslashes(strip_tags($this->txtClientBookingNote))."')";
		
		$res=$sableDB->updateQuery($insertQuery);
		//Check if the Client details were successfully added:
		if ($res)
		{
			$this->setClientId();
			SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 
											  'New Client added: '.$this->edtClientName.' '.$this->edtClientName, $this->hddnClientId);
			$this->addBuildings();
			SableSystem::ajaxResponse(true, '/booking/add.php+'.$this->hddnClientId, 'The Client was successfully added.', 0, "", 0, "");
			//https://champ.jona.co.za/index.php?/client/index.php ????
		}
		else
			SableSystem::ajaxResponse(false, "", "Add of a new Client failed. Please try again or contact support.", 
				5, "edtClientName", false, "edtClientName");
	}

	function updateClient($silent = false)
	{
		global $sableDB;
		$code = SableSystem::sableDecode($this->hddnClientId);
		$updateQuery = "UPDATE client set 
						client_name = '".addslashes($this->edtClientName)."', 
						client_surname = '".addslashes($this->edtClientSurname)."', 
						address_id = '".$this->selAddressId."', 
						client_distance = ".intval($this->distance).", 
						client_travel_time = ".intval($this->traveltime).", 
						client_cell = '".$this->edtClientCell."', 
						client_phone = '".$this->edtClientPhone."', 
						client_email = '".$this->edtClientEmail."', 
						client_address_note = '".addslashes(strip_tags($this->txtAddressNote))."', 
						client_notes = '".addslashes(strip_tags($this->txtClientNotes))."', 
						client_booking_note = '".addslashes(strip_tags($this->txtClientBookingNote))."', 
						last_update = '".date('Y-m-d H:i:s')."' 
						where client_id = '".$code."'";
		$res=$sableDB->updateQuery($updateQuery);
		//Check if the details were successfully updated:
		if ($res)
		{
			SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 
											  'Client details modified: '.$this->edtClientName.' '.$this->edtClientName, $code);
			if ($silent) 
				return 1;
			else
				SableSystem::ajaxResponse(true, '/client/', 'The Client was successfully updated.', 0, "", 0, "");
		}
		else 
		{
			if ($silent)
				return 0;
			else
				SableSystem::ajaxResponse(false, "", "Modification of the Client failed. Please try again or contact support.", 
				5, "edtClientName", false, "edtClientName");
		}
	}

	private function getClientId()
	{
		global $sableDB;
		$sql = "select 
				client_id from 
				client where 
				(client_email = '".$this->edtClientEmail."') and 
				(client_cell = '".$this->edtClientCell."') and 
				(client_phone = '".$this->edtClientPhone."') and (client_deleted = 0)";
		return $sableDB->getValue($sql);
	}

	private function checkClientExists()
	{
		$cid = $this->getClientId();
		if (!empty($cid)) return true; else return false;
	}

	private function setClientId()
	{
		$this->hddnClientId = $this->getClientId();
	}

	function viewClient()
	{
		$url = '/client/view.php?'.SableSystem::sableDecode($this->hddnClientId);
		SableSystem::ajaxPageRedirect($url);
	}

	function editClient()
	{
		$url = '/client/edit.php?'.SableSystem::sableDecode($this->hddnClientId);
		SableSystem::ajaxPageRedirect($url);
	}
	
	function viewBuildings()
	{
		global $sableDB;
		$count = $sableDB->getValue('select count(*) from building where client_id = '.$this->hddnClientId);
		if ($count)
			$url = '/building/index.php?'.SableSystem::sableDecode($this->hddnClientId);
		else
			$url = '/building/add.php?'.SableSystem::sableDecode($this->hddnClientId);
		SableSystem::ajaxPageRedirect($url);
	}
	
	function viewTxns()
	{
		global $sableDB;
		SableDBFunctions::clearListQueryFilter("finance");
		$count = $sableDB->getValue('select count(*) from finance where client_id = '.$this->hddnClientId);
		if ($count)
			$url = '/finance/index.php?'.SableSystem::sableDecode($this->hddnClientId);
		else
			$url = '/finance/add.php?'.SableSystem::sableDecode($this->hddnClientId);
		SableSystem::ajaxPageRedirect($url);
	}
	
	function viewHistory()
	{
		global $sableDB;
		$url = '/booking/history.php?'.SableSystem::sableDecode($this->hddnClientId);
		SableSystem::ajaxPageRedirect($url);
	}

	function deleteClient()
	{
		global $sableDB;
		$code = SableSystem::sableDecode($this->hddnClientId);
		$name = trim($sableDB->getValue('select concat(client_name, " ", client_surname) from client where client_id = '.$code));
		
		$cnt = $sableDB->getValue("select count(*) from client where client_id = ".$code);
		if ($cnt <= 0)
			SableSystem::ajaxResponse(false, "", "Delete failed - invalid Client selected.", 
				5, "edtClientName", false, "edtClientName");
		else
		{
			$sql = "update client set client_deleted = 1 where client_id = '".$code."'";
			$res = $sableDB->updateQuery($sql);
			if ($res)
			{
				//Update the Audit records
				SableDBFunctions::loadAuditDetail($_SESSION["user"]["user_code"], 'Client "'.$name.'" was deleted.', $code);
				
				/** RECORDS NO LONGER PHYSICALLY DELETED
				//we need to delete all bookings for this client:
				$sql = "delete `standing_appointment`, `standing_appointment__dow`, `standing_appointment__dom` 
						from standing_appointment 
						left join standing_appointment__dow on standing_appointment__dow.sa_id = standing_appointment.sa_id  
						left join standing_appointment__dom on standing_appointment__dom.sa_id = standing_appointment.sa_id
						where client_id = ".$code;
				$res = $sableDB->updateQuery($sql);
				if ($res) SableDBFunctions::loadAuditDetail($_SESSION["user"]["user_code"], 'Client "'.$name.'" standing appointments deleted.', $code);
				**/ 
				
				$sql = 'update booking set booking_deleted = 1 where client_id = '.$code;
				/** RECORDS NO LONGER PHYSICALLY DELETED
				$sql = "delete `booking`, `booking__service` 
						from booking  
						inner join booking__service on booking__service.booking_id = booking.booking_id 
						where client_id = ".$code;
				**/
				$res = $sableDB->updateQuery($sql);
				if ($res) SableDBFunctions::loadAuditDetail($_SESSION["user"]["user_code"], 'Client "'.$name.'" bookings deleted.', $code);
				
				/** RECORDS NO LONGER PHYSICALLY DELETED
				//we need to delete all of this clients buildings also:
				$sql = 'delete from building where client_id = '.$code;
				$sableDB->updateQuery($sql);
				SableDBFunctions::loadAuditDetail($_SESSION["user"]["user_code"], 'Client "'.$name.'" buildings deleted.', $code);
				**/

				SableSystem::ajaxPageRedirect('/client/','Client "'.$name.'" and related bookings were successfully deleted.');
			}
			else
			SableSystem::ajaxResponse(false, "", "System error: The Client failed to ".$name.". Please try again later or contact support.", 
				5, "edtClientName", false, "edtClientName");
		}
	}
	
	function addBuildings()
	{
		global $sableDB;
		$buildingName = null;

		foreach($this->buildingList as $buildingItem)
		{
			$building = $buildingItem['tag'];
			$buildNotes	= empty($building['edtBuildingNotes']) ? "NULL" : "'".$building['edtBuildingNotes']."'";
			$now	= new DateTime();
			$buildingName= SableGeneralFunctions::formatName($building['edtBuildingName']);
			$qry	= "INSERT INTO building 
						(client_id, area_id, building_name, building_special_instructions, building_notes, user_code, building_ip, building_date, last_update) 
						VALUES 
						({$this->hddnClientId}, {$building['selAreaId']}, '{$buildingName}', 
						'".addslashes($building['txtBuildingNeeds'])."', {$buildNotes}, {$_SESSION['user']['user_code']}, 
						'".SableGeneralFunctions::getRealIpAddr()."',  '".date('Y-m-d H:i:s')."', '".date('Y-m-d H:i:s')."')";
			$res=$sableDB->updateQuery($qry);
			//Check if the Building details were successfully added:
			if ($res)
			{
				$buildingid = $sableDB->getValue('select building_id from building where client_id = '.$this->hddnClientId.' and 
											area_id = '.$building['selAreaId'].' and building_name = "'.$buildingName.'" and 
											building_date = "'.$now->format('Y-m-d H:i:s').'"');
				SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 'New Building added: '.$buildingName, $buildingid);
			}
			unset($now);
		}
	}
	
	function addBooking()
	{
		$url = '/booking/add.php?'.SableSystem::sableDecode($this->hddnClientId);
		$_SESSION['module']['parent'] = 'client'; //tells booking this request comes from the client module
		SableSystem::ajaxPageRedirect($url);
	}

} //classClient