<?php
/**
## Version: 2.1 -- Date: 05-SEP-2019 -- Added version information and revision history.
**/
class SableValidationFunctions
{
	/*
	Function 'validateName' validates a first name.
	*/
	public static function validateName($name, $field){if ($name == '') exit($field.'#Please enter your first name.');}
	
	/*
	Function 'validateSurname' validates a last name.
	*/
	public static function validateSurname($surname, $field){if ($surname == '') exit($field.'#Please enter your last name.');}
	
	/*
	Function 'validatePhone' validates a telephone number, cell phone number or fax number.
	*/
	public static function validatePhone($no, $fieldName)
	{
		if ($no=='')
		{
			exit($fieldName.'#Please enter a valid phone number');
		}
	
		if (strlen($no)<>10)
		{
			exit($fieldName.'#Phone number should be 10 digits long with no spaces.');
		}
	
		if(ereg('[^0-9]', $no))
		{ // ensure only numeric values are provided
			exit($fieldName.'#Only numeric values are permitted for phone numbers.');
		} 	
	
	} /* validatePhone() */
	
	public static function validateCompanyRegNo($regNo)
	{
		$regArray = explode('/', $regNo);
		return (($regArray[0] <= date('Y')) && ($regArray[1] <= 999999) && ($regArray[2] <= 31)  & ($regArray[2] >= 6));
	}
	
	public static function validateCompanySDLNo($SDLNo){return preg_match('~^(?i)[L][0-9]{9}$~', $SDLNo);}
	public static function validateCompanyPAYENo($PAYENo){return preg_match('~^[7][0-9]{9}$~', $PAYENo);}
	public static function validateCompanyUIFNo($UIFNo){return preg_match('~^(?i)[U][0-9]{9}$~', $UIFNo);}
	
	/*
	Function 'validateEmail' validates an email address for all possible aspects.
	*/
	public static function validateEmail($email)
	{
		$email = filter_var($email, FILTER_SANITIZE_EMAIL);
		$test = filter_var($email, FILTER_VALIDATE_EMAIL);
		return $test;
	} /* validateEmail() */
	
	/*
	Function 'validateURL' validates an URL address for all possible aspects.
	*/
	public static function validateURL($url){return filter_var($url, FILTER_VALIDATE_URL);} /* validateURL() */	
	
	public static function validateVATNo($vatNo){return preg_match('/^[4][0-9]{9}$/', $vatNo);}
	
	/*
	Function 'validateIDNo' validates South African ID numbers for validity.
	*/
	public static function validateIDNo($id, $field, $silent = false)
	{
		//South African ID number is 13 digits in length:
		if (strlen($id) <> 13) 
		{
			if ($silent)
				return false;
			else
				SableSystem::ajaxValidationError('ID number should be 13 digits long.', $field);
		}
		
		//All digits must be numeric:	
		if(!(preg_match('/^[1-9][0-9]*$/', $id))) 
		{
			if ($silent)
				return false;
			else
				SableSystem::ajaxValidationError('ID Number should contain only numeric digits.', $field);
		}
	
		//the control figure, which is the 13th digit of all identity numbers where the 12th digit is
		//8 or 9 (should be in most cases) 
		//is calculated as follows using ID Number 800101 5009 087 as an example:
		//Add all the digits in the odd positions (excluding last digit).
		//8 + 0 + 0 + 5 + 0 + 0 = 13...................[1]
		//Move the even positions into a field and multiply the number by 2.
		//011098 x 2 = 22196
		//Add the digits of the result in b).
		//2 + 2 + 1 + 9 + 6 = 20.........................[2]
		//Add the answer in [2] to the answer in [1].
		//13 + 20 = 33
		//Subtract the second digit (i.e. 3) from 10.  The number must tally with the last number in
		//the ID Number. If the result is 2 digits, the last digit is used to compare against the 
		//last number in the ID Number.  If the answer differs, the ID number is invalid.	
		$id_1 = intval(substr($id, 0, 1)); //781202 5007 080
		$id_2 = intval(substr($id, 1, 1)); //7+1+0+5+0+0 = 13
		$id_3 = intval(substr($id, 2, 1)); //822078 x 2 = 1644156
		$id_4 = intval(substr($id, 3, 1)); //1+6+4+4+1+5+6 = 27
		$id_5 = intval(substr($id, 4, 1)); //27 + 13 = 40
		$id_6 = intval(substr($id, 5, 1)); //10 - 0 = 10
		$id_7 = intval(substr($id, 6, 1));
		$id_8 = intval(substr($id, 7, 1));
		$id_9 = intval(substr($id, 8, 1));
		$id_10 = intval(substr($id, 9, 1));
		$id_11 = intval(substr($id, 10, 1));
		$id_12 = intval(substr($id, 11, 1));
		$id_13 = intval(substr($id, 12, 1));	
		
		$odd_sum = $id_1 + $id_3 + $id_5 + $id_7 + $id_9 + $id_11;	
		
		$even_sum = $id_2.$id_4.$id_6.$id_8.$id_10.$id_12;
		
		$check_sum = $even_sum * 2;
		$check_len = intval(strlen($check_sum));
		$check_sum_sum = 0;
		
		for ($i=0; $i<=$check_len; $i++) $check_sum_sum = $check_sum_sum + intval(substr($check_sum,$i,1));
	
		$sub_total = $check_sum_sum + $odd_sum;
		$check_digit = 10 - substr($sub_total, 1, 1);
		
		if ($check_digit == 10) $check_digit = 0;
		
		if (intval($check_digit) === intval($id_13))
		{
			if ($silent) return true;
		}
		else
		{
			if ($silent)
				return false;
			else
				SableSystem::ajaxValidationError('The ID number provided is not a valid South African ID number.', $field);
		}
	}
	
	public static function validateEmployer($employerCode, $field)
	{
	  $query = 'select coy_name from company where coy_code = '.$employerCode;
	  $res = executeQuery($query, 1, '');
	  if ($res < 0)
	  {
		exit($field.'#The given Employer Code is not a valid Employer Code.');
	  }
	}
	
	public static function validateCaptchaCode($code, $field)
	{
		$userCode = strtolower($code);
		$dbCode = strtolower($_SESSION['securimage_code_value']);
		
		if ($userCode <> $dbCode){
			exit($field.'#The code you entered does not match the one in the image.');
		}
	}
	
	public static function validatePassword($pwd)
	{
		if (strlen($pwd) < 6) exit("edtPassword#Password must be at least 6 characters in length.");
	}
	
	public static function validateBankAccount($bank, $type, $branch, $account)
	{
		/**
		example: https://freecdv.co.za/check/current/019205/155439774
		Results as follows:
		Array
			(
				[branchName] => CAPITEC BANK CPC
				[bankName] => CAPITEC BANK LIMITED
				[status] => Valid ==> [Valid, InvalidAccountLength, AccountNotVerifiable, BranchNotComputerised, BranchCodeNotInvalid, AccountTypeNotValid, AccountNumberNotValid]
			)
		**/
		if (SABLE_DEMO_SYSTEM)
		{
			$data['msg']	= 'Account details are valid.'; 
			$data['result'] = 1;
			$data['code']	= 0;
			return $data;
		}
		
		global $sableDB;
		
		$url = 'https://freecdv.co.za/check/'.strtolower($type).'/'.trim($branch).'/'.trim($account);
		//open connection
		$ch = curl_init();
		
		//set the url, number of POST vars, POST data
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_NOBODY, false);
		curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);
		curl_setopt($ch, CURLOPT_POST, false);
//		curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);
		
		//execute post
		$result = curl_exec($ch);
		//{"branchName":"CAPITEC BANK CPC","bankName":"CAPITEC BANK LIMITED","status":"Valid"}
		//close connection
		curl_close($ch);
		$data = json_decode($result, true);
		
		if (empty($data))
		{
			$data['msg']  = 'Invalid account information.';
			$data['code'] = 1;
			$data['result'] = 0; //failed
		}
		else
		{

			$bankidA = intval($sableDB->getValue('select bank_id from bank where bank_name like "%'.$bank.'%"'));

			$bankname = str_ireplace('bank', '', $data['bankName']);
			$bankname = str_ireplace('limited', '', $bankname);
			$bankname = str_ireplace('corporate', '', $bankname);
			$bankname = str_ireplace('of', '', $bankname);
			$bankname = str_ireplace('ltd', '', $bankname);

			$bnm = explode(' ', $bankname);
			$sz = sizeof($bnm);
			
			$sql = 'select bank_id from bank where ';
			$started = false;
			foreach($bnm as $bnk)
			{
				if (!empty($bnk))
				{
					$prx = $started ? ' or' : ' ';
					$started = true;	
					$sql .= $prx.' (bank_name like "%'.$bnk.'%")';
				}
			}
			
			$bankidB = intval($sableDB->getValue($sql));
			$bankok = $bankidA === $bankidB;
			
			$data['result'] = 0; //failed
			$data['code'] 	= 0; //0 = ?, 1 = Account No, 2 = Account type,  3 = branch code, 4 = bank			
			if ($bankok)
			{
				switch($data['status'])
				{
					case	'Valid':
							{
								$data['msg'] = 'Account details are valid.'; 
								$data['result'] = 1; 
								break;
							}
					case	'InvalidAccountLength':
							{
								$data['msg']	= 'Account number is incorrect.'; 	
								$data['code']	= 1;	
								break;
							}
					case	'AccountNotVerifiable':
							{
								$data['msg']	= 'This account cannot be verified.';
								$data['code']	= 1;
								break;
							}
					case	'BranchNotComputerised':
							{
								$data['msg']	= 'The branch code is not computerised.';
								$data['code']	= 3;
								break;
							}
					case	'BranchCodeNotInvalid':
							{
								$data['msg']	= 'Invalid branch code.';
								$data['code']	= 3;
								break;
							}
					case	'AccountTypeNotValid':
							{
								$data['msg']	= 'Invalid account type.';
								$data['code']	= 2;
								break;
							}
					case	'AccountNumberNotValid':
							{
								$data['msg']	= 'Invalid account number.';
								$data['code']	= 1;
								break;
							}
				}
			}
			else
			{
				$data['msg']	= 'Incorrect bank specified.';
				$data['code']	= 4;
			}
		}
		
		return $data;
		
	}	
}
?>