<?php
require_once(__DIR__."/../includes/sysinit.php");
class Company 
{
	var 	$hddnCompanyId,	$edtCompanyName, $edtCompanyEmail, $edtCompanyLogo,	$edtCompanyAddress,	$edtCompanyURL,
			$edtCompanyPhone, $edtCompanyType, $edtCompanyRegNo, $addressLng, $addressLat, $selAddressId,
			$sableDB, $edtUserName, $edtUserSurname, $edtCompanyVatNo, 
			$edtCompanyContactName, $edtCompanyContactSurname, $edtCompanyContactEmail, $edtCompanyContactPhone;
			
	function __construct(){$this->sableDB = new SableDB;}
	
	function __destruct(){unset($this->sableDB);}
	
	private function companyValidation($edit=false)
	{		
		$this->checkCompanyExists($edit);
		
		if (!SableValidationFunctions::validateEmail($this->edtCompanyEmail)) 
			SableSystem::ajaxResponse(false, "", "Not a valid email address.", 5, "edtCompanyEmail", false, "");
	
		//SableDebug::debug($this->edtCompanyRegNo);
		if ($this->edtCompanyRegNo!=='//')
		{	
			if (!SableValidationFunctions::validateCompanyRegNo($this->edtCompanyRegNo))
				SableSystem::ajaxResponse(false, "", "Not a valid company registration number.", 5, "edtCompanyRegNo", false, "");
		}
			
		if (!empty($this->edtCompanyVatNo))
		{
			if(!SableValidationFunctions::validateVATNo($this->edtCompanyVatNo)) 
				SableSystem::ajaxResponse(false, "", "Not a valid VAT number.", 5, "edtCompanyVatNo", false, "");
		}
		
		if (!empty($this->edtCompanySDLNo))
		{
			if(!SableValidationFunctions::validateCompanySDLNo($this->edtCompanySDLNo)) 
				SableSystem::ajaxResponse(false, "", "Not a valid SDL number.", 5, "edtCompanySDLNo", false, "");
		}
					
		if(!empty($this->edtCompanyUrl))
		{
			if (!SableValidationFunctions::validateURL($this->edtCompanyUrl)) 
				SableSystem::ajaxResponse(false, "", "Not a valid URL.", 5, "edtCompanyUrl", false, "");
			else
			{
				if(!SableGeneralFunctions::checkURLExists($this->edtCompanyUrl)) 
					SableSystem::ajaxResponse(false, "", "Website does not exist. Please check your spelling.", 5, "edtCompanyUrl", false, "");
			}
		}
		$this->selAddressId = SableDBFunctions::storeAddress($this->edtCompanyAddress, $this->addressLng, $this->addressLat);
	}
	
	function addCompany()
	{
		if (empty($this->hddnCompanyId))
		{
			$this->companyValidation(false);
			$this->loadCompany(false);
		}
		else
		{
			$this->companyValidation(true);
			$this->updateCompany();
	 	}
	}
	
	function loadCompany($registering=false)
	{
		$suburb = empty($this->edtCompanySuburb)?0:SableSystem::sableDecode($this->edtCompanySuburb);
		$coReg = ($this->edtCompanyRegNo==="//")?"":$this->edtCompanyRegNo;
		$this->selAddressId = SableDBFunctions::storeAddress($this->edtCompanyAddress, $this->addressLng, $this->addressLat);
		$insertQuery = "INSERT INTO company (
						company_name,
						company_email,
						company_logo,
						address_id,
						company_url,
						company_phone,
						company_type_id,
						company_reg_no,
						company_vat_no) VALUES (
						'".addslashes($this->edtCompanyName)."',
						'".$this->edtCompanyEmail."',
						'".$this->edtCompanyLogo."',
						'".$this->selAddressId."',
						'".$this->edtCompanyURL."',
						'".$this->edtCompanyPhone."',
						'".SableSystem::sableDecode($this->edtCompanyType)."',
						'".$coReg."',
						'".$this->edtCompanyVatNo."')";
		$res=$this->sableDB->updateQuery($insertQuery);
		//Check if the company details were successfully added:
		if ($res)
		{
			$this->setCompanyId();
			if(!$registering)
			{
				SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 
					'New company added: '.addslashes($this->edtCompanyName), $this->hddnCompanyId);
				SableSystem::ajaxResponse(true, '/company/', 'The company was successfully added.', 0, "", 0, "");			 
			} 
			else 
			{
				$this->hddnCompanyId = $this->sableDB->getValue('select company_id from company where company_phone = "'.
										$this->edtCompanyPhone.'" and company_email = "'.$this->edtCompanyEmail.'"');
				
				return true;
			}
		}
		else
			SableSystem::ajaxResponse(false, "", "Add of a new company failed. Please try again or contact support.", 5, 
												"edtCompanyName", false, "edtCompanyName");
	}
	
	function registerCompany()
	{
		$this->companyValidation(false);
		$this->edtCompanyType = SableSystem::sableEncode(4); //2==Administrator
		if ($this->loadCompany(true))
		{
			if ($this->addFirstUser(2))
			{
				SableSystem::ajaxPageRedirect('/login/', 'Thank you for registering. An email with a confirmation link has been emailed to you. Please click on the link to activate your account.');
			}
		}
		else 
			SableSystem::ajaxResponse(false, "/login/", "Sign up failed. Please try again later or contact support.", 5, 
												"edtCompanyName", false, "edtCompanyName");		
	}
	
	function updateCompany()
	{
		$this->companyValidation(true);
		$code = SableSystem::sableDecode($this->hddnCompanyId);
		$coReg = ($this->edtCompanyRegNo==="//")?"":$this->edtCompanyRegNo;
		$suburb = empty($this->edtCompanySuburb)?0:SableSystem::sableDecode($this->edtCompanySuburb);
		$this->selAddressId = SableDBFunctions::storeAddress($this->edtCompanyAddress, $this->addressLng, $this->addressLat);
		$updateQuery = "UPDATE company set 
						company_name = '".addslashes($this->edtCompanyName)."',
						company_email = '".$this->edtCompanyEmail."',
						company_logo = '".$this->edtCompanyLogo."',
						address_id = '".$this->selAddressId."',
						company_url = '".$this->edtCompanyURL."',
						company_phone = '".$this->edtCompanyPhone."',
						company_type_id = '".SableSystem::sableDecode($this->edtCompanyType)."',
						company_reg_no = '".$coReg."',
						company_vat_no = '".$this->edtCompanyVatNo."',
						company_last_update = '".date('Y-m-d')."' 
						where company_id = '".$code."'";
		$res=$this->sableDB->updateQuery($updateQuery);
		//Check if the details were successfully updated:
		if ($res)
		{
			SableDBFunctions::loadAuditDetail($_SESSION['user']['user_code'], 'Company details modified: '.addslashes($this->edtCompanyName), $code);
			SableSystem::ajaxResponse(true, '/company/', 'The Company was successfully updated.', 0, "", 0, "");
		}
		else 
			SableSystem::ajaxResponse(false, "", "Modification of the company failed. Please try again or contact support.", 5,
												"edtCompanyName", false, "edtCompanyName");
	}
	
	private function addFirstUser($accessId)
	{
		include_once(SABLE_WORKING_PATH.'user/user.php');
		$_user = new User; //new class instance
		$_user->edtUserEmail	= $this->edtCompanyContactEmail;
		$_user->edtUserPhone	= $this->edtCompanyContactPhone;
		$_user->edtUserName 	= $this->edtCompanyContactName;
		$_user->edtUserSurname 	= $this->edtCompanyContactSurname;
		$_user->accessId		= $accessId;
		$_user->selUserTitle 	= $this->selCompanyContactTitle;
		$_user->selCompanyId	= $this->hddnCompanyId; 
		$_user->edtUserImage 	= SABLE_UNKNOWN_IMAGE;
		$result = $_user->addFirstUser();
		unset($_user);
		return $result;
	}	
	
	private function checkCompanyExists($editing)
	{
		$where = $editing?" and company_id <> ".SableSystem::sableDecode($this->hddnCompanyId):"";
		$cPhone=$this->sableDB->getValue("SELECT company_id from company where REPLACE(company_phone, ' ', '') = '".
				$this->edtCompanyPhone."'".$where);
		if(!empty($cPhone))
			SableSystem::ajaxResponse(false, "", "This company is already registered.", 5, "edtCompanyName", false, "edtCompanyName");

		$cName=$this->sableDB->getValue('select company_id from company where company_name = "'.$this->edtCompanyName.'"'.$where);
		if(!empty($cName))
			SableSystem::ajaxResponse(false, "", "This company is already registered.", 5, "edtCompanyName", false, "edtCompanyName");
			
		$cMail=$this->sableDB->getValue("SELECT company_id from company where company_email = '".$this->edtCompanyEmail."'".$where);
		if(!empty($cMail))
			SableSystem::ajaxResponse(false, "", "This company is already registered.", 5, "edtCompanyName", false, "edtCompanyName");		
		//$sql = "select count(*) from company where company_id = '".SableSystem::sableDecode($this->hddnCompanyId)."'";
		//$cid = $this->sableDB->getValue($sql);
		//if (!empty($cid)) return true; else return false;
	}
	
	function viewCompany()
	{
		$url = '/company/view.php?'.SableSystem::sableDecode($this->hddnCompanyId);
		SableSystem::ajaxPageRedirect($url);
	}
	
	function editCompany()
	{
		$url = '/company/edit.php?'.SableSystem::sableDecode($this->hddnCompanyId);
		SableSystem::ajaxPageRedirect($url);
	}
	
	function editContacts()
	{
		$url = '/company_contact/add.php?'.SableSystem::sableDecode($this->hddnCompanyId);
		SableSystem::ajaxPageRedirect($url);
	}

	function editEmailGroup()
	{
        global $sableDB;
        $egid = $sableDB->getValue('select email_group_id from email_group where company_id = '.$this->hddnCompanyId);
        if ($egid)
            $url = '/email_group/edit.php?'.$egid;
        else
		  $url = '/email_group/add.php?'.$this->hddnCompanyId;
		SableSystem::ajaxPageRedirect($url);
	}
	
	function deleteCompany()
	{
		$code = SableSystem::sableDecode($this->hddnCompanyId);
		
		if ($code == 1 ) SableSystem::ajaxResponse(false, "", "Main Company may not be deleted.", 5, "edtCompanyName", false, 
			"edtCompanyName");
		
		$cnt = $this->sableDB->getValue("select count(*) from company where company_id = ".$code);
		if ($cnt <= 0)
			SableSystem::ajaxResponse(false, "", "Delete failed - invalid company selected.", 5, "edtCompanyName", false, 
			"edtCompanyName");
		else
		{
			$sql = "delete from company where company_id = '".$code."'";
			$sql = "update company set deleted = 1 where company_id = '".$code."'";
			$res = $this->sableDB->updateQuery($sql);
			if ($res)
			{
                //$sql = "delete from company__contact where company_id = '".$code."'";
                //$res = $this->sableDB->updateQuery($sql);
                
				SableDBFunctions::loadAuditDetail($_SESSION["user"]["user_code"], "company record deleted.", $code);
				SableSystem::ajaxPageRedirect('/company/','The company was successfully deleted.');
			}
			else
				SableSystem::ajaxResponse(false, "", 
				"System error: The company failed to delete. Please try again later or contact support.", 5, 
				"edtCompanyName", false, "edtCompanyName");
		}
	}
	
	function setCompanyId()
	{
		global $sableDB;
		$sql = 'select company_id from company where company_name = "'.$this->edtCompanyName.'" and company_email = "'.
				$this->edtCompanyEmail.'"';
		$this->hddnCompanyId = $sableDB->getValue($sql);
	}
    
	function duplicateCompany()
	{
		global $sableDB;
		$code = SableSystem::sableDecode($this->hddnCompanyId);
		$newId = $sableDB->duplicateRow("company", "company_id", $code);
		if($newId)
		{
			SableDBFunctions::loadAuditDetail($_SESSION["user"]["user_code"], "Company record duplicated.", $code);
			SableSystem::ajaxPageRedirect("/company/", "The company was successfully duplicated.");
		}
		else
			SableSystem::ajaxResponse(false, "", "System error: The company failed to duplicate. Please try again later or contact support.", 
										5, "edtCompanyName", false, "edtCompanyName");
	}    
		
} //classCompany
