<?php

$startMS = microtime();

require("dbconnect_mysqli.php");
require("functions.php");

$report_name = 'Call Disconnection Report';

if (isset($_GET["from_date"]))				{$from_date=$_GET["from_date"];}
	elseif (isset($_POST["from_date"]))		{$from_date=$_POST["from_date"];}
if (isset($_GET["end_date"]))				{$end_date=$_GET["end_date"];}
	elseif (isset($_POST["end_date"]))		{$end_date=$_POST["end_date"];}
if (isset($_GET["user"]))				{$user_arr=$_GET["user"];}
	elseif (isset($_POST["user"]))		{$user_arr=$_POST["user"];}
if (isset($_GET["submit"]))				{$submit=$_GET["submit"];}
	elseif (isset($_POST["submit"]))		{$submit=$_POST["submit"];}

$data_to_print = 0;

$REQUEST_URI_array = explode('/',$_SERVER['REQUEST_URI']);
array_pop($REQUEST_URI_array);
$ADMIN = implode('/',$REQUEST_URI_array).'/index.php';

$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER'];
$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW'];
$PHP_SELF=$_SERVER['PHP_SELF'];
$PHP_SELF = preg_replace('/\.php.*/i','.php',$PHP_SELF);

$NOW_DATE = date("Y-m-d");
$NOW_TIME = date("Y-m-d H:i:s");
$STARTtime = date("U");
if (!isset($from_date)) {$from_date = $NOW_DATE;}
if (!isset($end_date)) {$end_date = $NOW_DATE;}

$DB=preg_replace("/[^0-9a-zA-Z]/","",$DB);

#############################################
##### START SYSTEM_SETTINGS LOOKUP #####
$stmt = "SELECT use_non_latin,outbound_autodial_active,slave_db_server,reports_use_slave_db,user_territories_active,enable_languages,language_method,admin_screen_colors,report_default_format,allow_web_debug FROM system_settings;";
$rslt=mysql_to_mysqli($stmt, $link);
#if ($DB) {$MAIN.="$stmt\n";}
$qm_conf_ct = mysqli_num_rows($rslt);
if ($qm_conf_ct > 0)
	{
	$row=mysqli_fetch_row($rslt);
	$non_latin =					$row[0];
	$SSoutbound_autodial_active =	$row[1];
	$slave_db_server =				$row[2];
	$reports_use_slave_db =			$row[3];
	$user_territories_active =		$row[4];
	$SSenable_languages =			$row[5];
	$SSlanguage_method =			$row[6];
	$SSadmin_screen_colors =		$row[7];
	$SSreport_default_format =		$row[8];
	$SSallow_web_debug =			$row[9];
	}
if ($SSallow_web_debug < 1) {$DB=0;}
##### END SETTINGS LOOKUP #####
###########################################

if ($non_latin < 1)
	{
	$PHP_AUTH_USER = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_USER);
	$PHP_AUTH_PW = preg_replace('/[^-_0-9a-zA-Z]/', '', $PHP_AUTH_PW);
	$agent = preg_replace('/[^-_0-9a-zA-Z]/','',$agent);
	}
else
	{
	$PHP_AUTH_USER = preg_replace('/[^-_0-9\p{L}]/u', '', $PHP_AUTH_USER);
	$PHP_AUTH_PW = preg_replace('/[^-_0-9\p{L}]/u', '', $PHP_AUTH_PW);
	$agent = preg_replace('/[^-_0-9\p{L}]/u','',$agent);
	}

$user=$agent;

$stmt="SELECT selected_language,full_name from vicidial_users where user='$PHP_AUTH_USER';";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$sl_ct = mysqli_num_rows($rslt);
if ($sl_ct > 0)
	{
	$row=mysqli_fetch_row($rslt);
	$VUselected_language =		$row[0];
	$LOGfull_name				=$row[1];
	}

$auth=0;
$reports_auth=0;
$admin_auth=0;
$auth_message = user_authorization($PHP_AUTH_USER,$PHP_AUTH_PW,'REPORTS',1,0);
if ($auth_message == 'GOOD')
	{$auth=1;}

if ($auth > 0)
	{
	$stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 7 and view_reports='1';";
	if ($DB) {echo "|$stmt|\n";}
	$rslt=mysql_to_mysqli($stmt, $link);
	$row=mysqli_fetch_row($rslt);
	$admin_auth=$row[0];

	$stmt="SELECT count(*) from vicidial_users where user='$PHP_AUTH_USER' and user_level > 6 and view_reports='1';";
	if ($DB) {echo "|$stmt|\n";}
	$rslt=mysql_to_mysqli($stmt, $link);
	$row=mysqli_fetch_row($rslt);
	$reports_auth=$row[0];

	if ($reports_auth < 1)
		{
		$VDdisplayMESSAGE = _QXZ("You are not allowed to view reports");
		Header ("Content-type: text/html; charset=utf-8");
		echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
		exit;
		}
	if ( ($reports_auth > 0) and ($admin_auth < 1) )
		{
		$ADD=999999;
		$reports_only_user=1;
		}
	}
else
	{
	$VDdisplayMESSAGE = _QXZ("Login incorrect, please try again");
	if ($auth_message == 'LOCK')
		{
		$VDdisplayMESSAGE = _QXZ("Too many login attempts, try again in 15 minutes");
		Header ("Content-type: text/html; charset=utf-8");
		echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
		exit;
		}
	if ($auth_message == 'IPBLOCK')
		{
		$VDdisplayMESSAGE = _QXZ("Your IP Address is not allowed") . ": $ip";
		Header ("Content-type: text/html; charset=utf-8");
		echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$auth_message|\n";
		exit;
		}
	Header("WWW-Authenticate: Basic realm=\"CONTACT-CENTER-ADMIN\"");
	Header("HTTP/1.0 401 Unauthorized");
	echo "$VDdisplayMESSAGE: |$PHP_AUTH_USER|$PHP_AUTH_PW|$auth_message|\n";
	exit;
	}

##### BEGIN log visit to the vicidial_report_log table #####
$LOGip = getenv("REMOTE_ADDR");
$LOGbrowser = getenv("HTTP_USER_AGENT");
$LOGscript_name = getenv("SCRIPT_NAME");
$LOGserver_name = getenv("SERVER_NAME");
$LOGserver_port = getenv("SERVER_PORT");
$LOGrequest_uri = getenv("REQUEST_URI");
$LOGhttp_referer = getenv("HTTP_REFERER");
$LOGbrowser=preg_replace("/\'|\"|\\\\/","",$LOGbrowser);
$LOGrequest_uri=preg_replace("/\'|\"|\\\\/","",$LOGrequest_uri);
$LOGhttp_referer=preg_replace("/\'|\"|\\\\/","",$LOGhttp_referer);
if (preg_match("/443/i",$LOGserver_port)) {$HTTPprotocol = 'https://';}
  else {$HTTPprotocol = 'http://';}
if (($LOGserver_port == '80') or ($LOGserver_port == '443') ) {$LOGserver_port='';}
else {$LOGserver_port = ":$LOGserver_port";}
$LOGfull_url = "$HTTPprotocol$LOGserver_name$LOGserver_port$LOGrequest_uri";

$LOGhostname = php_uname('n');
if (strlen($LOGhostname)<1) {$LOGhostname='X';}
if (strlen($LOGserver_name)<1) {$LOGserver_name='X';}

$stmt="SELECT webserver_id FROM vicidial_webservers where webserver='$LOGserver_name' and hostname='$LOGhostname' LIMIT 1;";
$rslt=mysql_to_mysqli($stmt, $link);
if ($DB) {echo "$stmt\n";}
$webserver_id_ct = mysqli_num_rows($rslt);
if ($webserver_id_ct > 0)
	{
	$row=mysqli_fetch_row($rslt);
	$webserver_id = $row[0];
	}
else
	{
	##### insert webserver entry
	$stmt="INSERT INTO vicidial_webservers (webserver,hostname) values('$LOGserver_name','$LOGhostname');";
	if ($DB) {echo "$stmt\n";}
	$rslt=mysql_to_mysqli($stmt, $link);
	$affected_rows = mysqli_affected_rows($link);
	$webserver_id = mysqli_insert_id($link);
	}
$stmt="INSERT INTO vicidial_report_log set from_date=NOW(), user='$PHP_AUTH_USER', ip_address='$LOGip', report_name='$report_name', browser='$LOGbrowser', referer='$LOGhttp_referer', notes='$LOGserver_name:$LOGserver_port $LOGscript_name |$user, $query_date, $shift, $file_download, $report_display_type|', url='$LOGfull_url', webserver='$webserver_id';";
if ($DB) {echo "|$stmt|\n";}
$rslt=mysql_to_mysqli($stmt, $link);
$report_log_id = mysqli_insert_id($link);
##### END log visit to the vicidial_report_log table #####

if ($SSadmin_screen_colors != 'default')
	{
	$stmt = "SELECT menu_background,frame_background,std_row1_background,std_row2_background,std_row3_background,std_row4_background,std_row5_background,alt_row1_background,alt_row2_background,alt_row3_background,web_logo FROM vicidial_screen_colors where colors_id='$SSadmin_screen_colors';";
	$rslt=mysql_to_mysqli($stmt, $link);
	if ($DB) {echo "$stmt\n";}
	$colors_ct = mysqli_num_rows($rslt);
	if ($colors_ct > 0)
		{
		$row=mysqli_fetch_row($rslt);
		$SSmenu_background =		$row[0];
		$SSframe_background =		$row[1];
		$SSstd_row1_background =	$row[2];
		$SSstd_row2_background =	$row[3];
		$SSstd_row3_background =	$row[4];
		$SSstd_row4_background =	$row[5];
		$SSstd_row5_background =	$row[6];
		$SSalt_row1_background =	$row[7];
		$SSalt_row2_background =	$row[8];
		$SSalt_row3_background =	$row[9];
		$SSweb_logo =				$row[10];
		}
	}
$Mhead_color =	$SSstd_row5_background;
$Mmain_bgcolor = $SSmenu_background;
$Mhead_color =	$SSstd_row5_background;

$selected_logo = "./images/vicidial_admin_web_logo.png";
$selected_small_logo = "./images/vicidial_admin_web_logo.png";
$logo_new=0;
$logo_old=0;
$logo_small_old=0;
if (file_exists('./images/vicidial_admin_web_logo.png')) {$logo_new++;}
if (file_exists('vicidial_admin_web_logo_small.gif')) {$logo_small_old++;}
if (file_exists('vicidial_admin_web_logo.gif')) {$logo_old++;}
if ($SSweb_logo=='default_new')
	{
	$selected_logo = "./images/vicidial_admin_web_logo.png";
	$selected_small_logo = "./images/vicidial_admin_web_logo.png";
	}
if ( ($SSweb_logo=='default_old') and ($logo_old > 0) )
	{
	$selected_logo = "./vicidial_admin_web_logo.gif";
	$selected_small_logo = "./vicidial_admin_web_logo_small.gif";
	}
if ( ($SSweb_logo!='default_new') and ($SSweb_logo!='default_old') )
	{
	if (file_exists("./images/vicidial_admin_web_logo$SSweb_logo")) 
		{
		$selected_logo = "./images/vicidial_admin_web_logo$SSweb_logo";
		$selected_small_logo = "./images/vicidial_admin_web_logo$SSweb_logo";
		}
	}

	$stmt = "SELECT DISTINCT user FROM vicidial_users WHERE user NOT IN('VDAD','VDCL');";
	$rslt = mysql_to_mysqli($stmt, $link);
	while($row = mysqli_fetch_assoc($rslt))
	{
		$user_list[] = $row['user'];
	}

	if(isset($submit) && !empty($submit))
	{
		$user_string = "'".implode("', '", $user_arr)."'";
		
		$stmt = "SELECT * FROM (SELECT uniqueid,lead_id,list_id,campaign_id,call_date,start_epoch,end_epoch,length_in_sec,status,phone_code,phone_number,user,comments,processed,user_group,term_reason, 'OUTBOUND' as direction FROM vicidial_log as vl WHERE vl.user IN($user_string) AND vl.call_date BETWEEN '".$from_date."' AND '".$end_date."' UNION SELECT uniqueid,lead_id,list_id,campaign_id,call_date,start_epoch,end_epoch,length_in_sec,status,phone_code,phone_number,user,comments,processed,user_group,term_reason, 'INBOUND' as direction from vicidial_closer_log as vcl WHERE vcl.user IN($user_string) AND vcl.call_date BETWEEN '".$from_date."' AND '".$end_date."') cl;";
		$rslt = mysql_to_mysqli($stmt, $link);
		while($row = mysqli_fetch_assoc($rslt))
		{
			$call_data[] = $row;
		}
	}

	##### BEGIN Set variables to make header show properly #####
	$ADD =					'999999';
	$hh =					'reports';
	$sh =					'sheet';
	$LOGast_admin_access =	'1';
	$ADMIN =				'index.php';
	$page_width='770';
	$section_width='750';
	$header_font_size='3';
	$subheader_font_size='2';
	$subcamp_font_size='2';
	$header_selected_bold='<b>';
	$header_nonselected_bold='';
	$users_color =		'#FFFF99';
	$users_font =		'BLACK';
	$users_color =		'#E6E6E6';
	$subcamp_color =	'#C6C6C6';
	##### END Set variables to make header show properly #####

echo "<!DOCTYPE html>";
echo "<html>";
echo "<head>";

echo "<script language=\"JavaScript\" src=\"calendar_db.js\"></script>\n";
echo "<link rel=\"stylesheet\" href=\"calendar.css\">\n";
echo "<link rel=\"stylesheet\" href=\"horizontalbargraph.css\">\n";
require("chart_button.php");
echo "<script src='chart/Chart.js'></script>\n"; 
echo "<script language=\"JavaScript\" src=\"vicidial_chart_functions.js\"></script>\n";
echo "<script src=\"inc\libs\jquery\jquery.js\"></script>";
echo "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css\">";
echo "<link rel=\"stylesheet\" href=\"inc\libs\bootstrap\bootstrap.css\">";
echo "<link rel=\"stylesheet\" href=\"inc/js/multiselect/dist/css/bootstrap-multiselect.css\">";
echo "<link rel=\"stylesheet\" href=\"inc/js/multiselect/dist/css/bootstrap-multiselect.min.css\">";
echo "<link rel=\"stylesheet\" href=\"inc/libs/sidebar5/css/next-sidebar.css\" />";
echo "<link rel=\"stylesheet\" href=\"inc/libs/sidebar5/css/perfect-scrollbar.css\" />";
echo "<link rel=\"stylesheet\" href=\"inc/css/style.css\">";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"vicidial_stylesheet.php\">\n";
echo "<script language=\"JavaScript\" src=\"help.js\"></script>\n";
echo "<div id='HelpDisplayDiv' class='help_info' style='display:none;z-index:99;'></div>";

echo "<title>ETI Report | "._QXZ($report_name)."</title>";
echo "</head><body>";
include("admin_header.php");
echo "<div class=\"container-fluid admin_form_blocks\">";
echo "<div class=\"container-fluid admin_form_heading\"><div><span>"._QXZ($report_name)."</span></div></div>";
echo "<div class=\"container-fluid mt-3\">";
echo "<FORM ACTION=\"$PHP_SELF\" METHOD=\"GET\" name=\"call_disconnectionReport\" id=\"call_disconnectionReport\">";
echo "<div class=\"form-row\">";
echo "<div class=\"form-group col-sm-3\"><label>"._QXZ("Date From")."</label>";
echo "<div class=\"input-group\"><input type=\"text\" name=\"from_date\" value=\"$from_date\" class=\"form-control\"><div class=\"input-group-append\"><span class=\"input-group-text\">";
echo "<script language=\"JavaScript\">
	var o_cal = new tcal ({
		// form name
		'formname': 'call_disconnectionReport',
		// input name
		'controlname': 'from_date'
	});
	o_cal.a_tpl.yearscroll = false;
	// o_cal.a_tpl.weekstart = 1; // Monday week start
	</script>";
echo "</span></div></div></div>";
echo "<div class=\"form-group col-sm-3\"><label>"._QXZ("Date To")."</label>";
echo "<div class=\"input-group\"><input type=\"text\" name=\"end_date\" value=\"$end_date\" class=\"form-control\"><div class=\"input-group-append\"><span class=\"input-group-text\">";
echo "<script language=\"JavaScript\">
	var o_cal = new tcal ({
		// form name
		'formname': 'call_disconnectionReport',
		// input name
		'controlname': 'end_date'
	});
	o_cal.a_tpl.yearscroll = false;
	// o_cal.a_tpl.weekstart = 1; // Monday week start
	</script>";
echo "</span></div></div></div>";
echo "<div class=\"form-group col-sm-3\"><label>User</label><select class=\"multi_select custom-select\" name=\"user[]\" multiple>";
foreach($user_list as $key=>$value)
{
	echo "<option value=\"$value\" ";
	if(isset($user_arr) && in_array($value, $user_arr))
	{
		echo "selected";
	}
	echo ">$value</option>";
}
echo "</select></div>";
echo "<div class=\"form-group col-sm-3 text-center\"><label>&nbsp;</label><br><input class=\"btn btn-secondary\" type=\"submit\" name=\"submit\" value=\"Submit\"></div>";

echo "</div></FORM></div></div>";
if(isset($submit))
{
	echo "<div class=\"container-fluid admin_form_blocks\">";
	echo "<table class=\"table table-sm table-bordered table-striped admin_form_table\"><thead><tr><th>#</th><th>Unique ID</th><th>Lead ID</th><th>Campaign ID</th><th>Call Date</th><th>Length In Seconds</th><th>Status</th><th>Phone Number</th><th>User</th><th>Direction</th><th>User Group</th><th>Disconnected By</th></tr></thead><tbody>";
	$i = 1;
	foreach($call_data as $key => $value)
	{
		echo "<tr>";
		echo "<td>$i</td>";
		echo "<td>".$value['uniqueid']."</td>";
		echo "<td>".$value['lead_id']."</td>";
		echo "<td>".$value['campaign_id']."</td>";
		echo "<td>".$value['call_date']."</td>";
		echo "<td>".$value['length_in_sec']."</td>";
		echo "<td>".$value['status']."</td>";
		echo "<td>".$value['phone_code']."-".$value['phone_number']."</td>";
		echo "<td>".$value['user']."</td>";
		echo "<td>".$value['direction']."</td>";
		echo "<td>".$value['user_group']."</td>";
		echo "<td>".$value['term_reason']."</td>";
		echo "</tr>";
		$i++;
	}
	echo "</tbody></table>";
	echo "</div>";
}
echo "</body>";

echo "<script src=\"inc/libs/cookie/src/jquery.cookie.js\"></script>";
echo "<script src=\"inc/js/custom_javascript.js\"></script>";
echo "<script src=\"inc/libs/sidebar5/js/perfect-scrollbar.min.js\"></script>";
echo "<script src=\"inc/libs/lordicons/lordiIcon.js\"></script>";
echo "<script src=\"inc\libs\bootstrap\bootstrap.js\"></script>";
echo "<script src=\"inc/js/multiselect/dist/js/bootstrap-multiselect.js\"></script>";
echo "<script src=\"inc/libs/sidebar5/js/next-sidebar.js\"></script>";
echo "<script>$(function(){
		  $('.multi_select').multiselect({
		  	includeSelectAllOption: true
		  });
		});</script>";

echo "</html>";



?>