<?php

require_once("./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 $asterisk_username; 
	public $asterisk_password; 
	public $asterisk_ip;
	public $asterisk_port;
	public $SIP;
	public $id_user;
	
	
	
	
	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_predictive("--- 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"));
		while ($MyPacket AND $CorrectUniqueid == false AND $TimePass == false) {
			switch ($MyPacket['Event']) {
				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
						
						$this->AM_LogWrite_predictive("Checking, if socket is alive after answer outside (Join): ".$this->mSocket);
						$this->Logoff();
						$this->AM_LogWrite_predictive("Loging out from the socket, Somebody answered outside (Join).");
						
						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")); 
						// 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 = 22;
								$status_rec_telnum = 700;
								
								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 = 25;
								$status_rec_telnum = 700;
								
								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")); 
						// 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_predictive("--- 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();
		
		$cntRowQueue = false;
		$cnt_free_agent = 0;
		while ($cntRowQueue == false 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));
			if ($row['sip']) {
				$this->sip_internal = $row['sip'];
				$cntRowQueue = true;
				$this->AM_LogWrite_predictive("I found the SIP inside queue in $cnt_free_agent seconds: ".$row['sip']);
			} else {
				$sql = "UNLOCK TABLES";
				mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
				$this->AM_LogWrite_predictive("Unlock asterisk_RMqueues inside while: ".$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);
			
			// ponovno se priklopim na socket da spojim kanala...
			if ($this->LogOn($this->asterisk_username, $this->asterisk_password, $this->asterisk_ip, $this->asterisk_port, $this->SIP, $this->id_user)) {
				$this->AM_LogWrite_predictive("Socket LogOn() inside bridge.");
				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->AM_LogWrite_predictive("Logon to socket for bridging the channels failed!");
			}
		} else {
			$this->AM_LogWrite_predictive("60s bridge timeout. Call disabled!");
			$this->BridgeStatus = 21;
			$this->SaveDialStatus(3, 700, $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);
			global $SQLconnect;
			$SQLconnect = $connect;
			$this->HangupExternal();
		}
		$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 HangupExternal() {
		
		if ($this->LogOn($this->asterisk_username, $this->asterisk_password, $this->asterisk_ip, $this->asterisk_port, $this->SIP, $this->id_user))
		{
			$arrLoginPairs = array("Action" => "Hangup", 
									"Channel" => $this->ExternalChannel
								   );
			
			$strAddPairs = $this->AddPair_AM($arrLoginPairs);
			
			// write Hangup command to LOG file
			$this->AM_LogWrite_predictive("----- Hangup ------\r\n".$strAddPairs."----- END Hangup ------\r\n\r\n");
			
			if ($this->SendPacket($strAddPairs) == true) {
				return true;
			} else {
				return false;
			}
		}
		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, $connect)	{
		$SQLconnect = $connect;;
		global $CATI_base_structure;
		
		$sql = "SELECT (max(QueueOrder)+1) AS id_queue FROM _Asterisk_RMqueues WHERE `id_project`=".$id_project;
		$result = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$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 = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$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 = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$this->AM_LogWrite_predictive("User adding to the queue: ".$sql);
	}
	
	
	public function RemoveFromQueue($SIP, $id_project, $connect)	{
		$SQLconnect = $connect;;
		global $CATI_base_structure;

		$sql = "DELETE FROM _Asterisk_RMqueues WHERE `id_project`=$id_project AND `sip`='$SIP'";
		mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$this->AM_LogWrite_predictive("Remove user from queue: ".$sql);
		
		$sql = "UPDATE _Asterisk_RMconnect SET connect=0 WHERE `sip`='$SIP'";
		mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
		$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) {
		return true;
		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->selectedIndex = $first_TelNumber['id_tel'];
		$this->isAppointment = $first_TelNumber['IsApp'];
		if($this->isAppointment && $this->dogovor_spec_num[$this->selectedIndex] )
		{
			$this->selectedTelephone = $this->dogovor_spec_num[$this->selectedIndex];
			
		}
		else
			$this->selectedTelephone = $first_TelNumber['telephone'];
			
		$this->selectedNetwork = $first_TelNumber['oms'];
		$this->selectedRegion = $first_TelNumber['tpreg'];
				
		//unset($this->TelNumberContainer[$key_TelNumber]);
		
		return $this->selectedTelephone;
	}
	
	
	
/**
	 * 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
		$selected_quota_layer = $parameters['id_select_layer'];					// int $selected_quota_layer - do we use quotas (example 20x02 network, 30x03 network , ...)
		$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.

		$limit = $parameters['predictive_numbers_tofind'];
			unset($id_tel_array);
		 
		 	$this->appointmentData = array();
			// grem izbrati telefonsko stevilko			
			// preverim ali kaksen dogovor ze obstaja
			$this->AM_LogWrite_predictive("FindNumber(). Checking appointment.");
			
			$tren_cas = time();
			
			// ce imam vklopljen strict locking moram zracunat, katere regije se nimam zapolnjene in izbirat tel stevilke samo od tam
			$useTable = $tren_tabl.'___telIndex AS a';
			$useLockTable = $tren_tabl.'___telIndex AS a';
			if ( $selected_quota_layer   || true ) {
			//new strict locking action :)
			$sql = "SELECT distinct id_question,source,q_name FROM quota_layer a LEFT JOIN quota_layer_addon b ON a.layer = b.id WHERE id_project = $id_project AND telSelect = 1";	
			$res = mysql_db_query($CATI_base_structure, $sql, $SQLconnect);
			$this->AM_LogWrite_predictive("SEARCHING QUOTAS: $sql");
			//we have all the fields that we have to bind!
			while ($row = mysql_fetch_row($res))
			{
				$telField = $row[2];
				if($row[1] == 1)
					$telField  = 'tel_'.$telField;
				$strictlock_region_def .= ' AND a.'.$telField.' = b.TP_'.$row[2];	
			}
			if($strictlock_region_def)
			{
				$strictlock_region_def .= ' AND isLocked = 0';
				$useTable .= ','.$tren_tabl.'___quotaLock as b';
				$useLockTable .= ' WRITE,'.$tren_tabl.'___quotaLock AS b';
			}
	
			}
			// 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, a.id, app_middle,app_call_this_num FROM $useTable WHERE status='91' AND app_time<'$tren_cas' AND tdisable=0 $strictlock_region_def ORDER by app_time LIMIT $limit";
	 		$this->AM_LogWrite_predictive("Select appointment if exist: ".$sql_show_dogovor);
			$result_show_dogovor = mysql_db_query($CATI_base_structure, $sql_show_dogovor, $SQLconnect);
			
			if ( mysql_num_rows($result_show_dogovor) > 0 ) {
				while ($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
					if ($row_show_dogovor[5]) 
					{
						$this->dogovor_spec_num[$telnum_index] =  str_replace( array('/',' ') ,'' ,$row_show_dogovor[5]);
					}
					// konec locevanja komentarja
					$id_idx_dogovor[] = $row_show_dogovor[3];
					$id_tel_array[] = $telnum_index;
					// rezerviram dogovor
					
				}
				$sql_reserve_dogovor = "UPDATE ".$tren_tabl."___telIndex SET status='90' WHERE id IN (".implode(',',$id_idx_dogovor).")";
	 			$this->AM_LogWrite_predictive("Reserve appointment: ".$sql_reserve_dogovor);
				$result_reserve_dogovor = mysql_db_query($CATI_base_structure, $sql_reserve_dogovor, $SQLconnect);

				$dogovor_exist = "YES";
				$index_sucess = "YES";
				$isDogovor = true;
				$this->AM_LogWrite_predictive("APPointment found: ".$telnum_index);
				$NumbersFound = 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
			
				// pridobim id_layerja ki ima tpreg nastavljen
			/*	$this->AM_LogWrite_predictive("Get ID layer where region quota is set: ".$selected_quota_layer);
				$select_quota_tpreg = "SELECT q_name,source FROM quota_layer WHERE layer = $selected_quota_layer";
				$res = mysql_db_query($CATI_base_structure, $select_quota_tpreg, $SQLconnect);
				while ($row = mysql_fetch_row($res))
				{
					$quotaVars[] = $row[0];
					if($row[1] == 0 )
					{
						$telVars[] = $row[0];
					}
					else 
					{
						$telVars[] = 'tel_'.$row[0];
					}
				}
				if(!is_array($quotaVars))
			  		{
			  			$this->AM_LogWrite_predictive("ERROR:  Selected telefone layer does not exist or isn't defined!!!! - $select_quota_tpreg");
			  			
			  		}
			  		
			  		
			  		$select_quota_tpreg = "SELECT TP_".implode(',TP_',$quotaVars).",q_value FROM {$tren_tabl}___quotaLimits WHERE id_layer=$selected_quota_layer ORDER BY q_value";
		//		echo $select_quota_tpreg."<br>";
		  		$res = mysql_db_query($CATI_base_structure, $select_quota_tpreg, $SQLconnect);
		  		while ($row_quota_tpreg = mysql_fetch_assoc($res))
		  		{
		  			
		  			$vals = array();
		  			foreach ($quotaVars as $qVar) {
		  				$vals[] = $row_quota_tpreg['TP_'.$qVar];
		  			}
		  			
		  			
		  			$tpreg_quota_array[ implode('_',$vals)  ] = $row_quota_tpreg['q_value'];
		//			echo "$row_quota_tpreg[value] : $row_quota_tpreg[number] <br>";
		  		}
		  		$this->AM_LogWrite_predictive("Getting quota limits - $select_quota_tpreg");
		  		if(!$tpreg_quota_array)
		  		{
		  			$this->AM_LogWrite_predictive("Error: Selected quotas not defined!!!");
		  		}
		  		mysql_free_result($res);
			  		
		  		$select_ank_tpreg = "SELECT TP_".implode(',TP_',$quotaVars).", count(*) AS number FROM {$tren_tabl}___quotaCalc GROUP BY TP_".implode(',TP_',$quotaVars);
		//		echo $select_ank_tpreg."<br>";
		  		$result_ank_tpreg = mysql_db_query($CATI_base_structure, $select_ank_tpreg, $SQLconnect);
		  		while ( $row_ank_tpreg = mysql_fetch_assoc($result_ank_tpreg) ) {
		  			$vals = array();
		  			foreach ($quotaVars as $qVar) {
		  				$vals[] = $row_ank_tpreg['TP_'.$qVar];
		  			}
		  			$tpreg_ank_array[ implode('_',$vals) ] = $row_ank_tpreg['number'];
		//			echo "$row_ank_tpreg[value] : $row_ank_tpreg[number] <br>";
		  		}
		  		$this->AM_LogWrite_predictive("Getting quota calc - $select_ank_tpreg");
		  		mysql_free_result($result_ank_tpreg);
			  		
		 
		  		foreach ($tpreg_quota_array as $index_qt_array => $quota_limit) {
		  				
		  				if($quota_limit > 0 && $quota_limit > $tpreg_ank_array[$index_qt_array] )
		  				{
		  					
		  					$keyArr = explode('_',$index_qt_array);
		  					$orStat = array();
		  					for($i=0;$i<count($keyArr);$i++)
		  					{
		  						$orStat[] = $telVars[$i] ."='".$keyArr[$i]."' ";
		  					}
		  					$strictlock_def_array[] ="( ". implode(' AND ',$orStat). " )";
		  				}
		  		}
		  		if($strictlock_def_array)
		  			$strictlock_region_def = 'AND ('. implode(' OR ', $strictlock_def_array ) .')';
		  		else 
		  			$strictlock_region_def = 'AND false ';//no quotas are avaliable!
		  		*/
			
			
			// 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;

			$statusCondition = "(status = 0 OR status = 22 OR status = 25)";
			$select_telnum_index = "SELECT id_tel FROM ".$useTable." 
									WHERE a.id > $rand_start_telbase AND $statusCondition AND call_time < $trenutni_cas AND call_num<$num_max_call $strictlock_region_def AND tdisable=0 ORDER BY a.id LIMIT $limit";
			
			$select_lock_index = "LOCK TABLES $useLockTable 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 ".$useTable." 
										WHERE a.id < $rand_start_telbase AND $statusCondition AND call_time < $trenutni_cas AND call_num<$num_max_call $strictlock_region_def AND tdisable=0 ORDER BY a.id DESC LIMIT $limit";
				$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));
			}
		}
		
		// ce sem uspel najti primerno stevilko
		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 ".$tren_tabl."___telIndex AS a SET 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");
				
				if(mysql_db_query($CATI_base_structure, $query_update_telnum_sts, $SQLconnect))
				{
					$this->AM_LogWrite_predictive("Reserve telephone number is sucess!");
				}
				else 
					$this->AM_LogWrite_predictive("MySQL error on reserving telephone number: ".mysql_error());
				$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_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'] = $isDogovor;

				$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, 
										status_rec=$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_array = getdate($startCallTime);
	  			
		// 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_status_rec='$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=$startCallTime 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', 
  								 status_rec='$status_rec_telnum',last_call='$startCallTime',call_time=0, 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='$startCallTime', id_tel='".$id_selected_telnum."',id_telname='$this->id_telname', 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 == 22 || $set_dial_status == 25)	{
			// 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_status_rec='$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=$startCallTime 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_status_rec='$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=$startCallTime 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 ($set_dial_status == 22)
					$newCallTime = $startCallTime + ($busy_call_delay*60);
				else if ($set_dial_status == 25)
					$newCallTime = $startCallTime + ($noanswer_call_delay*60);
					
				$query_update_telnum_sts = "UPDATE ".$tren_tabl."___telIndex SET status='91', status_rec='$status_rec_telnum', "
					."id_ank='$idUser',last_call=$startCallTime, app_time=$newCallTime WHERE id_tel=$id_selected_telnum";
					
			} else {
				if ($set_dial_status == 22)
					$newCallTime = $startCallTime + ($busy_call_delay*60);
				else if ($set_dial_status == 25)
					$newCallTime = $startCallTime + ($noanswer_call_delay*60);
					
				$query_update_telnum_sts = "UPDATE ".$tren_tabl."___telIndex SET  status='$set_dial_status', "
					."status_rec='$status_rec_telnum', last_call='$startCallTime', "
					."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 ".$tren_tabl."___telLog SET status='$set_dial_status', id_user='$idUser', "
      			."status_rec='$status_rec_telnum',call_time='".$startCallTime."',end_time='".time()."', "
      			."id_tel='$id_selected_telnum',id_telname='$this->id_telname' , oms='$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) {//tu ne more bit 99, 22 ali 25!!!!!!!!!!!!!!?!!!!!!!
			// 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_status_rec='$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=$startCallTime 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',"
				." status_rec='$status_rec_telnum', last_call='$startCallTime',call_time=0, 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='".$startCallTime."',end_time='".time()."'"
      			.", id_tel='$id_selected_telnum',id_telname='$this->id_telname',  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 = 'tel___'.$row['name'];
		$this->id_telname = $telId;
	}
	
	
	// 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) {
		return; //s tem ko smo zapisalistatus smo sprostili stevilko! ooooooooooouuuuuuuuuh yeah!
		$SQLconnect = $connect;;
		global $CATI_base_structure;
		
		if (!$region) 
			$sql = "UPDATE telephone_".$tren_tabl."_index SET  regija=call_time,call_time=0 WHERE id_tel=$telNumId";
		else 
			$sql = "UPDATE telephone_".$tren_tabl."_index 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);
		$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,"
			."id_select_layer,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);
		$row = mysql_fetch_array($result);
		
		$this->id_project = $projectId;
		
		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($properties,$availableUsers) {
		$SQLconnect = $connect;
		global $CATI_base_structure;
		
		
		$callOverPercent = $properties['predictive_overcall'];
		$numOfCallOverCalls = round($callOverPercent*$availableUsers/100);
		$this->AM_LogWrite_predictive("Number of call overs for the project ID=$idProject: ".$numOfCallOverCalls);
		
		return $numOfCallOverCalls;
	}
	
	
	
}

?>