<?php session_start();
include ('../inc/dbcon.php');
include ('../inc/functions.php');
include ('../inc/chatfunction.php');
if(isset($_SESSION["axeslogin"]) && $_SESSION["axeslogin"] == true){    
$aid=$_SESSION['uid'];
$brid=$_SESSION['abrid'];    
$today = strftime("%Y-%m-%d", time());    
$dtnow = date("Y-m-d h:i:s", time());    
}else{
header('Location:../index.php');
exit;    
}
?>
<?php if(isset($_POST['chatlist'])){ ?>
<ul class="live-search-list" style="padding:0px;">
<?php
$query = "SELECT * FROM (SELECT tbl_chat.id,tbl_chat.joined,tbl_chat.online,tbl_chat.last_acive,tbl_chat.status,if(tbl_user.image IS NULL,'duser.jpg',tbl_user.image) AS picname,tbl_user.name,tbl_chat.id AS username FROM tbl_chat LEFT JOIN tbl_user ON tbl_user.id=tbl_chat.id) res WHERE id != '".$_SESSION['uid']."' ORDER BY id = '0' , online";
$result = $con->query($query);
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$username = $row['username'];
$picname = $row['picname'];
$picname = (strlen($picname)<1)? "duser.jpg" : $picname;

$res = mysqli_query($con, "SELECT * FROM (SELECT tbl_chat.id,tbl_chat.joined,tbl_chat.online,tbl_chat.last_acive,tbl_chat.status,if(tbl_user.image IS NULL,'duser.jpg',tbl_user.image) AS picname,tbl_user.name,tbl_chat.id AS username FROM tbl_chat LEFT JOIN tbl_user ON tbl_user.id=tbl_chat.id) res WHERE id='$id' AND (TIMESTAMPDIFF(MINUTE, last_acive, NOW()) > 1 OR online='0');");
if($res === FALSE) {
die(mysqli_error($con)); // TODO: better error handling
}
$num = mysqli_num_rows($res);
if($num == "0")
$onofst = "Online";
else
$onofst = "Offline";
?>

<li class="iflychat-olist-item iflychat-ol-ul-user-img iflychat-userlist-room-item chat_options">
<div class="drupalchat-self-profile">
<span title="<?php echo $onofst ?>" class="<?php echo $onofst ?> statuso" style="text-align: right"><span class="statusIN"><i class="fa fa-circle" aria-hidden="true"></i></span></span>
<div class="drupalchat-self-profile-div">
<div class="drupalchat-self-profile-img + localhost-avatar-sprite-28 <?php echo strtoupper($username[0]); ?>_3">
<?php if(!empty($row['picname'])) {?>
<img src="../img/user/<?php echo $picname; ?>"/>
<?php } ?>
</div>
</div>
<div class="drupalchat-self-profile-namdiv">
<a class="drupalchat-profile-un drupalchat_cng" href="javascript:void(0)" onclick="javascript:chatWith('<?php echo $username ?>','<?php echo $picname; ?>','<?php echo $onofst ?>')"><?php echo get_fild_data('tbl_user',$username,'name'); ?></a>
</div>

</div>
</li>
<?php } ?>
</ul>    
<?php exit; } ?>


<?php
if(isset($_POST['check'])){
$mod=intval($_POST['check']);
if($mod==1){    
$_SESSION['chatmod']='on';
}else{
$_SESSION['chatmod']='off';
if(isset($_SESSION['chatHistory'])){
unset($_SESSION['chatHistory']);    
}
if(isset($_SESSION['openChatBoxes'])){
unset($_SESSION['openChatBoxes']);    
}    
}
$timenow = date('Y-m-d H:i:s');
$sql="SELECT * FROM tbl_chat WHERE id='$aid'";
$res=mysqli_query($con,$sql);    
if($res === FALSE) { die(mysqli_error($con));}
$num = mysqli_num_rows($res);
if($num == "0"){
mysqli_query($con, "INSERT INTO tbl_chat(id,joined,online,last_acive,status) VALUES ('$aid','$timenow','1','$timenow','0')");     
}else{
mysqli_query($con, "UPDATE tbl_chat SET online='$mod', last_acive = '$timenow' WHERE id='$aid'");     
}   
echo json_encode(array(
'status' => $_SESSION['chatmod']
));
exit;
}

if(isset($_POST['cname'])){
echo get_userdata('name',$_POST['cname'],''); 
exit;    
}

if ($_GET['action'] == "lastseen") {lastseen();}
if ($_GET['action'] == "get_all_msg") { get_all_msg(); }
if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
if ($_GET['action'] == "sendchat") { sendChat(); }
if ($_GET['action'] == "closechat") { closeChat($con); }
if ($_GET['action'] == "startchatsession") { startChatSession($con); }
if ($_GET['action'] == "typingstatus") { typingStatus($con); }

if (!isset($_SESSION['chatHistory'])) {
$_SESSION['chatHistory'] = array();	
}

if (!isset($_SESSION['openChatBoxes'])) {
$_SESSION['openChatBoxes'] = array();	
}

if (!isset($_SESSION['chatpage'])) {
	$_SESSION['chatpage'] = 1;	
}

function lastseen() {
$id=get_userdata('id','',$_GET['uname']);
echo $lastseen =  getlastActiveTime($id);
}

function get_all_msg() {
global $con;
$from = $_SESSION['uid'];
$from_id = $_SESSION['uid'];
$perPage = 10;

$sql = "SELECT * FROM tbl_messages WHERE  ((to_uname = '$from' AND from_uname = '".$_GET['client']."' AND recd = '1') OR (to_uname = '".$_GET['client']."' AND from_uname = '$from')) ORDER BY message_id DESC ";

$page = 1;
if(!empty($_GET["page"])) {
$_SESSION['chatpage'] = $page = $_GET["page"];
}
	
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
	
$query =  $sql . " LIMIT " . $start . "," . $perPage;

$query = $con->query($query);
	
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = $rowcount = mysqli_num_rows(mysqli_query($con, $sql));
}

$pages  = ceil($_GET["rowcount"]/$perPage);

$items = '';
if(!empty($query)) {

}

while ($chat = mysqli_fetch_array($query)) {

$to_id = get_userdata('id','',$chat['from_uname']);
$picname = get_userdata('picname','',$chat['from_uname']);
$status = get_userdata('online','',$chat['from_uname']);

$picname = ($picname == "")? "duser.jpg" : $picname;
$status  = ($status == "0")? "Offline" : "Online";

$picname2 = get_userdata('picname','',$chat['to_uname']);

$picname2 = ($picname2 == "")? "duser.jpg" : $picname2;


$chat['message_content'] = sanitize($chat['message_content']);
		
if($chat['from_uname'] == $from)
{
$u = 1;	
$sespic = $picname;
}
else{
$u = 2;	
$sespic = $picname2;
}

if (strpos($chat['message_content'], sanitize('file_name')) !== false) {

}
else{
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,10}(\/\S*)?/";

// Check if there is a url in the text
if (preg_match($reg_exUrl, $chat['message_content'], $url)) {

// make the urls hyper links
$chat['message_content'] = preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a>", $chat['message_content']);

} else {
// The Regular Expression filter
$reg_exUrl = "/(www)\.[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,10}(\/\S*)?/";

// Check if there is a url in the text
if (preg_match($reg_exUrl, $chat['message_content'], $url)) {

// make the urls hyper links
$chat['message_content'] = preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a>", $chat['message_content']);

}
}
}
$msgtime = timeAgo($chat['message_date']);    
$sn=get_fild_data('tbl_user',$_GET['client'],'name');
$items .= <<<EOD
{
"s": "0",
"sender": "{$chat['from_uname']}",
"fn": "{$sn}",
"f": "{$_GET['client']}",
"x": "{$chat['from_id']}",
"p": "{$picname}",
"p2": "{$picname2}",
"st": "{$status}",
"page": "{$_SESSION['chatpage']}",
"pages": "{$pages}",
"u": "{$u}",
"mtype": "{$chat['message_type']}",
"m": "{$chat['message_content']}",
"time": "{$msgtime}"
},
EOD;

}// End While Loop


if ($items != '') {
$items = substr($items, 0, -1);
}
	
header('Content-type: application/json');
?>
{
"items": [
<?php echo $items;?>
]
}

<?php
exit(0);
}

function chatHeartbeat() {
global $con;
$from = $_SESSION['uid'];
$from_id = $_SESSION['uid']; 
$sql = "SELECT * FROM tbl_messages WHERE (to_uname = '$from' AND recd = 0) order by message_id ASC";
$query = $con->query($sql);
$items = '';

$chatBoxes = array();

while ($chat = mysqli_fetch_array($query)) {

$to_id = get_userdata('id','',$chat['from_uname']);
$picname = get_userdata('picname','',$chat['from_uname']);
$status = get_userdata('online','',$chat['from_uname']);

$picname = ($picname == "")? "duser.jpg" : $picname;
$status  = ($status == "0")? "Offline" : "Online";

$picname2 = get_userdata('picname','',$from);

$picname2 = ($picname2 == "")? "duser.jpg" : $picname2;


if (!isset($_SESSION['openChatBoxes'][$chat['from_uname']]) && isset($_SESSION['chatHistory'][$chat['from_uname']])) {
$items = $_SESSION['chatHistory'][$chat['from_uname']];
}

$chat['message_content'] = sanitize($chat['message_content']);

if($chat['from_uname'] == $_SESSION['uid']){
$u = 1;
$sespic = $picname;
}else{
$u = 2;
$sespic = $picname2;
}

if (strpos($chat['message_content'], sanitize('file_name')) !== false) {

}else{
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,10}(\/\S*)?/";

// Check if there is a url in the text
if (preg_match($reg_exUrl, $chat['message_content'], $url)) {

// make the urls hyper links
$chat['message_content'] = preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a>", $chat['message_content']);

} else {
// The Regular Expression filter
$reg_exUrl = "/(www)\.[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,10}(\/\S*)?/";

// Check if there is a url in the text
if (preg_match($reg_exUrl, $chat['message_content'], $url)) {

// make the urls hyper links
$chat['message_content'] = preg_replace($reg_exUrl, "<a href='{$url[0]}'>{$url[0]}</a>", $chat['message_content']);

}
}
}
$msgtime = timeAgo($chat['message_date']);
$fn=get_userdata('name','',$chat['from_uname']);    
$items .= <<<EOD
					   {
"s": "0",
"f": "{$chat['from_uname']}",
"fn": "{$fn}",
"x": "{$chat['from_id']}",
"p": "{$picname}",
"p2": "{$picname2}",
"spic": "{$sespic}",
"st": "{$status}",
"u": "{$u}",
"mtype": "{$chat['message_type']}",
"m": "{$chat['message_content']}",
"time": "{$msgtime}"
},
EOD;

if (!isset($_SESSION['chatHistory'][$chat['from_uname']])) {
$_SESSION['chatHistory'][$chat['from_uname']] = '';
}

$_SESSION['chatHistory'][$chat['from_uname']] .= <<<EOD
{
"s": "0",
"f": "{$chat['from_uname']}",
"fn": "{$fn}",
"x": "{$chat['from_id']}",
"p": "{$picname}",
"p2": "{$picname2}",
"spic": "{$sespic}",
"st": "{$status}",
"u": "{$u}",
"mtype": "{$chat['message_type']}",
"m": "{$chat['message_content']}",
"time": "{$msgtime}"
},
EOD;

unset($_SESSION['tsChatBoxes'][$chat['from_uname']]);
$_SESSION['openChatBoxes'][$chat['from_uname']] = $chat['message_date'];
}

if (!empty($_SESSION['openChatBoxes'])){
foreach ($_SESSION['openChatBoxes'] as $chatbox => $time) {
if (!isset($_SESSION['tsChatBoxes'][$chatbox]))
{
$now = time()-strtotime($time);
$time = date('g:iA M dS', strtotime($time));
$message = "$time";
if ($now > 180)
{
$items .= <<<EOD
{
"s": "2",
"f": "$chatbox",
"fn": "$fn",
"x": "{$chat['from_id']}",
"p": "{$picname}",
"p2": "{$picname2}",
"spic": "{$sespic}",
"st": "{$status}",
"m": "{$message}",
"time": "{$msgtime}"
},
EOD;

if (!isset($_SESSION['chatHistory'][$chatbox])) {
$_SESSION['chatHistory'][$chatbox] = '';
}
$_SESSION['chatHistory'][$chatbox] .= <<<EOD
{
"s": "2",
"f": "$chatbox",
"fn": "$fn",
"x": "{$chat['from_id']}",
"p": "{$picname}",
"p2": "{$picname2}",
"spic": "{$sespic}",
"st": "{$status}",
"m": "{$message}"
},
EOD;
$_SESSION['tsChatBoxes'][$chatbox] = 1;
}
}
}
}

$sql = "UPDATE tbl_messages SET recd = 1 WHERE to_uname = '$from' and recd = 0";
$query = $con->query($sql);

update_lastactive($from_id);

if ($items != '') {
$items = substr($items, 0, -1);
}
header('Content-type: application/json');
?>
{
"items": [
<?php echo $items;?>
]
}

<?php
exit(0);
}

function sendChat() {
global $con;    
if(isset($_SESSION['uid'])){
$from = $_SESSION['uid'];
$from_id = $_SESSION['uid'];
$message = $_POST['message'];
$to = $_POST['to'];

$_SESSION['openChatBoxes'][$_POST['to']] = date('Y-m-d H:i:s', time());
$messagesan = sanitize($message);

if (!isset($_SESSION['chatHistory'][$_POST['to']])) {
$_SESSION['chatHistory'][$_POST['to']] = '';
}

$to_id = get_userdata('id','',$to);
$picname = get_userdata('picname','',$to);
$status = get_userdata('online','',$to);

$picname = ($picname == "")? "duser.jpg" : $picname;
$status  = ($status == "0")? "Offline" : "Online";

$picname2 = get_userdata('picname','',$from);

$picname2 = ($picname2 == "")? "duser.jpg" : $picname2;

$_SESSION['chatHistory'][$_POST['to']] .= <<<EOD
{
"s": "1",
"f": "{$to}",
"x": "{$to_id}",
"p": "{$picname}",
"p2": "{$picname2}",
"st": "{$status}",
"m": "{$messagesan}"
},
EOD;


unset($_SESSION['tsChatBoxes'][$_POST['to']]);
$timenow = date('Y-m-d H:i:s');
$sql = "INSERT INTO tbl_messages (from_uname,to_uname,from_id,to_id,message_content,message_type,message_date) values ('$from', '$to','$from_id','$to_id','$message','text','$timenow')";

$query = $con->query($sql);

echo "1";
}
else{
echo "0";
}
exit(0);
}

function typingStatus() {
$from = $_SESSION['uid'];
$to = $_POST['to'];
$to_id = $_POST['toid'];
$from_id = $_SESSION['uid'];
$typing = $_POST['typing'];

	
if (!isset($_SESSION['chatHistory'][$_POST['to']])) {
$_SESSION['chatHistory'][$_POST['to']] = '';
}

$_SESSION['chatHistory'][$_POST['to']] .= <<<EOD
					   {
"ty": "{$typing}"
},
EOD;


unset($_SESSION['tsChatBoxes'][$_POST['to']]);

echo "1";
exit(0);
}

function chatBoxSession($chatbox) {

$items = '';

if (isset($_SESSION['chatHistory'][$chatbox])) {
$items = $_SESSION['chatHistory'][$chatbox];
}
return $items;
}

function startChatSession() {
$items = '';
if (!empty($_SESSION['openChatBoxes'])) {
foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
$items .= chatBoxSession($chatbox);
}
}


if ($items != '') {
$items = substr($items, 0, -1);
}

header('Content-type: application/json');
?>
{
"username": "<?php echo $_SESSION['uid'];?>",
"items": [
<?php echo $items;?>
]
}

<?php
exit(0);
}

function closeChat() {

unset($_SESSION['openChatBoxes'][$_POST['chatbox']]);
	
echo "1";
exit(0);
}

function sanitize($text) {
$text = htmlspecialchars($text, ENT_QUOTES);
$text = str_replace("\n\r","\n",$text);
$text = str_replace("\r\n","\n",$text);
$text = str_replace("\n","<br>",$text);
return $text;
}
?>