<?php
	include 'myDBFunctions.php';
	include 'myUniversalVars.php';
	
	$db = dbConnect();
	$myCampus   = (isset($_POST['campus']) ? $_POST['campus'] : "");
	$myBuilding = (isset($_POST['building']) ? $_POST['building'] : "");
	$myRoom     = (isset($_POST['room']) ? $_POST['room'] : "");
	$myData     = (isset($_POST['data']) ? $_POST['data'] : "");
	
	// Typical POST
	// campus=UIUC&building=Bevier&room=Ricks%20Test%20(php)&data=PROP%7CEpson%205650%7CLamp%20Hours%7C4321%7CSTRING%7C%7Chrs%7C%3E%7C1600%7C2%7CTRUE%7CFALSE%0D%0APROP%7CEpson%205650%7CSerial%20Number%7C1234-56WCA%7CSTRING%7C%7Chrs%7C%3E%7C%7C2%7Cfalse%7CTRUE%0D%0APROP%7CIO%7CSecurity%20Loop%7C-5
	
	function requiredKeysExist(){ // tests to see if all required data included in this POST
		global $myCampus, $myBuilding, $myRoom, $myData;
		if( $myCampus != "" ){
			//echo "$myCampus<br>";
			if( $myBuilding != "" ){
				//echo "$myBuilding<br>";
				if( $myRoom != "" ){
					//echo "$myRoom<br>";
					return true;
				}
			}
		}
		return false;
	}

	function propertyLineToAssocArray($thisLine){ // convert this property line to an associative array...
		// typical property line: (may not contain all values or even the same number of values)
		//    PROP|Epson 5650|Lamp Hours|1234|NUMBER||hrs|>|1600|2|TRUE|FALSE
		
		// key array
		// We are going to combine two arrays into an associative array.
		// The 1st array contains the key names...
		$cols = array ( 'prop', 'device', 'caption', 'value', 'type', 'prefix', 'suffix', 'alertconfig', 'alertvalue', 'alerttype', 'allowreset', 'capitalize' );
		//echo "<br>There are ".count($cols)." slots in this array.<br>";
		
		// value array
		// The 2nd is the actual values from the property line...
		$prpArray = explode("|", $thisLine);
		
		//echo "<br>There are ".count($prpArray)." slots in this array.<br>";
		
		// The values array might not have the same count as the keys array.  
		// We have to pad it so that it does before combining
		
		while (count($prpArray) < count($cols)){
			$prpArray[] = "";
		}
		
		// key/value associative array
		// Now, we can combine the two arrays into an associative array and return the value
		$myProps = array_combine($cols, $prpArray);
		
		// set some default values if not specified... (won't overwrite if existing!)
		if ($myProps['type'] == ""){
			$myProps['type'] = "STRING";
		}
		if ($myProps['alerttype'] == ""){
			$myProps['alerttype'] = "1";
		}
		if ($myProps['alertvalue'] == ""){
			$myProps['alertvalue'] = "0";
		}
		if ($myProps['allowreset'] == ""){
			$myProps['allowreset'] = "1";
		}
		if($myProps['capitalize'] == ""){
			$myProps['capitalize'] = "0";
		}
		
		// some values should always be upper case...
		$myProps['prop']       = strtoupper($myProps['prop']);
		$myProps['type']       = strtoupper($myProps['type']);
		$myProps['allowreset'] = strtoupper($myProps['allowreset']);
		$myProps['capitalize'] = strtoupper($myProps['capitalize']);
		
		// some true/falses need to be converted to 1s/0s...
		if ($myProps['allowreset'] == 'TRUE'){
			$myProps['allowreset'] = "1";
		}elseif ($myProps['allowreset'] == 'FALSE'){
			$myProps['allowreset'] = "0";
		}
		
		if ($myProps['capitalize'] == 'TRUE'){
			$myProps['capitalize'] = "1";
		}elseif ($myProps['capitalize'] == 'FALSE'){
			$myProps['capitalize'] = "0";
		}
		
		// for testing
		/*
		foreach($myProps as $k => $v) {
			echo "$k=$v<br>";
		}
		*/
		
		return $myProps;
	}
	
	function cpLineToAssocArray($thisLine){ // convert this property line to an associative array...
		// typical cp line: 
		//    
		
		// key array
		// We are going to combine two arrays into an associative array.
		// The 1st array contains the key names...
		$cols = array ( 
						'type', // ignore, it will always be 'CP'
						'executable', 
						'args' 
					);
					
		//echo "<br>There are ".count($cols)." slots in this array.<br>";
		
		// value array
		// The 2nd is the actual values from the property line...
		$prpArray = explode("|", $thisLine);
		
		//echo "<br>There are ".count($prpArray)." slots in this array.<br>";
		
		// The values array might not have the same count as the keys array.  
		// We have to pad it so that it does before combining
		
		//echo count($cols)."\n";
		//echo "\n".count($prpArray)."\n";
		
		while (count($prpArray) < count($cols)){
			$prpArray[] = "";
		}
		
		// key/value associative array
		// Now, we can combine the two arrays into an associative array and return the value
		$myProps = array_combine($cols, $prpArray);
		
		// for testing
		/*
		foreach($myProps as $k => $v) {
			echo "$k=$v<br>";
		}
		*/
		
		return $myProps;
	}
	
	function idLineToAssocArray($thisLine){ // convert this id line to an associative array...
		// typical cp line: 
		//    
		
		// key array
		// We are going to combine two arrays into an associative array.
		// The 1st array contains the key names...
		$cols = array ( 
						'id', // ignore, it will always be 'ID'
						'campus',
						'building', 
						'room' 
					);
					
		//echo "<br>There are ".count($cols)." slots in this array.<br>";
		
		// value array
		// The 2nd is the actual values from the property line...
		$prpArray = explode("|", $thisLine);
		
		//echo "<br>There are ".count($prpArray)." slots in this array.<br>";
		
		// The values array might not have the same count as the keys array.  
		// We have to pad it so that it does before combining
		
		//echo count($cols)."\n";
		//echo "\n".count($prpArray)."\n";
		
		while (count($prpArray) < count($cols)){
			$prpArray[] = "";
		}
		
		// key/value associative array
		// Now, we can combine the two arrays into an associative array and return the value
		$myProps = array_combine($cols, $prpArray);
		
		// for testing
		/*
		foreach($myProps as $k => $v) {
			echo "$k=$v<br>";
		}
		*/
		
		return $myProps;
	}
	
	function btnLineToAssocArray($thisLine){ // convert this property line to an associative array...
		// typical cp line: 
		//    
		
		//$cols = array ( 'btn', 'groupname', 'buttonname', 'command' );
		// key array
		// We are going to combine two arrays into an associative array.
		// The 1st array contains the key names...
		$cols = array ( 
						'btn', // ignore, it will always be 'BTN'
						'groupname', 
						'buttonname', 
						'command' 
					);
					
		//echo "<br>There are ".count($cols)." slots in this array.<br>";
		
		// value array
		// The 2nd is the actual values from the property line...
		$prpArray = explode("|", $thisLine);
		
		//echo "<br>There are ".count($prpArray)." slots in this array.<br>";
		
		// The values array might not have the same count as the keys array.  
		// We have to pad it so that it does before combining
		
		while (count($prpArray) < count($cols)){
			$prpArray[] = "";
		}
		
		// key/value associative array
		// Now, we can combine the two arrays into an associative array and return the value
		$myProps = array_combine($cols, $prpArray);
		
		// for testing
		/*
		foreach($myProps as $k => $v) {
			echo "$k=$v<br>";
		}
		*/
		
		return $myProps;
	}
	
	function checkForRequiredPropValues($thisPropArray){ // props must have a minumum of device/caption/value...
		if($thisPropArray['device'] != ""){
			if($thisPropArray['caption'] != ""){
				return true;
			}
		}
		return false;
	}
	
	function alertHandler($ndx){
		global $myOS, $myAlertHandler; // from myUniversalVars.php
		//echo "ALERT!!!\n";
		//echo "$myOS\n";
		if ($myOS=='linux'){
			echo "./$myAlertHandler $ndx &> /dev/null";
			exec("./$myAlertHandler $ndx &> /dev/null &");
		}else{
			echo ".\\$myAlertHandler $ndx > NUL\n";
			exec(".\\$myAlertHandler $ndx > NUL");
		}
	}
	
	function getPropertyAlertStatus($alertConfig, $propType, $currentValue, $alertValue, $alertStatus, $allowReset, $propNdx ){
		$rv = 0;
		
		$alertConfig = trim($alertConfig);
		/*
		echo "AlertConfig = $alertConfig\n";
		echo "Prop Type   = $propType\n";
		echo "current Val = $currentValue\n";
		echo "Alert Val   = $alertValue\n";
		echo "AlertStatus = $alertStatus\n";
		echo "Allow Reset = $allowReset\n";                  
		echo "Prop ID     = $propNdx\n";
		*/
		if ($alertStatus == true){ // if the property is already 'in alert' then...
			//echo "property is already 'in alert'...\n";
			if ($allowReset == false){ // and if we are not allowed to reset this alert automatically then...
				//echo "we are not allowed to reset this alert automatically...\n";
				return $alertStatus; // exit with original status
			}
		}	
		
		if(($propType == "STRING") OR ($propType == "CHAR")){
			//echo "Not a Number!\n";
			switch ($alertConfig){
				case "<>":
					if ($currentValue != $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 1;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "!=":
					if ($currentValue != $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 2;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "==":
					if ($currentValue == $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 3;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "=":
					if ($currentValue == $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 4;
						break;
					}else{
						$rv = 0;
						break;
					}
			}
		}else{ // must be a numeric type
			//echo "Number!\n";
			
			switch ($alertConfig){
				case "<>":
					if ($currentValue != $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 10;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "!=":
					if ($currentValue != $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 11;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "<=":
					if ($currentValue <= $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 12;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "=<":
					if ($currentValue <= $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 13;
						break;
					}else{
						$rv = 0;
						break;
					}
				case ">=":
					if ($currentValue >= $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 14;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "=>":
					if ($currentValue >= $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 15;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "<":
					if ($currentValue < $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 16;
						break;
					}else{
						$rv = 0;
						break;
					}
				case ">":
					if ($currentValue > $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 17;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "==":
					if ($currentValue == $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 18;
						break;
					}else{
						$rv = 0;
						break;
					}
				case "=":
					if ($currentValue == $alertValue){
						if ($alertStatus == false){
							alertHandler($propNdx);
						}
						$rv = 19;
						break;
					}else{
						$rv = 0;
						break;
					}
			}
			
		}
		
		//echo "\nAlertStatus = $rv\n";
		return $rv;
		
	}
	
	function propertyLineToDB($propArray){ // process a Property line
		global $db, $myCampus, $myBuilding, $myRoom;
		static $lastDeviceName = "", $lastPropName = "";
		
		//$cols = array ( 'prop', 'device', 'caption', 'value', 'type', 'prefix', 'suffix', 'alertconfig', 'alertvalue', 'alerttype', 'allowreset', 'capitalize' );
		
		$thisDevice = $propArray['device'];
		$thisProp = $propArray['caption'];
		$thisValue = $propArray['value'];
		$thisType = $propArray['type'];
		$thisPrefix = $propArray['prefix'];
		$thisSuffix = $propArray['suffix'];
		$thisAlertConfig = $propArray['alertconfig'];
		$thisAlertValue = $propArray['alertvalue'];
		$thisAlertType = $propArray['alerttype'];
		$thisAllowReset = $propArray['allowreset'];
		$thisCapitalize = $propArray['capitalize'];
		
		$sql_ri = '
            SELECT c.id FROM tblCampus a
            INNER JOIN tblBuilding b ON a.id=b.idCampus
            INNER JOIN tblRoom c ON b.id=c.idBuilding
            WHERE a.ALTNAME=:campus AND b.ALTNAME=:building AND c.ALTNAME=:room;
        ';
        $sql_ri = $db->prepare($sql_ri);
        $sql_ri->bindParam(':campus', $myCampus);
        $sql_ri->bindParam(':building', $myBuilding);
        $sql_ri->bindParam(':room', $myRoom);
        $sql_ri->execute();
        $room_id = $sql_ri->fetch();
        $room_id = $room_id['id'];
		
		if ($thisDevice != $lastDeviceName){ // new or different device
			$sql_d = '
                INSERT INTO tblDevice (idRoom, NAME, ALTNAME) VALUES (:room_id, :device, :device);
            ';
            $sql_d = $db->prepare($sql_d);
            $sql_d->bindParam(':room_id', $room_id);
            $sql_d->bindParam(':device', $thisDevice);
            
			try{
				//echo "\n$sql_d\n";
				$sql_d->execute();
			}catch(Exception $e){
				//echo "<br>$sql_d<br>";
				//echo 'Message: ' .$e->getMessage();
			}
		}
        
		$sql_di = '
            SELECT d.id FROM tblCampus a
            INNER JOIN tblBuilding b ON a.id=b.idCampus
            INNER JOIN tblRoom c ON b.id=c.idBuilding
            INNER JOIN tblDevice d ON c.id=d.idRoom
            WHERE a.ALTNAME=:campus AND b.ALTNAME=:building AND c.ALTNAME=:room AND d.ALTNAME=:device;
        ';
        $sql_di = $db->prepare($sql_di);
        $sql_di->bindParam(':campus', $myCampus);
        $sql_di->bindParam(':building', $myBuilding);
        $sql_di->bindParam(':room', $myRoom);
        $sql_di->bindParam(':device', $thisDevice);
        $sql_di->execute();
        $device_id = $sql_di->fetch();
        $device_id = $device_id['id'];
		
		try{
			
			// Get the property TYPE and current VALUE for special cases like SUMs and SOURCEs.
			$sql_p = '
                SELECT e.id, e.TYPE, e.VALUE, e.ALERTCONFIG, e.ALERTVALUE, e.ALERTSTATUS, e.ALLOWRESET
                FROM tblCampus a
                INNER JOIN tblBuilding b ON a.id=b.idCampus
                INNER JOIN tblRoom c ON b.id=c.idBuilding
                INNER JOIN tblDevice d ON c.id=d.idRoom
                INNER JOIN tblProperties e ON d.id=e.idDevice
                WHERE a.ALTNAME=:campus AND b.ALTNAME=:building AND c.ALTNAME=:room AND d.ALTNAME=:device AND e.ALTNAME=:property;
            ';
            $sql_p = $db->prepare($sql_p);
            $sql_p->bindParam(':campus', $myCampus);
            $sql_p->bindParam(':building', $myBuilding);
            $sql_p->bindParam(':room', $myRoom);
            $sql_p->bindParam(':device', $thisDevice);
            $sql_p->bindParam(':property', $thisProp);
			$sql_p->execute();
            
			$cnt = $sql_p->rowCount();
			echo "Count=$cnt\n";
			$result = $sql_p->fetch(PDO::FETCH_OBJ);
			if((intval($cnt) == 1) OR (intval($cnt) == -1)) { // then this property already exists
                echo "Property already exists...";
				$propType           =        $result->TYPE;
				$propVal            = intval($result->VALUE);
				$propAlertConfig    =        $result->ALERTCONFIG;
				$propAlertValue     =        $result->ALERTVALUE;
				$propAlertStatus    = intval($result->ALERTSTATUS);
				$propAllowReset     =        $result->ALLOWRESET;
				$propID             = intval($result->id);
				
				//echo "\nproperty already exists\n";
				// if it gets to this point, the property already exists...
				
				// $alertConfig, $propType, $currentValue, $alertValue, $alertStatus, $allowReset
				$paStatus = getPropertyAlertStatus(
															$propAlertConfig,
															$propType,
															$thisValue,
															$propAlertValue,
															$propAlertStatus,
															$propAllowReset,
															$propID
														);
				//echo "AlertStatus = $paStatus\n";
				
				try{
					if(($propType != "SOURCE") AND ($propType != "SUM")){
						$tq = '
                            UPDATE tblProperties
                            SET VALUE=:value, ALERTSTATUS=:alert_status
                            WHERE idDevice=:device_id AND ALTNAME=:property;
                        ';
                        $tq = $db->prepare($tq);
                        $tq->bindParam(':value', $thisValue);
                        $tq->bindParam(':alert_status', $paStatus);
                        $tq->bindParam(':device_id', $device_id);
                        $tq->bindParam(':property', $thisProp);
                        
					}else{
                        $thisValue = intval($thisValue) + intval($propVal);
						$tq = '
                            UPDATE tblProperties
                            SET VALUE=:value, ALERTSTATUS=:alert_status
                            WHERE idDevice=:device_id AND ALTNAME=:property;
                        ';
                        $tq = $db->prepare($tq);
                        $tq->bindParam(':value', $thisValue);
                        $tq->bindParam(':alert_status', $paStatus);
                        $tq->bindParam(':device_id', $device_id);
                        $tq->bindParam(':property', $thisProp);
                    }

					$tq->execute();
					
				}catch(Exception $e){
					//echo "<br>$tq<br>";
					echo 'Update Property: ' .$e->getMessage();
				}
				
			}else{
				try{
					//echo "\nnon-catch insert\n";
					$tq = '
                        INSERT INTO tblProperties VALUES
                        (NULL, :device_id, :property, :property, :value, :type, :prefix, :suffix, :alert_config, :alert_value, :alert_type, 0, :allow_reset, :capitalize);
					';
                    $tq = $db->prepare($tq);
                    $tq->bindParam(':device_id', $device_id);
                    $tq->bindParam(':property', $thisProp);
                    $tq->bindParam(':value', $thisValue);
                    $tq->bindParam(':type', $thisType);
                    $tq->bindParam(':prefix', $thisPrefix);
                    $tq->bindParam(':suffix', $thisSuffix);
                    $tq->bindParam(':alert_config', $thisAlertConfig);
                    $tq->bindParam(':alert_value', $thisAlertValue);
                    $tq->bindParam(':alert_type', $thisAlertType);
                    $tq->bindParam(':allow_reset', $thisAllowReset);
                    $tq->bindParam(':capitalize', $thisCapitalize);
                    $tq->execute();
				}catch(Exception $e){
					echo 'Insert Property: ' .$e->getMessage();
				}
			}
			//echo "\n$propType\n$propVal\n";
			//$tq = "";
			
		}catch(Exception $e){ //if the property doesn't yet exist then
			//echo "\nCouldn't UPDATE, INSERTing...\n";

			try{
                $tq = '
                    INSERT INTO tblProperties VALUES
                    (NULL, :device_id, :property, :property, :value, :type, :prefix, :suffix, :alert_config, :alert_value, :alert_type, 0, :allow_reset, :capitalize);
                ';
                $tq = $db->prepare($tq);
                $tq->bindParam(':device_id', $device_id);
                $tq->bindParam(':property', $thisProp);
                $tq->bindParam(':value', $thisValue);
                $tq->bindParam(':type', $thisType);
                $tq->bindParam(':prefix', $thisPrefix);
                $tq->bindParam(':suffix', $thisSuffix);
                $tq->bindParam(':alert_config', $thisAlertConfig);
                $tq->bindParam(':alert_value', $thisAlertValue);
                $tq->bindParam(':alert_type', $thisAlertType);
                $tq->bindParam(':allow_reset', $thisAllowReset);
                $tq->bindParam(':capitalize', $thisCapitalize);
                $tq->execute();
			}catch(Exception $e){
				//echo 'Message: ' .$e->getMessage();
			}
		}
		
		$lastDeviceName = $thisDevice;
		$lastPropName = $thisProp;
	}
	
	function CPLineToDB($propArray){ // process a Command Processor line
		global $db, $myCampus, $myBuilding, $myRoom;
		static $lastDeviceName = "", $lastPropName = "";
		
		//$cols = array ( 'prop', 'device', 'caption', 'value', 'type', 'prefix', 'suffix', 'alertconfig', 'alertvalue', 'alerttype', 'allowreset', 'capitalize' );
		
		$thisExecutable = $propArray['executable']; // executables are placed into their own table
		$thisArgs = $propArray['args']; // args are unique to ea room and are stored in tblRoom
		
		try{ // see if this CP exists. If not, insert it and associate it with this room...
			$sql_cp = '
                INSERT INTO tblCmdProcs (NAME, ALTNAME) VALUES(:proc, :proc);
            ';
            $sql_cp = $db->prepare($sql_cp);
            $sql_cp->bindParam(':proc', $thisExecutable);
            
			//echo "\n$sql_cp\n";
			if($sql_cp->execute()){ // insert was successful
				$cpID = $db->lastInsertId(); // get the id of this new row
				//echo "\nexecuted insert with id=$cpID\n";
			}else{ // insert failed
				//try{
					$sql_cp = '
                        SELECT id FROM tblCmdProcs WHERE NAME=:proc;
                    ';
                    $sql_cp = $db->prepare($sql_cp);
                    $sql_cp->bindParam(':proc', $thisExecutable);
					$sql_cp->execute();
					$result = $sql_cp->fetch(PDO::FETCH_OBJ);
					$cpID = $result->id;
					//echo "\nexecuted select with id=$cpID\n";
			}
			//echo "\n$cpID\n";
			assignCmdProcToRoom($cpID);
			
		}catch(Exception $e){ // cmd proc already exists..  Just assign to room if not already assigned
			//echo "<br>$sql_p<br>";
			//echo 'Message: ' .$e->getMessage();
			try{
                $sql_cp = '
                    SELECT id FROM tblCmdProcs WHERE NAME=:proc;
                ';
                $sql_cp = $db->prepare($sql_cp);
                $sql_cp->bindParam(':proc', $thisExecutable);
                $sql_cp->execute();
                $result = $sql_cp->fetch(PDO::FETCH_OBJ);
                $cpID = $result->id;
				//echo "\nexecuted select with id=$cpID\n";
				assignCmdProcToRoom($cpID);
			}catch(Exception $e){
				echo 'Message: ' .$e->getMessage();
			}
		}
	}
	
	function assignCmdProcToRoom($cpID){
		global $db, $myCampus, $myBuilding, $myRoom;
		
		$sql_ri = '
            SELECT c.id FROM tblCampus a
            INNER JOIN tblBuilding b ON a.id=b.idCampus
            INNER JOIN tblRoom c ON b.id=c.idBuilding
            WHERE a.ALTNAME=:campus AND b.ALTNAME=:building AND c.ALTNAME=:room;
        ';
        $sql_ri = $db->prepare($sql_ri);
        $sql_ri->bindParam(':campus', $myCampus);
        $sql_ri->bindParam(':building', $myBuilding);
        $sql_ri->bindParam(':room', $myRoom);
        $sql_ri->execute();
        $room_id = $sql_ri->fetch();
        $room_id = $room_id['id'];
        
		try{
			// see if this room has a command processor assigned
			$sql_cp = 'SELECT idCmdProcs FROM tblRoom WHERE id=:room_id;';
			//echo "\n$sql_cp\n";
			$sth = $db->prepare($sql_cp);
            $sth->bindParam(':room_id', $room_id);
			$sth->execute();
			$result = $sth->fetch(PDO::FETCH_OBJ);
			$currentCPid = $result->idCmdProcs;
			if (intval($currentCPid) < 1){ 
				$currentCPid="-1";
			}
			//echo "\n$currentCPid\n";
			if (!(intval($currentCPid) > 0)){ // this room does not have a command processor, assign one here...
				//echo "\n$cpID\n";
				$sql = 'UPDATE tblRoom SET idCmdProcs=:proc_id WHERE id=:room_id;';
                $sql = $db->prepare($sql);
                $sql->bindParam(':proc_id', $cpID);
                $sql->bindParam(':room_id', $room_id);
				$sql->execute();
				//echo "\nexecuted update\n";
			}
		}catch(Exception $e){ // if there is an error, probably because control proc was never assigned, so assign it here...
			echo 'Message: ' .$e->getMessage();
            $sql = 'UPDATE tblRoom SET idCmdProcs=:proc_id WHERE id=:room_id;';
            $sql = $db->prepare($sql);
            $sql->bindParam(':proc_id', $cpID);
            $sql->bindParam(':room_id', $room_id);
            $sql->execute();
			//echo "\nexecuted update\n";
		}
	}
	
	function BTNLineToDB($propArray){ // process a Button line
		global $db, $myCampus, $myBuilding, $myRoom;
		
		//$cols = array ( 'btn', 'groupname', 'buttonname', 'command' );
		
		$thisGroup = $propArray['groupname']; // executables are placed into their own table
		$thisButton = $propArray['buttonname']; // args are unique to ea room and are stored in tblRoom
		$thisCommand = $propArray['command']; // args are unique to ea room and are stored in tblRoom

		$sql_ri = '
            SELECT c.id FROM tblCampus a
            INNER JOIN tblBuilding b ON a.id=b.idCampus
            INNER JOIN tblRoom c ON b.id=c.idBuilding
            WHERE a.ALTNAME=:campus AND b.ALTNAME=:building AND c.ALTNAME=:room;
        ';
        $sql_ri = $db->prepare($sql_ri);
        $sql_ri->bindParam(':campus', $myCampus);
        $sql_ri->bindParam(':building', $myBuilding);
        $sql_ri->bindParam(':room', $myRoom);
        $sql_ri->execute();
        $room_id = $sql_ri->fetch();
        $room_id = $room_id['id'];
        
		try{ // insert 
			$sql_cp = '
                INSERT INTO tblButtons ( idRoom, GROUPNAME, ALTGROUPNAME, BTNNAME, ALTBTNNAME, COMMAND, ALTCOMMAND ) VALUES(:room_id, :group_name, :group_name, :button_name, :button_name, :command, :command);
            ';
            $sql_cp = $db->prepare($sql_cp);
            $sql_cp->bindParam(':room_id', $room_id);
            $sql_cp->bindParam(':group_name', $thisGroup);
            $sql_cp->bindParam(':button_name', $thisButton);
            $sql_cp->bindParam(':command', $thisCommand);
            $sql_cp->execute();
		}catch(Exception $e){ // cmd proc already exists..  Just assign to room if not already assigned
			//echo 'Message: ' .$e->getMessage();
		}
	}
	
	function processLine($thisLine){ // process a single PROP/CP/BTN line...
		global $myCampus, $myBuilding, $myRoom;
		static $lastLineType = "";
		// get the 1st col of this line, should be PROP or CP or BTN...
		$upLine = substr( strtoupper($thisLine), 0, strpos($thisLine, "|"));
		//echo "\n$upLine\n";
		switch ($upLine){
			case "PROP":
				if ( requiredKeysExist() ){ 
					// convert this line(str) to a properly formatted assoc array
					$thisPropArray = propertyLineToAssocArray($thisLine);
					// save to db
					
					if (checkForRequiredPropValues($thisPropArray)){ // if the line has the MINIMUM required data...
						propertyLineToDB($thisPropArray);//processProperty();
						//echo "<br>ok<br>";
					}
					$lastLineType = "PROP";
				}
				break;
			case "ID":    // Identifies campus/building/room
				$lastLineType = "ID";
				$thisIDArray = idLineToAssocArray($thisLine);
				$myCampus   = $thisIDArray['campus'];
				$myBuilding = $thisIDArray['building'];
				$myRoom     = $thisIDArray['room'];
				echo "$myCampus/$myBuilding/$myRoom\n";
				if ( requiredKeysExist() ){ 
					insertCampusBuildingRoom($myCampus, $myBuilding, $myRoom); 
				}
				break;
			case "CP":    // Command Processor
				if ( requiredKeysExist() ){ 
					$lastLineType = "CP";
					$thisCPArray = cpLineToAssocArray($thisLine);
					CPLineToDB($thisCPArray);
				}
				break;
			case "BTN":   // Button
				if ( requiredKeysExist() ){ 
					$lastLineType = "BTN";
					$thisBTNArray = btnLineToAssocArray($thisLine);
					BTNLineToDB($thisBTNArray);
				}
				break;
		}
	}
	
	function insertCampusBuildingRoom($campus, $building, $room){ // inserts this campus/building/room in the database...
		global $db;
		// at this point, campus, building an droom are validated, so we can insert them
		$sql_c = 'INSERT INTO tblCampus (NAME, ALTNAME) VALUES (:campus, :campus);';
		$sql_ci = 'SELECT id FROM tblCampus WHERE ALTNAME=:campus;';
		$sql_b = 'INSERT INTO tblBuilding (idCampus, NAME, ALTNAME) VALUES (:campus_id, :building, :building);';
		$sql_bi = 'SELECT id FROM tblBuilding WHERE ALTNAME=:building AND idCampus=:campus_id;';
		$sql_r = 'INSERT INTO tblRoom (idBuilding, NAME, ALTNAME, ONLINE) VALUES (:building_id, :room, :room, 5);';
		$sql_ri = 'SELECT id FROM tblRoom WHERE ALTNAME=:room AND idBuilding=:building_id;';
		
		if( ($campus != "") AND ($building != "") AND ($room != "") ){
			
			//echo "Inserting CBR...\n";
		
			try{
                $sql_c = $db->prepare($sql_c);
                $sql_c->bindParam(':campus', $campus);
				$sql_c->execute();
				//echo "<br>$sql_c<br>";
			}catch(Exception $e){
				//echo "<br>$sql_c<br>";
				echo 'MessageC: ' .$e->getMessage();
			}

			try{
                $sql_ci = $db->prepare($sql_ci);
                $sql_ci->bindParam(':campus', $campus);
				$sql_ci->execute();
                $campus_id = $sql_ci->fetch();
                $campus_id = $campus_id['id'];

                $sql_b = $db->prepare($sql_b);
                $sql_b->bindParam(':campus_id', $campus_id);
                $sql_b->bindParam(':building', $building);
				$sql_b->execute();
			}catch(Exception $e){
				echo 'MessageB: ' .$e->getMessage();
			}

			try{
                $sql_bi = $db->prepare($sql_bi);
                $sql_bi->bindParam(':campus_id', $campus_id);
                $sql_bi->bindParam(':building', $building);
				$sql_bi->execute();
                $building_id = $sql_bi->fetch();
                $building_id = $building_id['id'];

                $sql_r = $db->prepare($sql_r);
                $sql_r->bindParam(':building_id', $building_id);
                $sql_r->bindParam(':room', $room);
				$sql_r->execute();
			}catch(Exception $e){
				//echo 'MessageR: ' .$e->getMessage();
			}
			
			// Update the ONLINE col of tblRoom to show that this room is 'online'...
			try{
                $sql_ri = $db->prepare($sql_ri);
                $sql_ri->bindParam(':building_id', $building_id);
                $sql_ri->bindParam(':room', $room);
				$sql_ri->execute();
                $room_id = $sql_ri->fetch();
                $room_id = $room_id['id'];
                
				$tq = 'UPDATE tblRoom SET ONLINE=5 WHERE id=:room_id;';
                $tq = $db->prepare($tq);
                $tq->bindParam(':room_id', $room_id);
                $tq->execute();
				//echo "<br>$tq<br>";
			}catch(Exception $e){
                //echo $sql_ri;
				//echo 'MessageR: ' .$e->getMessage();
			}
		}
	}
	
	if (requiredKeysExist()){
		insertCampusBuildingRoom($myCampus, $myBuilding, $myRoom); // make sure campus/building/room exist in this database
	}
	// All properties processed below...

	// make sure we have a common line terminator (\n) in $myProperties
	$order = array("\r\n", "\r");
	
	// $myProperties = all property lines within the POST, reformatted to a common EOL.
	$myProperties = str_replace($order, "\n", $myData); 
    $myProperties = str_replace("\0", "", $myProperties);

    error_log("ID|$myCampus|$myBuilding|$myRoom\n$myProperties\n\$\$\$END\n", 3, "/tmp/usm_server.log");
	
	// create an array of strings, each responding to a property line...
	$myLines = explode("\n", $myProperties);
	
	// go through the array, one string at a time...
	foreach ($myLines as $thisLine){
		//echo "\n\n>>>$thisLine\n\n";
		processLine($thisLine); // and process each line...
    }
?>

