<?php
require_once(__DIR__."/../includes/sysinit.php");

class Client
{
	// Properties of the class:
	var $hddnClientId, $edtClientName, $edtClientSurname, $selIdTypeId, $edtClientIdNo, $selClientTypeId, $cbClientAddrBill, $hddnAddressId, 
		$edtClientPhone, $edtClientPhoneAlt, $edtClientEmail, $edtClientNote, $selGenderId, $edtClientBusinessName, $edtClientVatNo, $edtClientRegNo, 
		$cbClientContract, $hddnClientDeleted, $hddnLastUpdate, $addresses = [], $buildings = [], $buildingAddresses = [];

	private $sableDB, $uc, $ts, $ip;

	function __construct()
	{
		$this->sableDB = new SableDB;
	}

	function __destruct()
	{
		unset($this->sableDB);
	}

	function addClient()
	{
		$this->uc = $_SESSION['user']['user_code'];
		$this->ts = date('Y-m-d H:i:s');
		$this->ip = SableGeneralFunctions::getRealIpAddr();

	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->hddnClientId))
		{
			if ($this->checkClientExists())
			SableSystem::ajaxResponse(false, "", "This Client has already been added.", 
				5, "hddnClientId", false, "hddnClientId");
			$this->loadClient();
		}
		else
		{
			$this->updateClient();
		}
	}

	function loadClient()
	{
		$this->saveAddresses();
        
        
		$insertQuery = "INSERT INTO client (
						client_name, client_surname, id_type_id, client_id_no, client_type_id, client_addr_bill, address_id, client_phone, client_phone_alt, client_email, client_note, gender_id, client_business_name, client_vat_no, client_reg_no, client_contract, client_deleted, last_update
						) VALUES (
						'".SableGeneralFunctions::formatName($this->edtClientName)."',
						'".SableGeneralFunctions::formatName($this->edtClientSurname)."',
						'{$this->selIdTypeId}',
						'{$this->edtClientIdNo}',
						'{$this->selClientTypeId}',
						'{$this->cbClientAddrBill}',
						'{$this->hddnAddressId}',
						'{$this->edtClientPhone}',
						'{$this->edtClientPhoneAlt}',
						'{$this->edtClientEmail}',
						'".SableGeneralFunctions::formatName($this->edtClientNote)."',
						'{$this->selGenderId}',
						'".SableGeneralFunctions::formatName($this->edtClientBusinessName)."',
						'{$this->edtClientVatNo}',
						'{$this->edtClientRegNo}',
						{$this->cbClientContract},
						'{$this->hddnClientDeleted}',
						'{$this->hddnLastUpdate}')";
		$res=$this->sableDB->updateQuery($insertQuery);
		//Check if the Client details were successfully added:
		if ($res)
		{
			$this->setClientId();
			SableDBFunctions::loadAuditDetail($this->uc, 'New Client added: '.$this->hddnClientId, $this->hddnClientId);
			SableSystem::ajaxResponse(true, '/client/', 'The Client was successfully added.', 0, "", 0, "");
		}
		else
			SableSystem::ajaxResponse(false, "", "Add of a new Client failed. Please try again or contact support.", 
				5, "hddnClientId", false, "hddnClientId");
	}

	function updateClient()
	{
		$code = SableSystem::sableDecode($this->hddnClientId);
		$updateQuery = "UPDATE client set 
						client_name = '".SableGeneralFunctions::formatName($this->edtClientName)."', 
						client_surname = '".SableGeneralFunctions::formatName($this->edtClientSurname)."', 
						id_type_id = '{$this->selIdTypeId}', 
						client_id_no = '{$this->edtClientIdNo}', 
						client_type_id = '{$this->selClientTypeId}', 
						client_addr_bill = '{$this->cbClientAddrBill}', 
						address_id = '{$this->hddnAddressId}', 
						client_phone = '{$this->edtClientPhone}', 
						client_phone_alt = '{$this->edtClientPhoneAlt}', 
						client_email = '{$this->edtClientEmail}', 
						client_note = '".SableGeneralFunctions::formatName($this->edtClientNote)."', 
						gender_id = '{$this->selGenderId}', 
						client_business_name = '".SableGeneralFunctions::formatName($this->edtClientBusinessName)."', 
						client_vat_no = '{$this->edtClientVatNo}', 
						client_reg_no = '{$this->edtClientRegNo}', 
						client_contract = {$this->cbClientContract}, 
						client_deleted = '{$this->hddnClientDeleted}', 
						last_update = '{$this->hddnLastUpdate}' 
						where client_id = '{$code}'";
		$res=$this->sableDB->updateQuery($updateQuery);
		//Check if the details were successfully updated:
		if ($res)
		{
			SableDBFunctions::loadAuditDetail($this->uc, 
				'Client details modified: '.$this->hddnClientId, $code);
			SableSystem::ajaxResponse(true, '/client/', 'The Client was successfully updated.', 0, "", 0, "");
		}
		else 
			SableSystem::ajaxResponse(false, "", "Modification of the Client failed. Please try again or contact support.", 
				5, "hddnClientId", false, "hddnClientId");
    }
    

    
	private function saveAddresses()
	{
		/**
		[addresses] => Array
			(
				[0] => Array
					(
						[value] => 1
						[text] => Physical
						[tag] => 88 Crane St, Roodepan, Kimberley, 8309
						[displayText] => Physical: 88 Crane St, Roodepan, Kimberley, 8309
						[readonly] => 
					)

			)
		**/
		$phys = 0;
		if (is_array($this->addresses) && !empty($this->addresses))
		{
			foreach($this->addresses as $address)
			{
                
                	SableDebug::debug($address['tag'], 1);

               
				$phys = SableDBFunctions::storeAddress($address['tag'], 0, 0);
				//if ($address['value']) $this->selAddressId = $phys;

			}
		}
		else
		{
			SableSystem::ajaxResponse(false, "", "A client address is required.", 5, "txtClientAddress", false, "txtClientAddress");
		}
        
        		$phys = 0;
        
                        	SableDebug::debug('Before write building', 1);

        
		if (is_array($this->buildingAddresses) && !empty($this->buildingAddresses))
		{                	SableDebug::debug($address['tag'], 1);
                                 	SableDebug::debug('In write building', 1);


			foreach($this->buildingAddresses as $buildingAddress)
			{
                
                	SableDebug::debug($buildingAddress['tag'], 1);

               
				$phys = SableDBFunctions::storeAddress($buildingAddress['tag'], 0, 0);
				//if ($address['value']) $this->selAddressId = $phys;

			}
		}
		else
		{
			SableSystem::ajaxResponse(false, "", "A building address is required.", 5, "txtBuildingAddress", false, "txtBuildingAddress");
		}
        
        
	}
    
    
    
    
	function addAddress()

	{

		global $sableDB;
        
        $addressStreet = null;
        $addressSuburb = null;
        $addressCounty = null;
        $addressCity = null;
        $addressPostalCode = null;
        $address_lng = null;
        $address_lat = null;
        
        foreach($this->addressList as $addressItem)

		{

			$address = $addressItem['tag'];

			$addressStreet= SableGeneralFunctions::formatName($address['edtAddressStreet']);
			$addressSuburb= SableGeneralFunctions::formatName(address['edtAddressSuburb']);
			$addressCity= SableGeneralFunctions::formatName($address['edtAddressCity']);
			$addressCounty= SableGeneralFunctions::formatName($address['edtAddressCounty']);
			$addressPostalCode= SableGeneralFunctions::formatName($address['edtAddressPostalCode']);

			$now	= new DateTime();

			$qry	= "INSERT INTO address 

						(client_id, address_type_id, country_id, post_id, address_street, address_suburb, address_city, address_county, address_postal_code, address_lng, address_lat) 

						VALUES 

						({$this->hddnClientId}, {$address['selAddressTypeId']}, {$address['selCountryId']}, {$address['selPostId']}, 
                        '{$addressStreet}', '{$addressSuburb}', '{$addressCounty}', '{$addressCity}', '{$addressPostalCode}')";

			$res=$sableDB->updateQuery($qry);

			//Check if the Address details were successfully added:

			if ($res)

			{

				$addressId = $sableDB->getValue('select address_id from address where client_id = '.$this->hddnClientId.' and address_street = "'.$addressStreet.'"');

				SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 'New Address added: '.$addressStreet, $addressId);

			}

			unset($now);

		}

	}
    
	function addBuildings()

	{

		global $sableDB;

		$buildingName = null;



		foreach($this->buildingList as $buildingItem)

		{

			$building = $buildingItem['tag'];

			$now	= new DateTime();

			$buildingName= SableGeneralFunctions::formatName($building['edtBuildingName']);
            

			$qry	= "INSERT INTO building 

						(client_id, address_id, area_id, building_name, building_notes, user_code, building_ip, building_date, last_update) 

						VALUES 

						({$this->hddnClientId}, {$this->hddnAddressId}, {$building['selAreaId']}, '{$buildingName}', 

						'".addslashes($building['txtBuildingNeeds'])."', {$_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 getClientId()
	{
		$sql = "select client_id from client where client_id = '{$this->hddnClientId}'";
		return $this->sableDB->getValue($sql);
	}

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

	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 deleteClient()
	{
		$code = SableSystem::sableDecode($this->hddnClientId);
		$cnt = $this->sableDB->getValue("select count(*) from client where client_id = {$code}");
		if ($cnt <= 0)
			SableSystem::ajaxResponse(false, "", "Delete failed - invalid Client selected.", 
				5, "hddnClientId", false, "hddnClientId");
		else
		{
			$sql = "delete from client where client_id = '{$code}'";
			$res = $this->sableDB->updateQuery($sql);
			if ($res)
			{
				SableDBFunctions::loadAuditDetail($this->uc, 'Client record deleted.', $code);
				SableSystem::ajaxPageRedirect('/client/','The Client record was successfully deleted.');
			}
			else
			SableSystem::ajaxResponse(false, "", "
			System error: The Client failed to delete. Please try again later or contact support.", 
				5, "hddnClientId", false, "hddnClientId");
		}
	}
    
	private function storeAddresses($code)
	{		
		global $sableDB;
		if (is_array($this->addresses))
		{
			$addressIds = [];
			foreach($this->addresses as $addr)
			{
				/*
				$addr['tag'] = the address (address)
				$addr['value'] = address type (address_type_id)
				$this->selCountryCode = (country_id)
				*/
                
                
                $addressStreet = substr($addr['tag'], 0, strpos($addr['tag'], ','));
                
                
				$land = empty($this->selCountryCode) ? 197 : 0;
				$sql = 'insert ignore into address (address_type_id, country_id, address_street) 
						values ('.$addr['value'].', '.$land.', "'.$addressStreet.'")';
				$sableDB->updateQuery($sql);
				$addressIds[]['value'] = $sableDB->getValue('select address_id from address 
				where address = "'.$addressStreet.'" and address_type_id = '.$addr['value'].' and country_id = '.
				$land);
			}
			SableDBFunctions::storeArray('client_address', 'client_id', $code, 'address_id', $addressIds);
		}
	}    
    

} //classClient
