<?php 
	/******************* Error Reporting ********************/
	error_reporting(E_ALL);
	date_default_timezone_set('Australia/Sydney');

	/******************* Global Variables ********************/
	$gaSettings = array();       // Holds Global Settings
	$gaFM = array();             // Holds FM Connections
	$gaPage = array();           // Holds Page Scope
	$gaDbgScopes = array();      // Array Scopes
	$gaDbgScopeNames = array();  // Names of Array Scopes

	$Version = "1.0";


	/********************* Site Settings *********************/
	require_once 'settings.php';
	require_once 'fmREST.php';
	require_once 'sitefunctions.php';
	require_once 'FileMakerODataClient.php';   // ! New System

	use Keysoft\FileMaker\Client;
	$fm = Client::getInstance('https://petsafe.keysoft.com.au/fmi/odata/v4/KeysoftPetsafe', 'oData', "bWOsV97',?r]iQ9O{}4?");

	use phpmailer\PHPMailer\PHPMailer;
	use phpmailer\PHPMailer\Exception;

	require 'phpmailer/src/Exception.php';
	require 'phpmailer/src/PHPMailer.php';
	require 'phpmailer/src/SMTP.php';

	/*********************** Constants ***********************/
	define('MAX_DIR_CREATE_ATTEMPTS', 100);
	
	/******************** Global Functions********************/

	function fPNG2GIF($sImgSrc){
	// fPNG2GIF
		if ((strstr($_SERVER['HTTP_USER_AGENT'], "MSIE 6") !== false or strstr($_SERVER['HTTP_USER_AGENT'], "MSIE 5") !== false)
			and (strstr($_SERVER['HTTP_USER_AGENT'], "Opera") === false))
		{
			return str_replace(".png", ".gif", $sImgSrc);
		}
		else
		{
			return $sImgSrc;
		}
	}

	function fGetFMTimeStamp(){
	// fGetFMTimeStamp - Gets FileMaker style Timestamp
		return date("m/d/Y") . ' ' . date("h:i:s A");
		//return date("d/m/Y") . ' ' . date("h:i:s A");
	}

	function fReformatDate($s){
	// fReformatDate - Format dates for display
		if ($s == '')
		{
			return '';
		}
		else
		{
			return date('d M Y', strtotime( $s ) );
		}
	}

	function fReformatTimestamp($s){
	// fReformatTimestamp - Format timestamps for display
		if ($s == '')
		{
			return '';
		}
		else
		{
			return date('d M Y', strtotime( $s ) ).' at '.date('H:i', strtotime( $s ) );
		}
	}

	function fReformatPhones($num) {
	// Format phone numbers - xx xxxx xxxx OR xxxx xxxx
		$newnum = preg_replace('%[^0-9]%','',$num);
		if (strlen($newnum) == 10 and is_numeric($newnum)){
			$batch1 = substr($newnum,0,2);
			$batch2 = substr($newnum,2,4);
			$batch3 = substr($newnum,6,4);
			$newnum = $batch1 . ' ' . $batch2 . ' ' . $batch3;

		} else if (strlen($newnum) == 8 and is_numeric($newnum)){
			$batch1 = substr($newnum,0,4);
			$batch2 = substr($newnum,4,4);
			$newnum = $batch1 . ' ' . $batch2;
		
		} else {
			$newnum = trim($num);
		}

		return $newnum;
	}

	function formatDecimal($number){
	//Format to 2 decimal places
		return number_format($number, 2, '.', '');
	}

	function fMakeUniqueDir($base_dir){
	// Creates a new directory with a unique name and returns the path to that directory.
		$pid = getmypid();
		$i = 0;
		@mkdir($base_dir);

		do {
			if (getenv('os')) {
				$ret = $base_dir.'\\'.$pid.'.'.rand(); // windows host
			} else {
				$ret = $base_dir.'/'.$pid.'.'.rand(); // mac or unix
			}
			if (++$i >= MAX_DIR_CREATE_ATTEMPTS) return false;
		} while (!mkdir($ret));

		return $ret;
	}

	function fGetMicrotime(){
	// fGetMicrotime
		list($usec, $sec) = explode(" ", microtime());
		return ((float) $usec + (float) $sec);
	}

	// fGetAuthenticationDetails
	function fGetAuthenticationDetails($bForce, $sRealm, $sError){
		if ($bForce
				|| !isset($_SERVER['PHP_AUTH_USER'])
				|| trim($_SERVER['PHP_AUTH_USER']) == ''
				|| trim($_SERVER['PHP_AUTH_PW']) == ''
			)
		{
			header('WWW-Authenticate: Basic realm="' . $sRealm . '"');
			header('HTTP/1.0 401 Unauthorized');
			echo $sError;
			exit;
		}
	}

	// fRequireParameter
	function fRequireParameter($sParameterName, &$aScope){
		if (!array_key_exists($sParameterName, $aScope)) {
			fReturnError('The required parameter ' . $sParameterName . ' was not provided');
		}
	}

	// fDefaultParameter
	function fDefaultParameter($sParameterName, &$aScope, $uDefault){
		if (!array_key_exists($sParameterName, $aScope)) {
			$aScope[$sParameterName] = $uDefault;
		}
	}

	// fReturnError
	function fReturnError($sErrorDescription){
		// Globals
		global $gaSettings;

		file_put_contents('/tmp/last_error.txt', $sErrorDescription);

		if ($gaSettings['output_format'] == "XML")
		{
			fReturnErrorXML($sErrorDescription);
		}
		else
		{
			echo $sErrorDescription;
			fCleanup();
		}
	}

	// fReturnErrorXML
	function fReturnErrorXML($sErrorDescription){
		echo "<?xml version=\"1.0\"?>";
		echo "<error>" . htmlentities($sErrorDescription) . "</error>";
		fCleanup();
	}

	// fPrintDebugOutput
	function fPrintDebugOutput(){
		// Globals
		global $gaSettings;
		global $gaDbgScopes;
		global $gaDbgScopeNames;
		
		// Defaults
		fDefaultParameter('dbg_scope_on', $gaSettings, false);

		// Print the Debug Output
		echo "<hr>\n";
		echo "<pre>\n";
		echo "<h1>Debug Output</h1>\n";
		echo "<b>" . $gaSettings['dbg_page_date'] . "</b><br>";
		echo "<i><b>Total Time Taken :" . $gaSettings['dbg_page_time'] . " ms</b></i>";
		echo "</pre>\n";

		if ($gaSettings['dbg_db_on'])
		{
			fDBPrintDebugOutput();
		}

		if ($gaSettings['dbg_fm_on'])
		{
			fFMPrintDebugOutput();
		}

		// Print the debug scopes
		if ($gaSettings['dbg_scope_on'])
		{
			for ($i = 0; $i < count($gaDbgScopes); $i++)
			{
				fPrintDebugScope($gaDbgScopes[$i], $gaDbgScopeNames[$i]);
			}
		}
	}

	// fPrintDebugScope
	function fPrintDebugScope($aScope, $sScope){
		// Print the Debug Output
		echo "<pre>\n";
		echo "<h2>" . htmlspecialchars($sScope) . "</h2>\n";

		foreach ($aScope as $key => $value) {
			echo "<b>" . htmlspecialchars($key) . "</b> = <i><b>" . htmlspecialchars($value) . "</b></i><br>\n";
		}

		echo "</pre>\n";
	}


	// fCleanup
	function fCleanup() {
		// Globals
		global $gaSettings;

		// Defaults
		fDefaultParameter('dbg_on', $gaSettings, false);

		// Set the finish time and time taken for the page
		$gaSettings['dbg_page_finish'] = fGetMicrotime();
		$gaSettings['dbg_page_time']   = (integer) (($gaSettings['dbg_page_finish'] - $gaSettings['dbg_page_start']) * 1000);

		// Print the debug output
		if ($gaSettings['dbg_on'])
			fPrintDebugOutput();

		exit;
	}

	// fRedirect
	function fRedirect($sHref) {
		// Globals
		global $gaSettings;


		// Javascript redirect if debug is on
		if ($gaSettings['dbg_on'])
		{
			echo('<a href="'.$sHref.'">Click to continue ('.$sHref.')</a>');
		}
		else
		// Http Redirect
		{

			//Carl: Does not work when $sHref = "indexsearchlogin.php?getquery=982222222222222&searchtype=chip"
			//Bug?
			header('Location: '.$sHref);
		}
	}

	function fParseAusDateString($sDate){
		if ($sDate == '')
		{
			return null;
		}
		else
		{
			$sDate_out = $sDate;
			$a = explode('/', $sDate);
			// strtotime expects US date format input i.e. mm/dd/yyyy, so we need
			// to swap month and day around.
			if (count($a) == 3) 
				$sDate_out = $a[1].'/'.$a[0].'/'.$a[2];
			else
				// try the original...
				return null;
				
			$ts = strtotime($sDate_out);
			return $ts;
		}
	}
    
    function pre($e){
        echo '<pre>';
        print_r($e);
        echo '</pre>';
        echo '<hr>';
    }
    
    function generate_basic_password() {
        $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }
	
	function send_mail($subject, $body, $to, $attachments = array()){
	//attachments must be an array of file paths

		$mail = new PHPMailer;
		$mail->isSendmail();                                // Set mailer to use Sendmail on Keysoft cPanel server
		$mail->From = 'confirm@petsafe.com.au';
		$mail->FromName = 'Digivet';
		$mail->addAddress($to);                               // Add a recipient
		
		foreach($attachments as $attachment){
			$mail->addAttachment($attachment);                // Add attachments
		}
		
		$mail->isHTML(true);                                  // Set email format to HTML
		
		$mail->Subject = $subject;
		$mail->Body    = $body;
	    
	    $result = $mail->send();

		if(!$result) {
			
		   echo 'Message could not be sent.';
		   echo 'Mailer Error: ' . $mail->ErrorInfo;
			return false;
		} else {
			return true;
		    //echo 'Email has been sent succesfully.';
		}
	}

	/****************** Filemaker Functions ******************/
	if ($gaSettings['fm_on'])
	{
		require_once 'fmfunctions.php';
	}

	/***************** Force page to Reload ******************/	
	header("Cache-Control: no-cache, max-age=0, must-revalidate, no-store");
	header("Pragma: no-cache");
	header("Expires: 0");

	/*********************** Page Start **********************/
	$gaSettings['dbg_page_start'] = fGetMicrotime();
	$gaSettings['dbg_page_date']  = date("d/m/Y H:i:s", time());
?>
