<?php
ini_set("display_errors", 1);
require_once("dbconnect_mysqli.php");
require_once("functions.php");

	if(isset($_GET['user'])){$user = $_GET['user'];}
		elseif(isset($_POST['user'])){$user = $_POST['user'];}
	if(isset($_GET['caller_id'])){$caller_id = $_GET['caller_id'];}
		elseif(isset($_POST['caller_id'])){$caller_id = $_POST['caller_id'];}
	$NOW_TIME = date("Y-m-d H:i:s");
	$mel=1;					# Mysql Error Log enabled = 1

	if($user && $caller_id != '')
	{
		$stmt = "SELECT * FROM eti_agent_caller_id WHERE user = '".$user."'; ";
		$rslt = mysql_to_mysqli($stmt, $link);
		if($rslt)
		{
			if(mysqli_num_rows($rslt) > 0)
			{
				$stmt = "UPDATE vicidial_users SET eti_selected_cli = '".$caller_id."' WHERE user = '".$user."';";
				$rslt = mysql_to_mysqli($stmt, $link);
				if($rslt)
				{
					$result = array("flag" => true);
					$stmt = "INSERT INTO eti_agent_caller_id_history(user, log) VALUES('".$user."', \"$stmt\")";
					$rslt = mysql_to_mysqli($stmt, $link);
				}
				else
				{
					$result = array("flag" => false);
				}
			}
			else
			{
				// $stmt = "INSERT INTO eti_agent_caller_id(user, caller_id) VALUES('".$user."','".$caller_id."')";
				// $rslt = mysql_to_mysqli($stmt, $link);
				// if($rslt)
				// {
				// 	$result = array("flag" => true);
				// 	$stmt = "INSERT INTO eti_agent_caller_id_history(user, log) VALUES('".$user."', \"$stmt\")";
				// 	$rslt = mysql_to_mysqli($stmt, $link);
				// }
				// else
				// {
				// 	$result = array("flag" => false);
				// }
			}
		}
		else
		{
			$result = array("flag" => false);
		}
	}
	elseif($user && $caller_id == '')
	{
		$stmt = "UPDATE vicidial_users SET eti_selected_cli = null WHERE user = '".$user."' ";
		$rslt = mysql_to_mysqli($stmt, $link);
		if($rslt)
		{
			$result = array("flag" => true);
			$stmt = "INSERT INTO eti_agent_caller_id_history(user, log) VALUES('".$user."', \"$stmt\")";
			$rslt = mysql_to_mysqli($stmt, $link);
		}
		else
		{
			$result = array("flag" => false);
		}
	}

	echo json_encode($result);

?>