<?php

include_once '_dirinfo.php';
require_once(PATH_TO_ROOT."webcati/_class/class.RM_AsteriskManager.php");

class RM_AsteriskManager_predictive extends RM_AsteriskManager {

	public $projectParameters;
	private $AvailableQueueUsers;
	private $sip_internal;
	private $startCallTime;
	private $TelLogID;
	public $TelNumberContainer;
	
	/*
	 * 1 - successful bridge to internal line
	 * 11 - error bridgeing the internal and external channel
	 * 12 - error sending GetRquest for bridge packet
	 * 21 - there is no internal SIP available for join in 60s
	 */
	private $BridgeStatus;
	
	public $selectedTelephone;
	public $selectedNetwork;
	public $selectedRegion;
	public $selectedIndex;
	public $isAppointment;
				
	public $id_project;
	public $tel_name;
	public $tren_tabl;
	public $DialOutside_actionID;
	
	
	public function ConnectDB($host_to_connect, $host_username, $host_password) {
		$link = mysql_connect($host_to_connect, $host_username, $host_password);
		if (!$link) {
			$this->AM_LogWrite_predictive("MySQL connect: false");
			return false;
		}
		$this->AM_LogWrite_predictive("MySQL connect: true");
		
		return $link; 
	}
	
	public function Close($link) {
		mysql_close($link);
	}
	
	
	public function SetParameters($param) {
		$this->projectParameters = $param;
	}
	
	
	public function DialInside($interna_stevilka, $Context, $CallerID, $PredictiveExt) {
		$actionID = $this->GetActionID();
		
		$arrLoginPairs = array("Action" => "Originate", 
								"Channel" => "SIP/".$interna_stevilka,
								"Context" => $Context, 
								"Exten" => $PredictiveExt,
								"Priority" => "1",
								"Callerid" => $CallerID, 
								"Timeout" => "15000",
								"Variable" => "RMpredictiveinside=".$actionID,
								"ActionID" => $actionID);
		
		$strAddPairs = $this->AddPair_AM($arrLoginPairs);
		
		// write Asterisk command pair to LOG file
		$this->AM_LogWrite_predictive("----- DialInside ------\r\n".$strAddPairs."----- END Dial ------\r\n\r\n");
		
		if ($this->SendPacket($strAddPairs) == true) {
			// check if login was success or failure
			$this->FindTime = $this->TimeNow(20); // set the timer for searching for my packet
			$this->AM_LogWrite_predictive("Curent time=".time().". Timer (this->FindTime) is set to:".$this->TimeNow(20));
			if ($this->GetQueueJoin($interna_stevilka) == true) {
				$this->AM_LogWrite_predictive("----- Queue Internal Join ------\r\n I got the status \r\n----- END Queue Internal Join ------\r\n\r\n");
				return true;
			} else {
				$this->AM_LogWrite_predictive("----- Dial status ------\r\n Return false! \r\n----- END Dial status ------\r\n\r\n");
			}
			return false;
		} else {
			return false;
		}
	}
	
	
	public function DialOutside($TelephoneNumber, $Context, $CallerID, $PredictiveExt, $TrunkName, $connect) {
		$actionID = $this->GetActionID();
		$this->DialOutside_actionID = $actionID;
		
		$this->dbAddRingingCall($this->id_project, $actionID, $TelephoneNumber, getmypid(), $this->selectedIndex, $connect);
		
		$this->startCallTime = time();
		
		$arrLoginPairs = array("Action" => "Originate", 
								"Channel" => "SIP/".$TelephoneNumber."@".$TrunkName,
								"Context" => $Context, 
								"Exten" => $PredictiveExt,
								"Priority" => "1",
								"Callerid" => $CallerID, 
								"Timeout" => "30000",
								"Variable" => "rmpredictive=".$actionID,
								"Async" => "1",
								"ActionID" => $actionID);
		
		$strAddPairs = $this->AddPair_AM($arrLoginPairs);
		
		// write Asterisk command pair to LOG file
		$this->AM_LogWrite_predictive("----- DialOutside ------\r\n".$strAddPairs."----- END Dial ------\r\n");
		
		if ($this->SendPacket($strAddPairs) == true) {
			// check if login was success or failure
			$this->FindTime = $this->TimeNow(5); // set the timer for searching for my packet
			$this->AM_LogWrite_predictive("Curent time=".time().". Timer (this->FindTime) is set to:".$this->TimeNow(5));
			$this->AM_LogWrite_predictive("I am sending in VarSet actionID=$actionID to check rmpredictive VarSet.");
			if ($this->GetRMvars($actionID) == true) {
				$this->AM_LogWrite_predictive("I got VarSet, now I am going to Join outside line to the queue.");
				$this->FindTime = $this->TimeNow(35); // set the timer for searching for my packet
				$this->AM_LogWrite_predictive("Curent time=".time().". Timer (this->FindTime) is set to:".$this->TimeNow(35));
				if ($this->GetQueueJoinOutside($connect) == true) {
					$this->AM_LogWrite_predictive("----- Queue External Join ------\r\n I got the status \r\n----- END Queue External Join ------\r\n");
					return true;
				} else {
					$this->AM_LogWrite_predictive("----- Dial external status ------\r\n Return false! \r\n----- END Dial external status ------\r\n");
				}
			}
			return false;
			
			
			
		} else {
			return false;
		}
	}
	
	
	private function GetRMvars($RMvalue) {
		$MyPacket = array();
		$CorrectVarSet = false;
		$TimePass = false;
				
		$MyPacket = $this->GetResponse("Event", array("VarSet"));
		while ($MyPacket AND $CorrectVarSet == false AND $TimePass == false) {
			$this->AM_LogWrite_predictive("I am checking VarSet:\r\n!".$MyPacket['Variable']."-".$MyPacket['Value']."!\r\n----- END GetRMvars -----\r\n");
			if ($MyPacket['Variable'] == "rmpredictive" AND $MyPacket['Value'] == $RMvalue) {
				$this->ExternalChannel = $MyPacket['Channel'];
				$this->ExternalID = $MyPacket['Uniqueid'];
				$this->AM_LogWrite_predictive("I got VarSet:\r\n!".$MyPacket['Channel']."-".$MyPacket['Uniqueid']."!\r\n----- END GetRMvars -----\r\n");
				$CorrectVarSet = true;
			} else {
				// if we did not find the correct packet, we search forward
				$this->AM_LogWrite_predictive("I did not find RMvalue actionID=$RMvalue, go for the next packet GetRMvars().");
				$MyPacket = $this->GetResponse("Event", array("VarSet"));
			}
			
			if ($this->FindTime < $this->TimeNow(0)) {
				$TimePass = true;
				$this->AM_LogWrite("--- TimeCompare GetRMvars()---\r\nTime limit: ".$this->FindTime." - Time now:".$this->TimeNow(0)."\r\n--- END TimeCompare ---\r\n\r\n");
			}
			
		}
		
		if ($CorrectVarSet == true) {
			return true;
		} else {
			return false;
		}	
	}
	
	
	private function GetQueueJoinOutside($connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
		$this->AM_LogWrite_predictive("I am inside GetQueueJoinOutside.");
		$MyPacket = array();
		$CorrectUniqueid = false;
		$TimePass = false;
				
		$MyPacket = $this->GetResponse("Event", array("Join","Hangup","OriginateResponse"));
		while ($MyPacket AND $CorrectUniqueid == false AND $TimePass == false) {
			switch ($MyPacket['Event']) {
				case "OriginateResponse": 
					$this->AM_LogWrite_predictive("--- OriginateResponse ---\r\nChannel: ".$MyPacket['Channel']);
					$this->AM_LogWrite_predictive("MyPacket UniqueID: ".$MyPacket['Uniqueid']." - ExternalID: ".$this->ExternalID."\r\n--- END OriginateResponse ---\r\n");
					if ($MyPacket['Uniqueid'] == $this->ExternalID AND $MyPacket['Response'] == "Success") {
						$this->AM_LogWrite_predictive("--- Response success: ".$MyPacket['Uniqueid']);
						$this->DialStatus = 1;  // external user pick up the phone, I must bridge the line with first in queue
						
						if ($this->BridgeToQueue($connect)) {
							$set_dial_status = 99;
							$status_rec_telnum = 0;
							
							$this->AM_LogWrite_predictive("I am going in Bridge to function SaveDialStatus().");
							$this->SaveDialStatus($set_dial_status, $status_rec_telnum, $this->id_project, $this->tel_name, $this->tren_tabl, 
												  $this->projectParameters['busy_call_delay'], $this->projectParameters['noanswer_call_delay'], 
												  $this->dbGetMustICheckDogovor($this->projectParameters), $this->selectedIndex, $this->startCallTime,  
												  $this->selectedTelephone, $this->selectedNetwork, $this->selectedRegion, $this->isAppointment, 
												  $this->WarpitUser, $connect);
											  
							$sql = "UPDATE _Asterisk_RMconnect SET channel_external='$this->ExternalChannel', id_external='$this->ExternalID', connect=1, id_tel_log='$this->TelLogID', id_tel='$this->selectedIndex' WHERE sip='".$this->sip_internal."'";
							mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
							$this->AM_LogWrite_predictive("If Bridged, activate internal line: ".$sql);
						} else {
							$this->AM_LogWrite_predictive("Bridge error! Connect to internal line was not made. Function will return true anyway to continue dialing new number.\r\n");
													}
						$CorrectUniqueid = true;					  											  
					} else {
						$MyPacket = $this->GetResponse("Event", array("Join","Hangup","OriginateResponse")); // if we did not find the correct packet, we search forward
						$this->AM_LogWrite_predictive("I did not find correct Uniqueid - Join ".$MyPacket['Uniqueid'].", go for the next packet GetQueueJoinOutside().");
					}
					break;
				case "Join": 
					$this->AM_LogWrite_predictive("--- Join outside to queue ---\r\nChannel: ".$MyPacket['Channel']);
					$this->AM_LogWrite_predictive("MyPacket UniqueID: ".$MyPacket['Uniqueid']." - ExternalID: ".$this->ExternalID."\r\n--- END Join outside ---\r\n");
					if ($MyPacket['Uniqueid'] == $this->ExternalID) {
						$this->AM_LogWrite_predictive("--- Checking join status ---\r\nJoined: ".$MyPacket['Uniqueid']."\r\n--- END Join check ---\r\n");
						$this->DialStatus = 1;  // external user pick up the phone, I must bridge the line with first in queue
						
						if ($this->BridgeToQueue($connect)) {
							$set_dial_status = 99;
							$status_rec_telnum = 0;
							
							$this->AM_LogWrite_predictive("I am going in Bridge to function SaveDialStatus().");
							$this->SaveDialStatus($set_dial_status, $status_rec_telnum, $this->id_project, $this->tel_name, $this->tren_tabl, 
												  $this->projectParameters['busy_call_delay'], $this->projectParameters['noanswer_call_delay'], 
												  $this->dbGetMustICheckDogovor($this->projectParameters), $this->selectedIndex, $this->startCallTime,  
												  $this->selectedTelephone, $this->selectedNetwork, $this->selectedRegion, $this->isAppointment, 
												  $this->WarpitUser, $connect);
											  
							$sql = "UPDATE _Asterisk_RMconnect SET channel_external='$this->ExternalChannel', id_external='$this->ExternalID', connect=1, id_tel_log='$this->TelLogID', id_tel='$this->selectedIndex' WHERE sip='".$this->sip_internal."'";
							mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
							$this->AM_LogWrite_predictive("If Bridged, activate internal line: ".$sql);
						} else {
							$this->AM_LogWrite_predictive("Bridge error! Connect to internal line was not made. Function will return true anyway to continue dialing new number.\r\n");
													}
						$CorrectUniqueid = true;					  											  
					} else {
						$MyPacket = $this->GetResponse("Event", array("Join","Hangup","OriginateResponse")); // if we did not find the correct packet, we search forward
						$this->AM_LogWrite_predictive("I did not find correct Uniqueid - Join ".$MyPacket['Uniqueid'].", go for the next packet GetQueueJoinOutside().");
					}
					break;
				case "Hangup": 
					$this->AM_LogWrite_predictive("--- Hangup value ---\r\nHangupID: ".$MyPacket['Uniqueid']."\r\nSavedID: ".$this->ExternalID."\r\n--- END Hangup value ---\r\n\r\n");
					if ($MyPacket['Uniqueid'] == $this->ExternalID) {
						$this->AM_LogWrite_predictive("--- Checking status ---\r\nHangup: ".$MyPacket['Cause-txt']." - [".$MyPacket['Cause']."]\r\n--- END Check ---\r\n\r\n");
						if ($MyPacket['Cause'] == 1) $this->DialStatus = 8;  // wrong, unallocated number
						if ($MyPacket['Cause'] == 16 OR $MyPacket['Cause'] == 0) $this->DialStatus = 9;  // normal clearing
						if ($MyPacket['Cause'] == 17) $this->DialStatus = 2;  // user busy
						if ($MyPacket['Cause'] >= 2 AND $MyPacket['Cause'] <= 15) $this->DialStatus = 5;  // other telephone network problem
						if ($MyPacket['Cause'] >= 18) $this->DialStatus = 5;  // other telephone network problem
						
						switch ($this->DialStatus) {
							case 2:
								$set_dial_status = 2;
								$status_rec_telnum = 2;
								
								break;
							case 5:
								$set_dial_status = 9;
								$status_rec_telnum = 4;
								
								break;
							case 8:
								$set_dial_status = 5;
								$status_rec_telnum = 4;
								
								break;
							case 9: 
								$set_dial_status = 2;
								$status_rec_telnum = 5;
								
								break;
						}
						$this->AM_LogWrite_predictive("I am going in Hangup to function SaveDialStatus().");
						$this->SaveDialStatus($set_dial_status, $status_rec_telnum, $this->id_project, $this->tel_name, $this->tren_tabl, 
											  $this->projectParameters['busy_call_delay'], $this->projectParameters['noanswer_call_delay'], 
											  $this->dbGetMustICheckDogovor($this->projectParameters), $this->selectedIndex, $this->startCallTime,  
											  $this->selectedTelephone, $this->selectedNetwork, $this->selectedRegion, $this->isAppointment, 
											  $this->WarpitUser, $connect);
						$CorrectUniqueid = true;
					} else {
						$MyPacket = $this->GetResponse("Event", array("Join","Hangup","OriginateResponse")); // if we did not find the correct packet, we search forward
						$this->AM_LogWrite_predictive("I did not find correct Uniqueid - Hangup ".$MyPacket['Uniqueid'].", go for the next packet GetQueueJoinOutside().");
					}
					break;
			}
			
			if ($this->FindTime < $this->TimeNow(0)) {
				$TimePass = true;
				$this->AM_LogWrite("--- TimeCompare GetRMvars()---\r\nTime limit: ".$this->FindTime." - Time now:".$this->TimeNow(0)."\r\n--- END TimeCompare ---\r\n\r\n");
			}
			
		}
		
		if ($CorrectUniqueid == true) {
			return true;
		} else {
			return false;
		}	
	}
	

			
	private function BridgeToQueue($connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
		$actionID = $this->GetActionID();
		
		$row = array();
		$cnt_free_agent = 0;
		while (count($row) == 0 AND $cnt_free_agent < 60) {
			$sql = "LOCK TABLES _Asterisk_RMqueues WRITE";
			mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
			$this->AM_LogWrite_predictive("Table lock asterisk RMqueues".$sql);
			
			$sql = "SELECT sip, channel_internal FROM _Asterisk_RMqueues WHERE id_project=".$this->id_project." ORDER by QueueOrder ASC LIMIT 1";
			$result = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
			$this->AM_LogWrite_predictive("Get internal channel to lock to: ".$sql);
			$row = mysql_fetch_array($result);
			//$this->AM_LogWrite_predictive("Results out of asterisk_RMqueues: ".print_r($row));
			
			$this->sip_internal = $row[sip];
			
			if (mysql_num_rows($result) == 0) {
				$sql = "UNLOCK TABLES";
				mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
				$this->AM_LogWrite_predictive("Unlock _Asterisk_RMqueues".$sql);
				
				sleep(2);
				$cnt_free_agent += 2;
			}
		}

		if ($cnt_free_agent < 60) {
			$sql = "DELETE FROM _Asterisk_RMqueues WHERE id_project=".$this->id_project." AND sip='".$row[sip]."'";
			mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
			$this->AM_LogWrite_predictive("Remove internal channel from queue: ".$sql);
					
			$sql = "UNLOCK TABLES";
			mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
			$this->AM_LogWrite_predictive("Unlock _Asterisk RMqueues: ".$sql);
	
			$arrLoginPairs = array("Action" => "Bridge", 
									"Channel1" => $row['channel_internal'],
									"Channel2" => $this->ExternalChannel, 
									"ActionID" => $actionID);
			$strAddPairs = $this->AddPair_AM($arrLoginPairs);
			$this->AM_LogWrite_predictive("Bridge external and internal :\r\n".$strAddPairs."\r\n");
			
			if ($this->SendPacket($strAddPairs) == true) {
				
				$this->FindTime = $this->TimeNow(5); // set the timer for searching for my packet
				$this->AM_LogWrite_predictive("GetBridgeStatus() curent time=".time().". Timer (this->FindTime) is set to:".$this->TimeNow(5));
				if ($this->GetBridgeStatus($actionID) == true) {
					$this->AM_LogWrite_predictive("----- Bridge status ------\r\n I got bridge status \r\n----- END Bridge status ------\r\n\r\n");
					$this->AM_LogWrite_predictive("Timer to join the queue (how long respondent wait in queue before we get free interviewer): ".$cnt_free_agent);
					return true;
				} else {
					$this->AM_LogWrite_predictive("----- Bridge status ------\r\n Response error! \r\n----- END Bridge status ------\r\n\r\n");
				}
			}
		} else {
			$this->BridgeStatus = 21;
		}
		$this->AM_LogWrite_predictive("Timer to join the queue (how long respondent wait in queue before we get free interviewer): ".$cnt_free_agent);
		return false;
	}

	
	private function GetBridgeStatus($actionID) {
		$MyPacket = array();
				
		if ($MyPacket = $this->GetResponse("ActionID", array($actionID))) {
			if ($MyPacket['Response'] == "Success") {
				$this->BridgeStatus = 1;
				return true;
			} else {
				$this->BridgeStatus = 11;
				return false;
			}
		} else {
			$this->BridgeStatus = 12;
			return false;
		}
	}
	
	
	private function GetQueueJoin($interna_stevilka) {
		$CorrectChannel = false;
		$MyPacket = array();
				
		$MyPacket = $this->GetResponse("Event", array("VarSet"));
		while ($MyPacket AND $CorrectChannel == false AND $TimePass == false) {
			$array_MyPacket = explode("-", $MyPacket['Channel'], 2);
			$this->AM_LogWrite_predictive("I got GetQueueJoin Status:\r\n".$array_MyPacket[0]."\r\n----- END GetQueueJoin Status -----\r\n\r\n");
			if ($array_MyPacket[0] == "SIP/".$interna_stevilka AND $MyPacket['Variable'] == "RMpredictiveinside") {
				$this->InternalChannel = $MyPacket['Channel'];
				$this->InternalID = $MyPacket['Uniqueid'];
				
				$CorrectChannel = true;
			} else {
				// if we did not find the correct packet, we search forward
				$this->AM_LogWrite_predictive("I did not find GetQueueJoin packet. Searching forward...");
				$MyPacket = $this->GetResponse("Event", array("VarSet"));
			}
			
			if ($this->FindTime < $this->TimeNow(0)) {
				$TimePass = true;
				$this->AM_LogWrite("--- TimeCompare GetRMvars()---\r\nTime limit: ".$this->FindTime." - Time now:".$this->TimeNow(0)."\r\n--- END TimeCompare ---\r\n\r\n");
			}
		}
		
		if ($CorrectChannel == true) {
			return true;
		} else {
			return false;
		}	
		
	}
	

	public function ClearZombies(&$nextTimeToClearZombies, $timeout) {
 		$this->AM_LogWrite_predictive("ClearZombies. NextTime: ".$nextTimeToClearZombies);
 		
 		if (time() > $nextTimeToClearZombies) {
		 	// When children die, this gets rid of the zombies
		 	$i = 1;
			while(pcntl_wait($status, WNOHANG OR WUNTRACED) > 0) {
			  	usleep(5000);
			  	$this->AM_LogWrite_predictive("Process".$i);
			  	++$i;
			}	
			$nextTimeToClearZombies += $timeout;
 			$this->AM_LogWrite_predictive("End of clearing zombies.");
 		}		
 	}
 	
 	
 	public function WaitForChildren() {
		$i = 1;
		while(pcntl_wait($status) > 0) {
			usleep(5000);
			$this->AM_LogWrite_predictive("Child".$i);
			++$i;
		}	
 	}
	
 	
 	public function EventsOn(){
		$arrLoginPairs = array("Action" => "EVENTS", 
								"EVENTMASK" => "ON",
							   );
		$strAddPairs = $this->AddPair_AM($arrLoginPairs);
		$this->AM_LogWrite_predictive("----- Events On ------");
		
		if ($this->SendPacket($strAddPairs) == true) {
			return true;
		} else {
			return false;
		}
	}
	
        
 	public function EventsOff(){
		$arrLoginPairs = array("Action" => "EVENTS", 
								"EVENTMASK" => "OFF",
							   );
		$strAddPairs = $this->AddPair_AM($arrLoginPairs);
		$this->AM_LogWrite_predictive("----- Events Off ------");
		
		if ($this->SendPacket($strAddPairs) == true) {
			return true;
		} else {
			return false;
		}
	}
	
        
	private function dbAddRingingCall($idProject, $actionId, $calledNumber, $pid, $selectedNumId, $connect) {	
		$SQLconnect = $connect;;
		global $CATI_base_structure;
		
		$currentTime= time();
		$sql = "INSERT INTO _Asterisk_RMringing VALUES('".$actionId."','".$calledNumber."',".$idProject.",".$currentTime.",".$pid.",".$selectedNumId.")";
		$this->AM_LogWrite_predictive("Add ringing call: ".$sql);
		
		mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
	}
	
	
	public function dbDeleteRingingCall($idProject, $actionId, $connect) {	
		$SQLconnect = $connect;;
		global $CATI_base_structure;
		
		$sql = "DELETE FROM _Asterisk_RMringing WHERE callerId='".$actionId."' AND projectId=".$idProject;
		mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$this->AM_LogWrite_predictive("Delete one ringing call: ".$sql);
	}
	
	
	// Returns string. Maximum length of the stringth is 18.
	private function GetRandomNumber()
	{
		$utime = time(); 
		$urand = mt_rand(1,$utime);
		$ucombine = substr($urand.$utime, 0, 18); 
		
		return 	$ucombine;
	}
	
	
	// Returnes true on success, false otherwise.
	private function KillProcess($pid) {
		return posix_kill($pid, SIGKILL);
	}
	
	
	public function AddToQueue($SIP, $id_project, $id_user, $db)	{
		$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		
		$sql = "SELECT (max(QueueOrder)+1) AS id_queue FROM _Asterisk_RMqueues WHERE `id_project`=".$id_project;
		$result = $db->SQLexecute($sql);
		$this->AM_LogWrite_predictive("Get queue new order ID: ".$sql);
		$row = mysql_fetch_array($result);
		$LastQueuePosition = $row[id_queue];
		if (!$LastQueuePosition) $LastQueuePosition = 0;
		 
		$sql = "REPLACE _Asterisk_RMconnect SET `sip`='$SIP', `id_user`=$id_user,id_project=$id_project, channel_internal='".$this->InternalChannel."', id_internal='".$this->InternalID."', connect=null, id_tel_log=null, id_tel=null";
		$result = $db->SQLexecute($sql);
		$this->AM_LogWrite_predictive("Prepare connect table for starting the questionnaire: ".$sql);
		
		$sql = "REPLACE _Asterisk_RMqueues SET QueueOrder=$LastQueuePosition, `id_project`=$id_project, `sip`='$SIP', `id_user`=$id_user, channel_internal='".$this->InternalChannel."', id_internal='".$this->InternalID."'";
		$result = $db->SQLexecute($sql);
		$this->AM_LogWrite_predictive("User adding to the queue: ".$sql);
	}
	
	
	public function RemoveFromQueue($SIP, $id_project)	{
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		
		$sql = "DELETE FROM _Asterisk_RMqueues WHERE `id_project`=$id_project AND `sip`='$SIP'";
		$this->db->SQLexecute($sql);
		$this->AM_LogWrite_predictive("Remove user from queue: ".$sql);
		
		$sql = "UPDATE _Asterisk_RMconnect SET connect=0 WHERE `sip`='$SIP'";
		$this->db->SQLexecute($sql);
		$this->AM_LogWrite_predictive("Set connect flag to 0 (I already start the questionniare): ".$sql);
	}
	
	
	/**
	 * Prepare the log location
	 *
	 * @return string
	 */
	private function LogLocation_predictive() {
		return "/tmp/RM_AsteriskManagerPredictive___".getmypid().".log";
	}
	

	/**
	 * Write debug info to a log file
	 *
	 * @param string $strLog
	 */
	public function AM_LogWrite_predictive($strLog) {
		$strLog = $this->GetTimeLog()." - ".$strLog."\r\n";
		
		if (file_put_contents($this->LogLocation_predictive(), $strLog, FILE_APPEND)) {
			return true;
		} else {
			return false;
		}
	}
	

	private function dbGetMustICheckDogovor($parameters) {
		if ($parameters['questionaire_options'] == 1)
			return 0;
		else 
			return 1;
	}

	
	public function getNewNumber($connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;

		$first_TelNumber = array_shift($this->TelNumberContainer);
		$this->AM_LogWrite_predictive("FirstValue in getNewNumber(): ".$first_TelNumber);

		$this->selectedTelephone = $first_TelNumber['telephone'];
		$this->selectedNetwork = $first_TelNumber['oms'];
		$this->selectedRegion = $first_TelNumber['tpreg'];
		$this->isAppointment = $first_TelNumber['IsApp'];
		$this->selectedIndex = $first_TelNumber['id_tel'];
		
		unset($this->TelNumberContainer[$key_TelNumber]);
		
		return $first_TelNumber['telephone'];
	}
	
	
	
/**
	 * Finds the next number to call from the database.
	 * 
	 * @param resource connection
	 * @param string $id_project id of selected project
	 * @param parameters - parameters for the project
	 * @param string $tren_table name of the project table.
	 * @param int $id_user - logged in user.
	 * @param int $selectedIndex, outgoing parameter where we save id of selected number (index table)
	 * @param gsm_array look in init/connect_config_predictive.php
	 * @param call_regional look in init/connect_config_predictive.php
	 * @param int $selectedTelephone - outgoing param, selected telephone number without network, gsm, etc
	 * @param int $selectedNetwork - outgoing param selected network number
	 * @param int $selectedRegion . outgoing paramter, selected region number
	 * @param bool $isDogovor is the number we found dogovor?
	 */
	public function dbFindNumber($id_project, $parameters, $tren_tabl, $id_user, $gsm_array, $call_regional, $tel_name, $izhodna_koda, $connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
	/*	$NumbersFound = false;
		$mustICheckDogovor = $this->dbGetMustICheckDogovor($parameters); // int $mustICheckDogovor - do we also have to check dogovor or are they using other system?
		$telselect = $parameters[telselect];						// 1 = choose numbers one after another, 2 = random	
		$num_max_call = $parameters[num_max_call];					// int $num_max_call - max allowed calls for specific number
		$should_use_quota = $parameters[usequota];					// int $should_use_quota - do we use quotas (example 20x02 network, 30x03 network , ...)
		$should_use_telphone = $parameters[usetelphone];			// int $should_use_telphone do we use telephone?
		$qt_useregtel = $parameters[qt_useregtel];				// int $qt_useregtel Do we calculate quotas or do we use random region?
		$is_reg_strictlock = $parameters[reg_strictlock];			// int $is_reg_strictlock - when we use quotas, are we strict ?
		$tel_reserve = $parameters[tel_reserve];			// Number of reserved numbers.

		// izkloljeno za sedaj, dokler testiramo...
		if ($mustICheckDogovor == "test") {
			// grem izbrati telefonsko stevilko			
			// preverim ali kaksen dogovor ze obstaja
			$this->AM_LogWrite_predictive("FindNumber(). Checking appointment.");
			
			$tren_cas = time();
			// preverim ali za anketarja/na splosno obstaja kaksen dogovor in ce obstaja izberem najstarejsega
			// ce imam manualno nastavljanje tel stevilk potem omejim vse skupaj na izbrano regijo
			$sql_show_dogovor = "SELECT id_tel, app_koment, app_time, id, app_middle FROM telephone_".$tren_tabl."_index WHERE status='91' AND app_time<'$tren_cas' AND tdisable=0 ORDER by app_time LIMIT 1";
	 		$this->AM_LogWrite_predictive("Select appointment if exist: ".$sql);
			$result_show_dogovor = mysql_db_query($CATI_base_structure, $sql_show_dogovor, $SQLconnect);
			
			if ( mysql_num_rows($result_show_dogovor) == 1 ) {
				$row_show_dogovor = mysql_fetch_row($result_show_dogovor);
				$telnum_index = $row_show_dogovor[0];
				$app_koment =  $row_show_dogovor[1];
				// ker zraven komentarja shranjujem se novo tel. stevilko, ce jo rabim, le to locim od samega komentarja
				$app_koment_array = explode("|",$app_koment,2);
				$app_koment =  $app_koment_array[0];
				if ($app_koment_array[1]) 
					$dogovor_tel_array = explode(";",$app_koment_array[1]);
				$dogovor_telcheck_chk = $dogovor_tel_array[0];
				$dogovor_oms = $dogovor_tel_array[1];
				$dogovor_telnum = $dogovor_tel_array[2];
				// konec locevanja komentarja
				$last_app_time =  $row_show_dogovor[2];
				$id_idx_dogovor =  $row_show_dogovor[3];
				$last_app_time_array = getdate($last_app_time);
				$tren_year = $last_app_time_array[year];
				$tren_mon = $last_app_time_array[mon];
				$tren_mday = $last_app_time_array[mday];
				$tren_hours = $last_app_time_array[hours];
				$tren_minutes = $last_app_time_array[minutes];
			
				// rezerviram dogovor
				$sql_reserve_dogovor = "UPDATE telephone_".$tren_tabl."_index SET status='90' WHERE id='$id_idx_dogovor'";
	 			$this->AM_LogWrite_predictive("Reserve appointment: ".$sql);
				$result_reserve_dogovor = mysql_db_query($CATI_base_structure, $sql_reserve_dogovor, $SQLconnect);
			
				$dogovor_exist = "YES";
				$index_sucess = "YES";
				$isDogovor = true;
			}
		}

		$realni_time = time();
		
		if ( $dogovor_exist != "YES" ) {
			$this->AM_LogWrite_predictive("FindNumber(). Dogovor does not exist.");
			$isDogovor = false;
			
// ce imam vklopljen strict locking moram zracunat, katere regije se nimam zapolnjene in izbirat tel stevilke samo od tam
			if ( $should_use_quota == 1 AND $should_use_telphone == 1 AND $qt_useregtel == 1 AND $is_reg_strictlock == 1 ) {

				// pridobim id_layerja ki ima tpreg nastavljen
				$select_id_layer_tpreg = "SELECT id_layer FROM layer_def WHERE id_project=$id_project AND layer_def='tpreg'";
				$this->AM_LogWrite_predictive("Get ID layer where region quota is set: ".$sql);
				$result_id_layer_tpreg = mysql_db_query($CATI_base_structure, $select_id_layer_tpreg, $SQLconnect);
				
				$row_id_layer_tpreg = mysql_fetch_row($result_id_layer_tpreg);
				$id_layer = $row_id_layer_tpreg[0];
				mysql_free_result($result_id_layer_tpreg);

				if ($id_layer) {
					// precitam nastavljene kvote za tpreg
			  		$select_quota_tpreg = "SELECT id_question_0 AS value, percent AS number FROM quota_percent WHERE id_project=$id_project AND id_layer=$id_layer ORDER BY value";
			  		$result_quota_tpreg = mysql_db_query($CATI_base_structure, $select_quota_tpreg, $SQLconnect);
			  		while ( $row_quota_tpreg = mysql_fetch_array($result_quota_tpreg)) {
			  			$tpreg_quota_array[$row_quota_tpreg[value]] = $row_quota_tpreg[number];
			  		}
			  		mysql_free_result($result_quota_tpreg);
					// precitam se ze zanketirane vrednosti za QT_tpreg
			  		$select_ank_tpreg = "SELECT QT_tpreg AS value, count(*) AS number FROM ".$tren_tabl."_quota_calc WHERE QT_tpreg>0 GROUP BY QT_tpreg";
			  		$result_ank_tpreg = mysql_db_query($CATI_base_structure, $select_ank_tpreg, $SQLconnect);
			  		while ( $row_ank_tpreg = mysql_fetch_array($result_ank_tpreg)) {
			  			$tpreg_ank_array[$row_ank_tpreg[value]] = $row_ank_tpreg[number];
			  		}
			  		mysql_free_result($result_ank_tpreg);
			  		
					// zgradim string za query, ki onemogoci dolocene regije (PAZI!!! tukaj je sedanj narejeno na default-nerekodirano tpreg, ce bo kdaj rekodirana moras najprej pogleda na katere vse regije kaze rekodirana variabla in tiste vrednosti zajet v string)
			  		$strictlock_region_def = "";
			  		for ( reset($tpreg_quota_array); $index_qt_array = key($tpreg_quota_array); next($tpreg_quota_array) ) {
			  			if ( $tpreg_quota_array[$index_qt_array] <= $tpreg_ank_array[$index_qt_array] ) {
			  				$strictlock_region_def = $strictlock_region_def." AND regija <> '$index_qt_array'";
			  			}
			  		}
				} else {
					$this->AM_LogWrite_predictive("Error! If you are using quota system with telephone number system, please define tpreg variable as separate layer.");
				}
			}
			
			// trenutni cas nic vec ne zmanjsam za 30 min in klicem tudi zasedene stevilke ampak
			// za zamik casa poskrbim ze pri zapisu statusa zasedeno v index tabelo, tukaj se samo
			// preverim ali je ze prisel cas za klic zasedene stevilke
			$trenutni_cas = $realni_time;
			// izbiranje telefonskih stevilk
			//		echo "tel_reserve : $tel_reserve<br>";
			list($usec, $sec) = explode(' ', microtime()); 
			$randomSeed = (float) $sec + ((float) $usec * 100000); 
			mt_srand($randomSeed);
			$rand_start_telbase = mt_rand(1, $tel_reserve) - 1;

			$select_telnum_index = "SELECT id_tel FROM telephone_".$tren_tabl."_index 
									WHERE id > $rand_start_telbase AND regija>0 AND call_time < $trenutni_cas AND call_num<$num_max_call $strictlock_region_def AND tdisable=0 ORDER BY id LIMIT 100";
		 
			$select_lock_index = "LOCK TABLES telephone_".$tren_tabl."_index WRITE";
			mysql_db_query($CATI_base_structure, $select_lock_index, $SQLconnect);

			$this->AM_LogWrite_predictive("FindNumber SQL: $select_telnum_index");

			$result_telnum_index = mysql_db_query($CATI_base_structure, $select_telnum_index, $SQLconnect);
			if (mysql_num_rows($result_telnum_index)) $NumbersFound = true;
			
			$this->AM_LogWrite_predictive("Find telephone numbers: ".mysql_num_rows($result_telnum_index));
			
			
			if ( $NumbersFound == false ) {
				$rand_start_telbase++;
				$select_telnum_index = "SELECT id_tel FROM telephone_".$tren_tabl."_index 
										WHERE id < $rand_start_telbase AND regija>0 AND call_time < $trenutni_cas AND call_num<$num_max_call $strictlock_region_def AND tdisable=0 ORDER BY id DESC LIMIT 100";
				$this->AM_LogWrite_predictive("FindNumber SQL (DESC): $select_telnum_index");
				$result_telnum_index = mysql_db_query($CATI_base_structure, $select_telnum_index, $SQLconnect);
				if (mysql_num_rows($result_telnum_index)) $NumbersFound = true;
				
				$this->AM_LogWrite_predictive("Find telephone numbers: ".mysql_num_rows($result_telnum_index));
			}
		}
		*/
		include_once (PATH_TO_ROOT.'webcati/_class/class.Dialer.php');
		//include_once (PATH_TO_ROOT.'_config/dbConfig.php');			
		$d = new Dialer($this->db);
		$id_tel_array = $d->getTelId( $id_project ,-700,0 , $this->projectParameters['predictive_numbers_tofind']  );
		// ce sem uspel najti primerno stevilko
		$NumbersFound = is_array($id_tel_array);
		if ( $NumbersFound == true ) {
			if ( $dogovor_exist != "YES" ) {
				// nardim array vseh izbranih tel stevilk
				
//				while ($row_sqlidtel = mysql_fetch_row($result_telnum_index)) {
//					$id_tel_array[] = $row_sqlidtel[0];  
//				}
				
				// rezerviram tel stevilke
				$query_update_telnum_sts = "UPDATE telephone_".$tren_tabl."_index SET call_time=regija, regija='-1', status='-1', id_ank='$id_user' WHERE id_tel IN (".implode(",", $id_tel_array).")";
				$this->AM_LogWrite_predictive("Reserved tel numbers: $query_update_telnum_sts");
				
				mysql_db_query($CATI_base_structure, $query_update_telnum_sts, $SQLconnect);
				$select_unlock_index = "UNLOCK TABLES";
				mysql_db_query($CATI_base_structure, $select_unlock_index, $SQLconnect);
			}
			// potegnem iz tel tabele dejanske cifre
			$select_telnum = "SELECT oms, telephone, id, region, zip, name, neusp_klici FROM tel___$tel_name WHERE id IN (".implode(",", $id_tel_array).")";
			$this->AM_LogWrite_predictive("Get number from the telephone table: $select_telnum");

			$result_select_telnum = mysql_db_query($CATI_base_structure, $select_telnum, $SQLconnect);
			$n = 0;
			while ($row_select_telnum = mysql_fetch_array($result_select_telnum)) {
				$add_oms_number = $call_regional.$row_select_telnum['oms'];
				$full_tel_number = $izhodna_koda.$add_oms_number.$row_select_telnum['telephone'];

				$this->TelNumberContainer[$n]['telephone'] = $full_tel_number;  
				$this->TelNumberContainer[$n]['id_tel'] = $row_select_telnum['id'];  
				$this->TelNumberContainer[$n]['oms'] = $row_select_telnum['oms'];  
				$this->TelNumberContainer[$n]['tpreg'] = $row_select_telnum['region']; 
				$this->TelNumberContainer[$n]['IsApp'] = 0;

				$n++; 
			}
			$this->AM_LogWrite_predictive("I fill telephone numbers container with new numbers...");
			
			return true;
		} else {
			// TODO - no more numbers, connect 9
			$select_unlock_index = "UNLOCK TABLES";
			mysql_db_query($CATI_base_structure, $select_unlock_index, $SQLconnect);
			throw new Exception("Could not find number to call. Maybe we ran out of them?");
			return false;
		}
	}

	
	/**
	 * Writes calls statuses in database.
	 * 
	 * Status 	99 1 - person is in queue
	 * 			99 0 - person is connected to the user
	 * 			2 5  - no answer
	 * 			2 2  - person is busy
	 * 			3 9  - hangup from queue
	 * 			5 4  - error
	 * @param int $set_dial_status
	 * @param int $status_rec_telnum
	 * @param int $idProject
	 * @param string $tel_name main table with phone numbers
	 * @param string $tren_tabl name of the project table.
	 * @param int $busy_call_delay
	 * @param int $noanswer_call_delay
	 * @param int $mustICheckDogovor - do we also have to check dogovor or are they using other system?
	 * @param int $id_selected_telnum
	 * @param int $startCallTime - time we started this call
	 * @param int $selectedTelephone - selected telephone number without network, gsm, etc
	 * @param int $selectedNetwork -  selected network number
	 * @param int $selectedRegion
	 * @param bool $isDogovor is the number we found dogovor?
	 * @param int $logTableId - ID of log table we inserted our number to.
	 */
	private function SaveDialStatus($set_dial_status, $status_rec_telnum, $idProject, $tel_name, $tren_tabl, 
									$busy_call_delay, $noanswer_call_delay, $mustICheckDogovor, $id_selected_telnum, $startCallTime, 
									$selectedTelephone, $selectedNetwork, $selectedRegion, $isDogovor, $idUser, $connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
			
		$this->AM_LogWrite_predictive("Save dial status parameters:
										status=$set_dial_status, 
										rec_status=$status_rec_telnum, 
										project ID=$idProject, 
										telephone table name=$tel_name, 
										project name=$tren_tabl, 
										delay for busy call=$busy_call_delay, 
										delay for no answer call=$noanswer_call_delay, 
										must I check appointment=$mustICheckDogovor, 
										telephone number ID=$id_selected_telnum, 
										time when we activate outside call=$startCallTime, 
										telephone number to call=$selectedTelephone, 
										network number to call=$selectedNetwork, 
										region from telephone table=$selectedRegion, 
										is appointment set?=$isDogovor");
		
		if ($mustICheckDogovor == 1) {		
			$app_exist = $isDogovor;
		}

		
		$trenuten_cas= $startCallTime;
  		$trenuten_cas_array = getdate($trenuten_cas);
	  			
		// Successful call - user is in the queue.
		if ($set_dial_status == 99) {	
			// Update main table.
	  		$SQL_append_telbase = "UPDATE $tel_name SET usp_klici=usp_klici+1, status=$set_dial_status, "
		  		."proj_status=$set_dial_status, proj_rec_status='$status_rec_telnum', usp_day={$trenuten_cas_array['mday']}, "
		  		."usp_month={$trenuten_cas_array['mon']}, usp_year={$trenuten_cas_array['year']}, usp_hour={$trenuten_cas_array['hours']},"
		  		." usp_min={$trenuten_cas_array['minutes']}, usp_utime=$trenuten_cas WHERE id=$id_selected_telnum"; 
		  	$this->AM_LogWrite_predictive("Write TELEPHONE table (dial_status=99): ".$SQL_append_telbase);
		  	mysql_db_query($CATI_base_structure, $SQL_append_telbase, $SQLconnect);
	  		
  			$SQL_update_index = "UPDATE ".$tren_tabl."___telIndex SET id_ank='$idUser',status='$set_dial_status', 
  								 rec_status='$status_rec_telnum', call_num=call_num+1 WHERE id_tel=$id_selected_telnum";
      		$this->AM_LogWrite_predictive("Write INDEX table (dial_status=99): ".$SQL_update_index);
	  		mysql_db_query($CATI_base_structure, $SQL_update_index, $SQLconnect);
	  		
  		
  			$SQL_insert_log = "INSERT into ".$tren_tabl."___telLog ";
	  		$SQL_insert_log = $SQL_insert_log."SET status='$set_dial_status', id_user='$idUser', status_rec='$status_rec_telnum',
	  						  call_time='$trenuten_cas', id_tel='".$id_selected_telnum."', oms='$selectedNetwork', 
	  						  telephone='$selectedTelephone'";
  			
      		$this->AM_LogWrite_predictive("Write LOG table: ".$SQL_insert_log);
      		mysql_db_query($CATI_base_structure, $SQL_insert_log, $SQLconnect);
	  			
	  		$logTableId = mysql_insert_id();
			$this->TelLogID = $logTableId; 
		} else if ($set_dial_status == 2)	{
			// Update main table.
			if ($app_exist)
				$SQL_append_telbase = "UPDATE $tel_name SET neusp_klici=neusp_klici+1, status='91', "
			  		."proj_status=$set_dial_status, proj_rec_status='$status_rec_telnum', neusp_day={$trenuten_cas_array['mday']}, "
			  		."neusp_month={$trenuten_cas_array['mon']}, neusp_year={$trenuten_cas_array['year']}, neusp_hour={$trenuten_cas_array['hours']},"
			  		." neusp_min={$trenuten_cas_array['minutes']}, neusp_utime=$trenuten_cas WHERE id=$id_selected_telnum";	
			else
		  		$SQL_append_telbase = "UPDATE $tel_name SET neusp_klici=neusp_klici+1, status=$set_dial_status, "
			  		."proj_status=$set_dial_status, proj_rec_status='$status_rec_telnum', neusp_day={$trenuten_cas_array['mday']}, "
			  		."neusp_month={$trenuten_cas_array['mon']}, neusp_year={$trenuten_cas_array['year']}, neusp_hour={$trenuten_cas_array['hours']},"
			  		." neusp_min={$trenuten_cas_array['minutes']} neusp_utime=$trenuten_cas WHERE id=$id_selected_telnum"; 
		  	
      		$this->AM_LogWrite_predictive("Write TELEPHONE table (dial_status=2): ".$SQL_append_telbase);
			 mysql_db_query($CATI_base_structure, $SQL_append_telbase, $SQLconnect);
		  	
	  		// Write to INDEX table.
	  //		if (!$app_exist)
	  //			$this->dbFreeNumber($id_selected_telnum, $tren_tabl, $connect);
			// ce je dogovor
			if($app_exist) {
				if ($status_rec_telnum == 2)
					$newCallTime = $trenuten_cas + ($busy_call_delay*60);
				else if ($status_rec_telnum == 5)
					$newCallTime = $trenuten_cas + ($noanswer_call_delay*60);
					
				$query_update_telnum_sts = "UPDATE ".$tren_tabl."___telIndex SET status='91', rec_status='$status_rec_telnum', "
					."id_ank='$idUser',last_call=$trenuten_cas, app_time=$newCallTime WHERE id_tel=$id_selected_telnum";
					
			} else {
				if ($status_rec_telnum == 2)
					$newCallTime = $trenuten_cas + ($busy_call_delay*60);
				else if ($status_rec_telnum == 5)
					$newCallTime = $trenuten_cas + ($noanswer_call_delay*60);
					
				$query_update_telnum_sts = "UPDATE ".$tren_tabl."___telIndex SET  status='$set_dial_status', "
					."rec_status='$status_rec_telnum', last_call='$trenuten_cas', "
					."call_time=$newCallTime, call_num=call_num+1 WHERE id_tel=$id_selected_telnum";
				
			}
      		$this->AM_LogWrite_predictive("Write INDEX table (dial_status=2)".$query_update_telnum_sts);
			mysql_db_query($CATI_base_structure, $query_update_telnum_sts, $SQLconnect);
			
	  			
	  		$SQL_insert_log = "INSERT into telephone_".$tren_tabl."_log SET status='$set_dial_status', id_ank='$idUser', "
      			."status_rec='$status_rec_telnum',call_time='".$trenuten_cas."',end_time='".time()."', "
      			."id_tel='$id_selected_telnum', regija='$selectedRegion', omrezna='$selectedNetwork', "
      			."telephone='$selectedTelephone'";
      			
      		$this->AM_LogWrite_predictive("Write LOG table (dial_status=2): ".$SQL_insert_log);
      		mysql_db_query($CATI_base_structure, $SQL_insert_log, $SQLconnect);
      			
	  		$logTableId = mysql_insert_id();
			$this->TelLogID = $logTableId; 
      		
		} else if ($set_dial_status == 3) {
			// Update main table.
	  		$SQL_append_telbase = "UPDATE $tel_name SET neusp_klici=neusp_klici+1, status=$set_dial_status, "
		  		."proj_status=$set_dial_status, proj_rec_status='$status_rec_telnum', neusp_day={$trenuten_cas_array['mday']}, "
			  		."neusp_month={$trenuten_cas_array['mon']}, neusp_year={$trenuten_cas_array['year']}, neusp_hour={$trenuten_cas_array['hours']},"
			  		." neusp_min={$trenuten_cas_array['minutes']}, neusp_utime=$trenuten_cas WHERE id=$id_selected_telnum"; 
		  	
      		$this->AM_LogWrite_predictive("Write TELEPHONE table (dial_status=3): ".$SQL_append_telbase);
		  	mysql_db_query($CATI_base_structure, $SQL_append_telbase, $SQLconnect);
		  	
		  	
			// Index
		//	$this->dbFreeNumber($id_selected_telnum, $tren_tabl, $connect, true);
			
			$query_update_telnum_sts = "UPDATE telephone_".$tren_tabl."_index SET  "
					."status='$set_dial_status', rec_status='$status_rec_telnum', last_call='$trenuten_cas', call_num=call_num+1 "
					." WHERE id_tel=$id_selected_telnum";
					
      		$this->AM_LogWrite_predictive("Write INDEX table (dial_status=3): ".$query_update_telnum_sts);
			mysql_db_query($CATI_base_structure, $query_update_telnum_sts, $SQLconnect);		
				
			
	  		$SQL_update_log = "INSERT INTO telephone_".$tren_tabl."_log SET status='$set_dial_status',  id_ank='$idUser',"
      			."status_rec='$status_rec_telnum',call_time='".$trenuten_cas."',end_time='".time()."', "
      			."id_tel='$id_selected_telnum', regija='$selectedRegion', omrezna='$selectedNetwork', "
      			."telephone='$selectedTelephone'";
      			
      		$this->AM_LogWrite_predictive("Write LOG table (dial_status=3): ".$SQL_update_log);
      		mysql_db_query($CATI_base_structure, $SQL_update_log, $SQLconnect);		
      				
	  		$logTableId = mysql_insert_id();
			$this->TelLogID = $logTableId; 
		} else if ($set_dial_status > 3) {
			// Update main table.
	  		$SQL_append_telbase = "UPDATE $tel_name SET neusp_klici=neusp_klici+1, status=$set_dial_status, "
		  		."proj_status=$set_dial_status, proj_rec_status='$status_rec_telnum', neusp_day={$trenuten_cas_array['mday']}, "
			  		."neusp_month={$trenuten_cas_array['mon']}, neusp_year={$trenuten_cas_array['year']}, neusp_hour={$trenuten_cas_array['hours']},"
			  		." neusp_min={$trenuten_cas_array['minutes']}, neusp_utime=$trenuten_cas WHERE id=$id_selected_telnum"; 
		  	
      		$this->AM_LogWrite_predictive("Write TELEPHONE table (dial_status>3): ".$SQL_append_telbase);
		  	mysql_db_query($CATI_base_structure, $SQL_append_telbase, $SQLconnect);
		  	
		  	
			// Index table
		//	$this->dbFreeNumber($id_selected_telnum, $tren_tabl, $connect, true);
			
			$query_update_telnum_sts = "UPDATE ".$tren_tabl."___telIndex SET status='$set_dial_status',"
				." rec_status='$status_rec_telnum', last_call='$trenuten_cas', call_num=call_num+1 WHERE id_tel=$id_selected_telnum";
			
      		$this->AM_LogWrite_predictive("Write INDEX table (dial_status>3): ".$query_update_telnum_sts);
			mysql_db_query($CATI_base_structure, $query_update_telnum_sts, $SQLconnect);

			
			$SQL_insert_log = "INSERT into ".$tren_tabl."_telLog ";
	  		$SQL_insert_log .= "SET id_user=$idUser, status='$set_dial_status', "
      			."status_rec='$status_rec_telnum',call_time='".$trenuten_cas."',end_time='".time()."'"
      			.", id_tel='$id_selected_telnum',  oms='$selectedNetwork'"
      			.", telephone='$selectedTelephone'";
      			
      		$this->AM_LogWrite_predictive("Write LOG table (dial_status>3): ".$SQL_insert_log);
      		mysql_db_query($CATI_base_structure, $SQL_insert_log, $SQLconnect);
      				
	  		$logTableId = mysql_insert_id();
			$this->TelLogID = $logTableId; 
		}
	}
	
	
	// Looks for project telephone name we are using.
	public function dbGetTelephoneName($parameters, $connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;

		$telId = $parameters['id_telname'];
		$sql = "SELECT name FROM _TelephoneTables where id=".$telId;
	 	$this->AM_LogWrite_predictive("Get name of telephone table: ".$sql);
	 	
		$result = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$row = mysql_fetch_array($result);
		
		$this->tel_name = $row['name'];
	}
	
	
	// When number we dailed is busy or no answers, we have to make that number free in 
	// the database - make in "unreserved"
	// @param $region : true if we have to change the region also.
	private function dbFreeNumber($telNumId, $tren_tabl, $connect, $region = false) {
		$SQLconnect = $connect;;
		global $CATI_base_structure;
		
		if (!$region) 
			$sql = "UPDATE ".$tren_tabl."___telIndex SET  regija=call_time,call_time=0 WHERE id_tel=$telNumId";
		else 
			$sql = "UPDATE ".$tren_tabl."___telIndex SET  regija=(call_time+10000)*-1,call_time=0 WHERE id_tel=$telNumId";
			
		mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$this->AM_LogWrite_predictive("Update INDEX table: ".$sql);
	}

	
	public function dbDeleteAllRingingCalls($idProject, $connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
		$sql = "DELETE FROM _Asterisk_RMringing WHERE projectId=".$idProject;
		mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$sql = "DELETE FROM _Asterisk_RMqueues WHERE projectId=".$idProject;
		//ne smem brisat ker ce so prijavljeni so prijavljeni :)
		//mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		
		$this->AM_LogWrite_predictive("Delete all ringing calls: ".$sql);
	}
	
	
	//  Looks for project name.
	public function dbGetProjectName($projectId,$connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
		$sql = "SELECT proj_name FROM _Projects WHERE id=".$projectId;
		$this->AM_LogWrite_predictive("Load projet properties (dbGetProjectName): ".$sql);
		$result = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$row = mysql_fetch_array($result);
		
		return $row['proj_name'];
	}
	
	
	// Projects table.
	public function dbGetProjectParameters($projectId,$connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
		$sql = "SELECT  predictive_work, noanswer_call_delay,busy_call_delay,telselect,num_max_call,"
			."qt_useregtel,reg_strictlock,id_telname,tel_reserve,call_time_length,predictive_numbers_tofind,predictive_overcall"
			." from _Projects where id=".$projectId;
		$result = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$this->AM_LogWrite_predictive("Get projet properties (dbGetProjectParameters): ".$sql);
		echo mysql_error();
		$row = mysql_fetch_array($result);
		$this->id_project = $projectId;
		$this->projectParameters = $row;
		
		return $row;
	}
	
	
	public function dbGetNumOfRingingCalls($idProject, $connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
		$sql = "SELECT * FROM _Asterisk_RMringing WHERE projectId=".$idProject;
		$result = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$this->AM_LogWrite_predictive("Get ringing calls: ".$sql);
		
		return mysql_num_rows($result);
	}
	

	public function CountQueueUsers($QueueID, $connect) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
  		$sql = "SELECT count(*) AS cntQU FROM _Asterisk_RMqueues WHERE id_project=$QueueID";
  		$result = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);		
      	$row = mysql_fetch_array($result);	
		
		$this->AM_LogWrite_predictive("Count number of waiting users in queue: ".$sql);
      	return $row['cntQU'];
	}
	
	
	// Calculates and returns number of calls in queue for specific number of users
	public function dbGetNumofCallOverCalls($idProject, $availableUsers) {
		
		$callOverPercent = $this->projectParameters['predictive_overcall'];
		$numOfCallOverCalls = round($callOverPercent*$availableUsers/100);
		$this->AM_LogWrite_predictive("Number of call overs for the project ID=$idProject: ".$numOfCallOverCalls);
		
		return $numOfCallOverCalls;
	}
	
	
	
}

?>