<?php
	// Filemaker Data API
	error_reporting(1);
	ini_set('display_errors', true );

	require_once ('../phpobjects/common/global.php');

	// Globals
	$gDbgFMQuery = "";

	function fFMFindAll($sFMName, $sLayout, $aSortCriteria = null)	{
		// Globals - Database
		global $gaFM;
		global $gDbgFMQuery;

		// Start time
		$tStartTime = fGetMicrotime();
		$sFMQuery = '';

		// Connect to filemaker
		$fm = new fmREST($gaFM[$sFMName]['host'],$gaFM[$sFMName]['datasource'], $gaFM[$sFMName]['login'], $gaFM[$sFMName]['password'], $sLayout);


        $fm -> show_debug = false; //turn this to true or "html" to show automatically. We're manually including debug information with <print_r ($fm->debug_array);>
        $fm -> secure = true; //not required - defaults to true
        $fm -> fmversion = 19; 
        
		$sFMQuery .= '<b>Layout:</b> '.$sLayout.'<br>';
		// Add Sort Criteria
		if ($aSortCriteria != null )
		{
          $data['_sort'] = json_encode($aSortCriteria);
      //      $fm -> sort = json_encode($aSortCriteria);
		}
        $result = $fm -> getRecords ($data); 



		if ($result['messages'][0]['code'] > 0)
		{
			if (!isset($fmResult->code) || strlen(trim($fmResult->code)) < 1)
			{
				fReturnError('Error Finding All : <br><br><pre>' . $sFMQuery . '</pre><br><br>System Error');
			}
			else
			{
				fReturnError('Error Finding All : <br><br><pre>' . $sFMQuery . '</pre><br><br>Error: '.$fmResult->code);
			}
		}

		return $result;
	}

	function fFMPerformFind(
			$sFMName,			// Name of database to connect to
			$sLayout,			// Name of filemaker layout to use for find
			$aSearchCriteria,		// Array containing filemaker search criteria
			$aSortCriteria = null		// Array of fields to sort by (Optional)
		)
	/*
		Description:
			Performs a filemaker find.
			
		Return:
			Returns a filemaker record set or false if there is an error returned.
			If no records are found the default behaviour is to throw an error.
	*/
	{
		// Globals - Database
		global $gaFM;
		global $gDbgFMQuery;

		// Start time
		$sFMQuery = '';

		// Connect to filemaker
		$fm = new fmREST($gaFM[$sFMName]['host'], $gaFM[$sFMName]['datasource'],  $gaFM[$sFMName]['login'], $gaFM[$sFMName]['password'], $sLayout);
        $fm -> show_debug = false; //turn this to true or "html" to show automatically. We're manually including debug information with <print_r ($fm->debug_array);>
        $fm -> secure = true; //not required - defaults to true
        $fm -> fmversion = 19; 
        
		$sFMQuery .= '<b>Layout:</b> '.$sLayout.'<br>';

        $fmQuery = array ($aSearchCriteria);
        $data['query'] = $fmQuery;
        $data['limit'] = 10000;


		// Add Sort Criteria
		if ($aSortCriteria != null )
		{
          $data['_sort'] = json_encode($aSortCriteria);
		}

		// Add Script
		if ($sScriptName != null)
		{
			$data['script']=$sScriptName;
			$sFMQuery .= 'Running Script: '.$sScriptName.'<br>';
		}

		// Execute the query
        $result=$fm -> findRecords ($data);


	
		if ($result['response']['messages'][0]['code'] > 0)
		{
			// filemaker has returned an error
			
			if (!isset($result['response']['messages'][0]['code']) || strlen(trim($result['messages'][0]['code'])) < 1)
			{
				// filemaker did not set error code
				
				fReturnError('Error Performing Find : <br><br><pre>' . $sFMQuery . '</pre><br><br>System Error');
			}
			else if ($result['response']['messages'][0]['code'] == '401')
			{
				// Dont throw error if no records found (401)
				
				$fmResult = FALSE;
			}
			else
			{
				// Throw error and return error code to browser
				
				fReturnError('Error Performing Find : <br><br><pre>' . $sFMQuery . '</pre><br><br>Error: '.$result['response']['messages'][0]['code']);
			}
		}

		return $result;
	}

	function fFMPerformUpdate($sFMName, $sLayout, $fmRecord, $aUpdateCriteria){
		// Globals - Database
		global $gaFM;
		global $gDbgFMQuery;

	    // Connect to filemaker
		$fm = new fmREST($gaFM[$sFMName]['host'], $gaFM[$sFMName]['datasource'],  $gaFM[$sFMName]['login'], $gaFM[$sFMName]['password'], $sLayout);
        $fm -> show_debug = false; //turn this to true or "html" to show automatically. We're manually including debug information with <print_r ($fm->debug_array);>
        $fm -> secure = true; //not required - defaults to true
        $fm -> fmversion = 19; 


        $data['fieldData'] =  $aUpdateCriteria;
	 
    	$result = $fm -> editRecord ($fmRecord, $data); 


		return $result;
	}
	
	function fFMGetRecord($sFMName, $sLayout, $fmRecord){
		// Globals - Database
		global $gaFM;
		global $gDbgFMQuery;

	    // Connect to filemaker
		$fm = new fmREST($gaFM[$sFMName]['host'], $gaFM[$sFMName]['datasource'],  $gaFM[$sFMName]['login'], $gaFM[$sFMName]['password'], $sLayout);
        $fm -> show_debug = false; //turn this to true or "html" to show automatically. We're manually including debug information with <print_r ($fm->debug_array);>
        $fm -> secure = true; //not required - defaults to true
        $fm -> fmversion = 19; 

	    $recordId = $fmRecord; 
    	$result = $fm -> getRecord ($recordId, $sLayout); 

		return $result;
	}

	function fFMPerformInsert($sFMName, $sLayout, $aUpdateCriteria){
		// Globals - Database
		global $gaFM;
		global $gDbgFMQuery;

		// Start time
		$tStartTime = fGetMicrotime();
		$sFMQuery = '';

		// Connect to filemaker
	    $fm = new fmREST($gaFM[$sFMName]['host'], $gaFM[$sFMName]['datasource'],  $gaFM[$sFMName]['login'], $gaFM[$sFMName]['password'], $sLayout);
        $fm -> show_debug = false; //turn this to true or "html" to show automatically. We're manually including debug information with <print_r ($fm->debug_array);>
        $fm -> secure = true; //not required - defaults to true
        $fm -> fmversion = 19; 
        
		// Set the layout
		$sFMQuery .= '<b>Layout:</b> '.$sLayout.'<br>';

        $data['fieldData']=$aUpdateCriteria;
        $fmRecord = $fm->createRecord($data);
		// Commit

		if ($fmRecord['messages']['code']!=0)
		{

			if (isset($fmResult->code) && strlen(trim($fmResult->code)) > 0)
			{
				fReturnError('Error Performing Insert : <br><br><pre>' . $sFMQuery . '</pre><br><br>Error Code: '.$fmResult->code);
			}
			else if ($fmResult->isValidationError())
			{
				$e = $fmResult->getErrors();
				$v = '';
				for ($i = 0; $i < count( $e ); $i++ )
				{
					$v .= $e[$i][0]->getName().'<br>';
				}

				fReturnError('Error Performing Insert : <br><br><pre>' . $sFMQuery . '</pre><br><br>'.$fmResult->numErrors().' Validation Error(s):<br>'.$v);
			}
			else
			{
				fReturnError('Error Performing Insert : <br><br><pre>' . $sFMQuery . '</pre><br><br>System Error');
			}

		}

		return $fmRecord;
	}

	function fFMDelete($sFMName, $sLayout, $recordid){
	    // Globals - Database
		global $gaFM;
		global $gDbgFMQuery;
	    
	    // Connect to filemaker
		$fm = new fmREST($gaFM[$sFMName]['host'],$gaFM[$sFMName]['datasource'], $gaFM[$sFMName]['login'], $gaFM[$sFMName]['password'], $sLayout);

        $scripts = NULL;
        $fm -> show_debug = false; //turn this to true or "html" to show automatically. We're manually including debug information with <print_r ($fm->debug_array);>
        $fm -> secure = true; //not required - defaults to true
        $fm -> fmversion = 19; 

    	$result = $fm -> deleteRecord ($recordid, $scripts, $sLayout); 
    	
    	return $result;
	}
	
	function fFMExecuteScript($sFMName, $scriptName, $scriptParameter, $layout=NULL){
	    // Globals - Database
		global $gaFM;
		global $gDbgFMQuery;
	    
	    // Connect to filemaker
		$fm = new fmREST($gaFM[$sFMName]['host'],$gaFM[$sFMName]['datasource'], $gaFM[$sFMName]['login'], $gaFM[$sFMName]['password'], $sLayout);

        $fm -> show_debug = false; //turn this to true or "html" to show automatically. We're manually including debug information with <print_r ($fm->debug_array);>
        $fm -> secure = true; //not required - defaults to true
        $fm -> fmversion = 19; 

    	$result = $fm -> executeScript ($scriptName, $scriptParameter, $layout); 
    	
    	return $result;
	}
	
	function fFMPrintDebugOutput(){
		global $gDbgFMQuery;

		echo "<pre>\n";
		echo "<h2>Queries</h2>\n";
		echo $gDbgFMQuery;
		echo "</pre>\n";
	}
	
	function fFMCompoundFind($sFMName, $sLayout, $aSearchCriteria, $aSortCriteria = null, $sScriptName = null, $ThrowOnNoRecords = TRUE, $aSortOrder = null){
		// Globals - Database
		global $gaFM;
		global $gDbgFMQuery;

		// Start time
		$sFMQuery = '';

		// Connect to filemaker
		$fm = new fmREST($gaFM[$sFMName]['host'], $gaFM[$sFMName]['datasource'],  $gaFM[$sFMName]['login'], $gaFM[$sFMName]['password'], $sLayout);
        $fm -> show_debug = false; //turn this to true or "html" to show automatically. We're manually including debug information with <print_r ($fm->debug_array);>
        $fm -> secure = true; //not required - defaults to true
        $fm -> fmversion = 19; 
        
		// Set the layout
		$sFMQuery .= '<b>Layout:</b> '.$sLayout.'<br>';

		// Add Search Criteria
        $fmQuery = $aSearchCriteria;
        $data['query'] = $fmQuery;
        $data['limit'] = 1000;

		// Add Sort Criteria and sort order if specified
		$fmSort = $aSortCriteria;

       $data['sort'] = $fmSort;

		// Add Script
		if ($sScriptName != null)
		{
			$fmCompundRequest->setScript($sScriptName);
			$sFMQuery .= 'Running Script: '.$sScriptName.'<br>';
		}

		// Execute the query


        $result=$fm -> findRecords ($data);
		if ($result['messages'][0]['code'] > 0)
		{
			// filemaker has returned an error
			
			if (!isset($result['messages'][0]['code']) || strlen(trim($result['messages'][0]['code'])) < 1)
			{
				// filemaker did not set error code
				
				fReturnError('Error Performing Find : <br><br><pre>' . $sFMQuery . '</pre><br><br>System Error');
			}
			else if ($result['messages'][0]['code'] == '401')
			{
				// Dont throw error if no records found (401)
				
				$fmResult = FALSE;
			}
			else
			{
				// Throw error and return error code to browser
				
				fReturnError('Error Performing Find : <br><br><pre>' . $sFMQuery . '</pre><br><br>Error: '.$result['messages'][0]['code']);
			}
		}

		return $result;
	}

	//Unused functions below
	function fFMCheckError($fmResult){
		if (FileMaker::isError($fmResult))
		{
			if (isset($fmResult->code) && strlen(trim($fmResult->code)) > 0)
			{
				fReturnError('Error : Error Code: '.$fmResult->code);
			}
			else if ($fmResult->isValidationError())
			{
				$e = $fmResult->getErrors();
				$v = '';
				for ($i = 0; $i < count( $e ); $i++ )
				{
					$v .= $e[$i][0]->getName().'<br>';
				}

				fReturnError('Error : '.$fmResult->numErrors().' Validation Error(s):<br>'.$v);
			}
			else
			{
				fReturnError('Error : System Error:<br>'.$fmResult->getErrorString().'<br>'.$fmResult->getMessage());
			}
		}
	}
?>