<?php
header('Cache-Control: no-cache, no-store, must-revalidate');   
header('Expires: 0');
$mFunction  		= $_GET['function'];
$mConnection 		= $_GET['connection'];
$mTranType 			= $_GET['trantype'];
$mCompany			= $_GET['company'];
$mDbHost 			= $_GET['host'];
$mDbUser 			= $_GET['user'];
$mDbPwd 			= $_GET['pword'];
$mDbase 			= $_GET['dbase'];

$mTranId = null;
$mColString = "";
$mRow = array();
$mReturnData = array();
$mFieldDefaults = array();

$i=1;

$mPath = "";
$mSystem = "";
$mUser = "";						  
$mMenu = "";
// $mDbHost = "";
// $mDbUser = "";
// $mDbPwd = "";
// $mDbase = "";
$mMqServer = "";
$mTranDef = "trandef";

$mTranType = strToUpper($mTranType);

// Return Header String for Columns - Hard-coded based on Transaction Definition
if (($mFunction != null) && ($mFunction == "column"))
{
	$mColString = "label,input,content,id,name,state,hidden,prefix,sequence,validation,formattedinput,screenoption,preprocess";
	echo ($mColString);
	return;
}

// Parse XML Transaction Definition to build Screen
if (($mFunction != null) && ($mFunction == "row"))
{
// Get System Defaults (Prefix, etc..)
	if (($mDbHost) && ($mDbHost != "") && ($mDbHost != null))
	{
		$mFieldDefaults = defaultSetting($mDbHost,$mDbUser,$mDbPwd,$mDbase,$mCompany);
//		print_r("FAIL-TEST3-".$mFieldDefaults[0]['fieldname']);
	}
	else
	{
		$mFieldDefaults = getDefaultSettings($mConnection, $mCompany);
//		print_r("FAIL-TEST4-".$mFieldDefaults);
	}
// Check for Transaction Root Folder in TranType
	if (strpos($mTranType, "/") === false)
		$mTranType = "trandef/".$mTranType;
// Get Transaction Definition XML from URL
	$mData = file_get_contents(strtolower($mTranType).".xml");
	if ($mData == "")
	{
        exit("FAIL-Unknown Transaction Type");
	}
// Parse XML to XML Object Array
	$xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
	
// Split-out Transaction Definitions from XML 'fields' Nodes
	$i = 0;
	for ($i = 0; $i <= 50; $i++)
	{	
		$mName = "";
		$mValidation = "";
		$mInput = "";
		$mContent = "";
		$mFormattedInput = "";
		$mScreenOption = "";
		$mStatus = "";
		$mPath = "";
        $mPreprocess = "";
	
		$mName = "".$xml->fields->field[$i]->name."";
	
		if  ((($mName == "") || ($mName == false)) && ($i > 0))
			break;
		if 	(($mName == "") && ($i == 0))
		{
			$mLabel = "No Transaction - ".$mTranType;
			break;
		}
// Split-out Transaction Row elements	
		$mLabel = "".$xml->fields->field[$i]->label."";
		$mContent = "".$xml->fields->field[$i]->content."";
		$mInput = "".$xml->fields->field[$i]->input."";
		$mState = "".$xml->fields->field[$i]->state."";
		$mHidden = "".$xml->fields->field[$i]->hidden."";
		$mPrefix = "".$xml->fields->field[$i]->prefix."";
		$mSequence = "".$xml->fields->field[$i]->sequence."";
		$mValidation = "".$xml->fields->field[$i]->validation."";
		$mScreenOption = "".$xml->fields->field[$i]->screenoption."";
		$mStatus = "".$xml->fields->field[$i]->status."";
		$mPath = "".$xml->fields->field[$i]->path."";
		$mPreprocess = "".$xml->fields->field[$i]->preprocess."";

// Try to get related TransactionId
		if ($mName == "transactionType.id")
		{
//			$mDataTrnId = file_get_contents($mConnection."getTransactionDefinitionByShortCode?shortCode=".$mContent);
//			if ($mDataTrnId)
//			{
//				$xmlTrnId = simplexml_load_string($mDataTrnId, 'SimpleXMLElement', LIBXML_NOCDATA);
//				$mContent = "".$xmlTrnId->fields->field[0]->content."";
//			}
		}
	
		if ($mSequence == "")
			$mSequence = $i+1;
	
		$mLabel = substr($mLabel,0,20);
		$mInput = substr($mInput,0,25);
		$mContent = substr($mContent,0,20);
	
		$mState = "input";
	
		if ($mInput == false)
			$mInput = "";
		if ($mHidden == false)
			$mHidden = "false";
		if ($mContent == false)
			$mContent = "";
		if ($mScreenOption == false)
			$mScreenOption = "";
		if ($mValidation == false)
			$mValidation = "";
		if ($mState == false)
			$mState = "input";

// Initialise Screen 1 Format for Multi-Screen Transactions
// Codes - 	"H" - Input Hidden
//        	"I" - Input
//			"V" - Input Validate against passed Content
//			"P"	- Input Protected
//			"O" - Output
// 			"X"	- Input Excluded (like "H" but values ignored by "POST" function)
//			"*" - Input Password Format
//		if (substr($mScreenOption,0,1) == "H")
//			$mHidden = "true";
        if (!$mHidden || $mHidden == null || $mHidden == "")
            $mHidden = "false";
		if (substr($mScreenOption,0,1) == "I")
			$mState = "input";
		if (substr($mScreenOption,0,1) == "V")
			$mState = "input-validate";
		if (substr($mScreenOption,0,1) == "P")
			$mState = "input-protect";
		if (substr($mScreenOption,0,1) == "O")
			$mState = "output";
		if (substr($mScreenOption,0,1) == "X")
		{
			$mHidden = "true";
			$mState = "output";
		}
		if (substr($mScreenOption,0,1) == "*")
			$mState = "input-password";
	
		if (substr($mScreenOption,0,1) == "")
		{
			$mScreenOption = "P";
			If ($mState == "input")	
				$mScreenOption = "I";
			If ($mState == "output")
				$mScreenOption = "O";
			If ($mState == "input-validate")
				$mScreenOption = "V";
			If ($mState == "input-password")
				$mScreenOption = "*";
			If ($mHidden == "true")
				$mScreenOption = "H";
			if (($mHidden == "true") && ($mState == "output"))
				$mScreenOption = "X";
		}

// $mValidation types are:
// validate - Return Validation Status from Server
// return   - Return Validation Status & Replace Input Value with Server Data
// refresh  - Return Validation Status & Refresh Screen / transaction Data
// post     - Post Screen Data to Server
// update   - Direct Update	

// for testing - populate altPartNumber validation
//	if  (($mName == "altPartNumber") && ($mValidation == ""))
//	{
// Field Names between '/' will be replaced with related Screen data when processed by HTML
//		$mValidation = "replace:getVendorPart?partNumber=/partNumber/&vendorPartString=/altPartNumber/";
//	}
// Testing - populate partNumber validation
//	if (($mName == "partNumber") && ($mValidation == ""))
//	{
//		$mValidation = "validate:getSuggestedLocation?partNumber=/partNumber/";
//	}
// Testing Screen Option - Start
//	if (($mName == "toLocationCode") && (($mValidation == "") || ($mValidation == false)))
//	{
//		$mState = "input";
//		$mHidden = "true";
//		$mScreenOption = "HIP";
//		$mValidation = "validate:getSuggestedLocation?partNumber=/partNumber/,post:postTransaction";
//	}
//	else
//	{	
//		if ($mHidden == "true")
//			$mScreenOption = trim($mScreenOption)."HH";
//		else
//			$mScreenOption = trim($mScreenOption)."PI";
//	}
// Testing Screen Option - End

// Populate "formattedInput" for Hidden Fields
		if (($mHidden == "true") && ($mFormattedInput == ""))
			$mFormattedInput = $mContent;
	
// Replace escape Char. '&' with '|AND|'
		$mValidation = str_replace("&","|AND|",$mValidation);

		if (($mName == "") || ($mName == false))
			break;
		
		if ($mPrefix != "*")
		{
// Apply Company Defaults to Transaction Row (Prefix, etc..)
//		$mDefaults = array();
			$c = 0;
			$mDefaultPrefix = "";
			if ($mCompany != "")
			{
//				$mDefaults = getDefaultSettings($mConnection, $mCompany);
				foreach ($mFieldDefaults as $mDefault)
				{
					if (strtolower($mName) == strtolower($mDefault['fieldname']))	
					{
						$mDefaultPrefix = $mDefault['prefix'];
						$c++;
						break;
					}		
				}
			}
			if ($mDefaultPrefix != "")
				$mPrefix = $mDefaultPrefix;
		}
		else
			$mPrefix = "";
		
//		if ($mContent == "")
//			$mContent = $mPrefix;
// Create Object Array of Complete Transaction Definition
		$mReturnData[$i] = array(
						   "label" => $mLabel,
						   "status" => $mStatus,
						   "input" => $mInput,
						   "content" => $mContent,
						   "id" => $i+1, 
						   "name" => $mName,
						   "state" => $mState,
						   "hidden" => $mHidden,
						   "prefix" => $mPrefix,
						   "sequence" => $mSequence,
						   "validation" => $mValidation,
						   "formattedinput" => $mFormattedInput,
						   "screenoption" => $mScreenOption,
						   "path"=>$mPath,
						   "preprocess"=>$mPreprocess
						   );
						   
		if (($mName == "") || ($mName == false))
			break;
	}
	
//	Return Transaction Definition
	echo json_encode($mReturnData);
	return;
}
// Dynamic Buttons
// Parse XML Button Definition
if (($mFunction != null) && ($mFunction == "button"))
{
	if (strpos($mTranType, "/") === false)
		$mTranType = "trandef/".$mTranType;
// Get Button Definition XML from URL
//	$mData = file_get_contents($mConnection."getTransactionDefinitionByShortCode?shortCode=".$mTranType);
	$mData = file_get_contents(strtolower($mTranType).".xml");
	if ($mData == "")
	{
	}
// Parse XML to XML Object Array
	$xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
	
// Split-out Button Definitions from XML 'fields' Nodes
	$i = 0;
	for ($i = 0; $i <= 50; $i++) 
	{	
	$mName = "";
	$mText = "";
	$mAction = "";
	$mAltKey = "";
	$mScreenOption = "";
	$mValidation = "";
    
	$mName = "".$xml->buttons->button[$i]->name."";
	$mText = "".$xml->buttons->button[$i]->text."";
	$mAction = "".$xml->buttons->button[$i]->action."";
	$mAltKey = "".$xml->buttons->button[$i]->altkey."";
	$mScreenOption = "".$xml->buttons->button[$i]->screenoption."";
    $mValidation = "".$xml->buttons->button[$i]->validation."";
	
	if (($mName == "") || ($mName == false))
		break;
	
// Create Object Array of Complete Button Definition
	$mReturnData[$i] = array(
						   "name" => $mName,
						   "text" => $mText,
						   "action" => $mAction, 
						   "altkey" => $mAltKey,
						   "screenoption" => $mScreenOption,
                           "validation"=>$mValidation
						   );
						   
	}
	
//	Return Transaction Definition
	echo json_encode($mReturnData);

	return;
}

// User Settings
// Parse XML Button Definition
if (($mFunction != null) && ($mFunction == "usersettings"))
{
	
// Get User Definition XML from URL
	$mData = file_get_contents("../../vimsconfig/usersettings.xml");
	if ($mData == "")
	{
	}
// Parse XML to XML Object Array
	$xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
	
// Split-out User Definitions from XML 'fields' Nodes
	$i = 0;
	$mUser = "";
	$mMenu = "";
	$mPath = "";
	$mSystem = "";
	$mCompany = "";
	$mMqServer = "";
	$mStatus = "";
	for ($i = 0; $i <= 150; $i++) 
	{	
		if (("".$xml->users->user[$i]->name."" == "") || ("".$xml->users->user[$i]->name."" == false) || ("".$xml->users->user[$i]->name."" == false))
			break;
		
		$mUser = "".$xml->users->user[$i]->name."";
		if (($mUser == "") || ($mUser == false))
			break;
		
		if ((strtolower($mUser) == "default") && ($mSystem == ""))
		{
			$mUser = $mTranType;
			$mStatus = "".$xml->users->user[$i]->status."";
			$mLabel = "".$xml->users->user[$i]->label."";
			$mPath = "".$xml->users->user[$i]->path."";
			$mMenu = "".$xml->users->user[$i]->menu."";
			$mSystem = "".$xml->users->user[$i]->system."";
			$mCompany = "".$xml->users->user[$i]->company."";
			$mDbHost = "".$xml->users->user[$i]->dbhost."";
			$mDbUser = "".$xml->users->user[$i]->dbuser."";
			$mDbPwd = "".$xml->users->user[$i]->dbpwd."";
			$mDbase = "".$xml->users->user[$i]->dbase."";
			$mMqServer = "".$xml->users->user[$i]->mqserver."";			
		}
		else if (strToUpper($mUser) == $mTranType)
		{
			$mStatus = "".$xml->users->user[$i]->status."";
			$mLabel = "".$xml->users->user[$i]->label."";
			$mPath = "".$xml->users->user[$i]->path."";
			$mMenu = "".$xml->users->user[$i]->menu."";
			$mSystem = "".$xml->users->user[$i]->system."";
			$mCompany = "".$xml->users->user[$i]->company."";
			$mDbHost = "".$xml->users->user[$i]->dbhost."";
			$mDbUser = "".$xml->users->user[$i]->dbuser."";
			$mDbPwd = "".$xml->users->user[$i]->dbpwd."";
			$mDbase = "".$xml->users->user[$i]->dbase."";
			$mMqServer = "".$xml->users->user[$i]->mqserver."";
			break;
		}

		if (($mUser == "") || ($mUser == false) || ($mUser == null))
			break;
	}

// Get System-wide settings if required
	if (($mPath == "") && ($mSystem != ""))
	{
		$mUser = $mTranType;
// Get System Definition XML from URL
		$mData = file_get_contents("../../vimsconfig/systemsettings.xml");
// Parse XML to XML Object Array
		$xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
// Split-out User Definitions from XML 'fields' Nodes
		$i = 0;

		for ($i = 0; $i <= 150; $i++) 
		{			
			$mSystemId = "";
			$mPath = "";
			$mMqServer = "";
			$mCompany = "";

			if (("".$xml->systems->system[$i]->systemid."" == "") || ("".$xml->systems->system[$i]->systemid."" == false) || ("".$xml->systems->system[$i]->systemid."" == false))
				break;
		
			$mSystemId = "".$xml->systems->system[$i]->systemid."";
			if (($mSystemId == "") || ($mSystemId == false))
				break;
		
			if (strToUpper($mSystem) == strToUpper($mSystemId))
			{

				$mPath = "".$xml->systems->system[$i]->path."";
				if ($mMenu == "")
					$mMenu = "".$xml->systems->system[$i]->menu."";
				$mCompany = "".$xml->systems->system[$i]->company."";
				$mDbHost = "".$xml->systems->system[$i]->dbhost."";
				$mDbUser = "".$xml->systems->system[$i]->dbuser."";
				$mDbPwd = "".$xml->systems->system[$i]->dbpwd."";
				$mDbase = "".$xml->systems->system[$i]->dbase."";
				$mMqServer = "".$xml->systems->system[$i]->mqserver."";
				$mTranDef = "".$xml->systems->system[$i]->trandef."";
				break;
			}
			if (($mSystemId == "") || ($mSystemId == false))
				break;
		}
	}
// If no User Settings Get System Default Settings
	if ($mSystem == "")
	{
		include("../../vimsconfig/phpConfig.php");
		$mConnection = defaultDbConnectionVal("DEFAULT");
		$mConnectionVals = explode(",",$mConnection);
		$mPath = $mConnectionVals[0];
		$mDbHost = $mConnectionVals[1];
		$mDbUser = $mConnectionVals[2];
		$mDbPwd = $mConnectionVals[3];
		$mDbase = $mConnectionVals[4];
		$mUser = $mTranType;
		$mMenu = "MENU1";
		$mTranDef = "TRANDEF";
	}
	$mUser = $mTranType;
	$mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbase) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error().":".$mConnection);
//	$mDataQuery = "SELECT company_name FROM company JOIN user ON user.company_id=company.id WHERE user.user_id='".$mUser."' LIMIT 1";
	$mDataQuery = "SELECT company_name FROM company JOIN user ON user.version=company.id WHERE user.username='".$mUser."' LIMIT 1";
// mysql query construct
	if(!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
	$mData = mysqli_query($mConnection,$mDataQuery);
	if (mysqli_num_rows($mData) == 0)
	{
		$mDataQuery = "SELECT company_name FROM company LIMIT 1";
		if(!mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection).$mDataQuery);
			$mData = mysqli_query($mConnection,$mDataQuery);
	}
	$i = 0;
	$mCompany = "";
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$mCompany =($mRow['company_name']);
//			$mSystem =($mRow['company_name']);
		$i++;
	}
	mysqli_close($mConnection);
	
//	$mReturnData[$i] = array(
//						   "user" => "gth",
//						   "menu" => "RSTC",
//						   "path" => "http://172.16.1.33:8080/Vantec/sequence/" 
//	);

//	Return Transaction Definition
	if ($mSystem != "")
		$mReturnData[0] = array(
						"user"   => $mUser,
						"status" => $mStatus,
						"menu"   => $mMenu,
						"path"   => $mPath,
						"system" => $mLabel,
						"company" => $mCompany,
						"dbhost" => $mDbHost,
						"dbuser" => $mDbUser,
						"dbpwd" => $mDbPwd,
						"dbase" => $mDbase,
						"mqserver" => $mMqServer,
						"trandef" => $mTranDef
		);	
	echo json_encode($mReturnData);
	return;
}

// Parse XML Transaction Definition to build Screen
if (($mFunction != null) && ($mFunction == "screen"))
{
	$mData = file_get_contents("http://172.16.1.33:8080/Vantec/sequence/getTransactionDefinitionByShortCode?shortCode=RSTC");

	$xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);

	$i = 0;
	for ($i = 0; $i <= 50; $i++) {
	$mName = "".$xml->fields->field[$i]->name."";
	if ($mName == "")
		Break;
	$mLabel = "".$xml->fields->field[$i]->label."";
	$mInput = "".$xml->fields->field[$i]->input."";
	$mContent = "".$xml->fields->field[$i]->content."";
	$mState = "".$xml->fields->field[$i]->state."";
	$mHidden = "".$xml->fields->field[$i]->hidden."";
	$mPrefix = "".$xml->fields->field[$i]->prefix."";
	$mReturnData[$i] = urlEncode(array("id" => $i+1, 
						   "name" => $mName,
						   "label" => $mLabel,
						   "input" => $mInput,
						   "content" => $mContent,
						   "state" => $mState,
						   "hidden" => $mHidden,
						   "prefix" => $mPrefix
						   ));
	}

	echo json_encode($mReturnData);

	return;
}

// Get Comapny Default validation Settings
function defaultSetting($mDbHost,$mDbUser,$mDbPwd,$mDbase,$mCompany)
{
// Defaults Array
	$mDefaults = array();
// mysql connection
	$mConnection=mysqli_connect($mDbHost,$mDbUser,$mDbPwd,$mDbase) or
		exit("FAIL-Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
		
	$mDataQuery = "SELECT field_name AS fieldname, prefix_name AS prefix, min AS min, max AS max, system_generated AS systemgenerated FROM default_setting";
// mysql query construct
	if(!$mData = mysqli_query($mConnection,$mDataQuery))
		exit("FAIL-".mysqli_error($mConnection));
	$i = 0;
	while($mRow = mysqli_fetch_assoc($mData)) 
	{
		$mDefaults[] =($mRow);
		$i++;
	}
	mysqli_close($mConnection);
//	print_r("FAIL-TEST2-".$mDefaults[0]['fieldname'].$mDefaults[0]['prefixname']."-".$i);
	return $mDefaults;	
}

function getDefaultSettings($mConnection, $mCompany)
{
	$mReturnData = array();
    $mData = "";
	if ($mConnection != "")
	{
		try 
		{
			$mData = file_get_contents($mConnection."defaultSettings?company=".$mCompany);
			if ($mData === false) 
			{
//				exit("FAIL-No Default Settings for Company - ".$mCompany." at ".$mConnection);
			}
		} 
		catch (Exception $e) 
		{
			exit("FAIL-Connection Error at - ".$mConnection.":".$mCompany.":".$e);
		}
	
        if (($mData == "") || ($mData == null))
        {
            $mReturnData[] = array(
                "fieldname" => "partNumber",
                "prefix" => "",
                "min" => "0",
                "max" => "100",
                "systemgenerated" => "0"
            );
        }
        else
        {
            $json = json_decode($mData, true);
            $i = 0;
            foreach ($json as $key => $val) 
            {
                if(is_array($val)) 
                {
                    foreach($val as $key1 => $val1)
                    {
                        if (strtolower($key1) == "fieldname")
                            $mFieldName = $val1;
                        if (strtolower($key1) == "prefixname")
                            $mPrefixName = $val1;
                        if (strtolower($key1) == "min")
                            $mMin = $val1;
                        if (strtolower($key1) == "max")
                            $mMax = $val1;
                        if (strtolower($key1) == "systemgenerated")
                            $mSystemGenerated = $val1;
    //					exit("FAIL-1 ".$key1.":".$val[0][1].":".$mData);
                    }
                } 
                else 
                {
                    exit("FAIL-2 ".$json.":".$key.":".$val);
                }
                $mReturnData[$i] = array(
                            "fieldname" => $mFieldName,
                            "prefix" => $mPrefixName,
                            "min" => $mMin,
                            "max" => $mMax,
                            "systemgenerated" => $mSystemGenerated
                            );
                $i++;
            }
/*
            $xml = simplexml_load_string($mData, 'SimpleXMLElement', LIBXML_NOCDATA);
            for ($i = 0; $i <= 50; $i++) 
            {
                $mFieldName = "".$xml->item[$i]->fieldName."";
                if ($mFieldName == "")
                    Break;
                $mPrefixName = "".$xml->List->item[$i]->prefixName."";
                $mMin = "".$xml->List->item[$i]->min."";
                $mMax = "".$xml->List->item[$i]->max."";
                $mSystemGenerated = "".$xml->List->item[$i]->systemGenerated."";
                $mReturnData[$i] = array( 
                               "fieldname" => $mFieldName,
                               "prefix" => $mPrefixName,
                               "min" => $mMin,
                               "max" => $mMax,
                               "systemgenerated" => $mSystemGenerated
                               );
            }
            if (($i == 0) && ($mFieldName == ""))
            {
                $mReturnData[$i] = array(
                                "fieldname" => "partNumber",
                               "prefix" => "",
                               "min" => "0",
                               "max" => "100",
                               "systemgenerated" => "0",
                               );
            }
*/
        }
	}
	return $mReturnData;
}
?>