<?php

/*
* @package BANANA WARS
* @copyright: (c) 2017 G.P. aka Mvcshka (mvcshka@yandex.ru)
* @license: GNU General Public License version 2; see LICENSE.txt
* @files: /process/chat.php
*
*/

ob_start();
session_start();
header('Content-type: application/json');
Header("Content-Type: text/html;charset=UTF-8");
if($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) { exit();}
include($_SERVER['DOCUMENT_ROOT'].'/lib/connect.php');
include($_SERVER['DOCUMENT_ROOT'].'/lib/func.php');
include($_SERVER['DOCUMENT_ROOT'].'/lib/CofigFarm.php');

if(isset($_GET['action']))
{
	
	if($_GET['action'] == 'load')
	{
		$q = $mysql->query("SELECT * FROM db_chat LIMIT 200");
		if($q->rowCount() == 0)
		{
			echo json_encode($result = array('messege' => 'Нет сообщений'));
		}
		else
		{
			while($w = $q->fetch())
			{
				if($w['Login'] == $_SESSION['login'])
				{
					$b1 = '<b>';
					$b2 = '</b>';
				}
				for($i=1;$i<=100;$i++){
				  $w['Text'] = str_replace("smile:".$i.";","<img src=\"/images/smile/".$i.".gif\" border=\"0\">",$w['Text']);
				}
				 $find = array ( "'\[b\]'i", "'\[/b\]'i", "'\[i\]'i", "'\[/i\]'i", "'\[u\]'i", "'\[/u\]'i");

				$replace = array ( "<b>", "</b>", "<i>", "</i>", "<u>", "</u>");

				$w['Text'] = preg_replace( $find, $replace, $w['Text'] );
				if($w['Login'] != 'Robot')
				{
					if(GetUser("ModerChat", $_SESSION['id']) == 1 and GetUser("ChatBan", $_SESSION['id']) != 1)
					{
					
						$moder = '<a href="/chat?ban='.$w['Login'].'"><img src="/images/list-remove-user_8066.png" title="Забанить пользователя"></a> <a href="/chat?dell='.$w['Uid'].'" title="Удалить сообщение"><img src="/images/mail_delete_6130.png"></a>';
					}
				}
				else
				{
					$moder = '';
				}
				$msg .= '<div class="messege" id="mess'.$w['Uid'].'">
						<span class="time">'.date("H:i", $w['DateAdd']).'</span> 
						'.$moder.' <span class="login orange" onclick="treatment(\''.$w['Login'].'\')">'.$w['Login'].' </span>
						<span><span class="ssylka" onclick="treatment(\''.$w['To'].'\')">'.$w['To'].'</span>: '.$w['Text'].'</span>
						
					</div>';
			}
			$s = $mysql->query("SELECT * FROM db_chat");
			$_SESSION['CountMsg'] = $s->rowCount();
			echo json_encode($result = array('messege' => $msg, 'processing' => '<script type="text/javascript">  with (document.getElementById (\'messege\')) scrollTop = scrollHeight;</script>', "allmessege" => $s->rowCount()));
		}
	}
	elseif($_GET['action'] == 'send')
	{
		
		$msg = clean($_POST['messege']);
		if(GetUser("ChatBan", $_SESSION['id']) != 1)
		{
			
		
			if(mb_strlen($msg, 'UTF-8') < 3)
			{
				echo json_encode($result = array("messegeForm .button" => 'Отправить', "processing" => "<script type=\"text/javascript\"> $(\"#messege\").append('<div class=\"error left\">Слишком короткое сообщение!</div>'); with (document.getElementById ('messege')) scrollTop = scrollHeight; </script>"));
			}
			else
			{
			
				for($i=1;$i<=100;$i++){
						  $msgg = str_replace("smile:".$i.";","<img src=\"/images/smile/".$i.".gif\" border=\"0\">",$msg);
				}
				$ex = explode('[to]:', $msg);
				$aa = count($ex);
				if($aa >= 3) {
				
				$msg = str_replace( '[to]:'.$ex[1], '', $msg );
				$msg = str_replace( '[to]:', '', $msg );
				$to = $ex[1];
				} 
				else 
				{
					$msg = $msgg;
					$to = '';
				}
				$Reut = GetUser('Reuting', $_SESSION['id']);
				$LevelAcc = GetUser('Level', $_SESSION['id']);
				$e = $mysql->prepare("INSERT INTO db_chat SET Text = ?, UserId = ?, Login = ?, `To` = ?, DateAdd = ?");
				$e->execute(array($msg, $_SESSION['id'], $_SESSION['login'], $to, time()));
				//$mysql->query("UPDATE db_users SET ")
				$FullOpyt = $Lev[$LevelAcc];
				$rt = 10;
				ReutingUser($_SESSION['id'], $LevelAcc, $Reut, $FullOpyt, $rt);
				
				$Reut = GetUser('Reuting', $_SESSION['id']);
			$LevelAcc = GetUser('Level', $_SESSION['id']);
			
			if($LevelAcc < 12)
			{
				$FullOpyt = $Lev[$LevelAcc];
			}
			else
			{
				$FullOpyt = '&infin; max';
			}
			if($LevelAcc != 12)
			$width = 100 / $FullOpyt * $Reut;
			else $width = 100;
							
							
			echo json_encode($result = array("level" => "<a href=\"/levels\" title=\"Опыт\"><img src=\"/images/level.png\"/> <span class=\"title\">".$LevelAcc."</span> <span id=\"led\"><span id=\"strip\" style=\"width:".$width."%;\"><span id=\"exp-one\">".$Reut."</span>/".$FullOpyt."</span></span></a>", "messegeForm .button" => 'Отправить', "processing" => '<script type="text/javascript"> $("#messege").append(\'<div class="messege"><span class="time" style="margin-right:5px;">'.date("H:i", time()).'</span><span class="login orange bold" style="margin-right:5px;">'.$_SESSION['login'].'</span><span>'.$msgg.'</span></div>\'); $("#allmessege").html(parseInt($("#allmessege").html())+1); $("#messegeForm input[name=messege]").val(""); with (document.getElementById (\'messege\')) scrollTop = scrollHeight;</script>'));
			}
		}
		else
		{
			echo json_encode($result = array("frm" => "<script type=\"text/javascript\"> $(\"div.frm\").remove(); <\/script>"));
		}
	}
	elseif($_GET['action'] == 'refresh')
	{
		$co = intval($_GET['allmessege']);
		
		$q = $mysql->query("SELECT * FROM db_chat");
		if($q->rowCount() > 0){
			$msg = '';
		while($w = $q->fetch())
			{
				if($w['Login'] == $_SESSION['login'])
				{
					$b1 = '<b>';
					$b2 = '</b>';
				}
				for($i=1;$i<=100;$i++){
				  $w['Text'] = str_replace("smile:".$i.";","<img src=\"/images/smile/".$i.".gif\" border=\"0\">",$w['Text']);
				}
				
				 //$find = array ( "'\[b\]'i", "'\[/b\]'i", "'\[i\]'i", "'\[/i\]'i", "'\[u\]'i", "'\[/u\]'i");

				//$replace = array ( "<b>", "</b>", "<i>", "</i>", "<u>", "</u>");

				//$w['Text'] = preg_replace( $find, $replace, $w['Text'] );
				if($w['Login'] != 'Robot')
				{
					if(GetUser("ModerChat", $_SESSION['id']) == 1 and GetUser("ChatBan", $_SESSION['id']) != 1)
					{
					
						$moder = '<a href="/chat?ban='.$w['Login'].'"><img src="/images/list-remove-user_8066.png" title="Забанить пользователя"></a> <a href="/chat?dell='.$w['Uid'].'" title="Удалить сообщение"><img src="/images/mail_delete_6130.png"></a>';
					}
				}
				else
				{
					$moder = '';
				}
				
				$msg .= '<div class="messege" id="mess'.$w['Uid'].'"><span class="time">'.date("H:i", $w['DateAdd']).' </span> '.$moder.' <span class="login orange" onclick="treatment(\''.$w['Login'].'\')">'.$w['Login'].' </span><span><span class="ssylka" onclick="treatment(\''.$w['To'].'\')">'.$w['To'].'</span>: '.$w['Text'].'</span></div>';
			}
			
			
			$sq = $mysql->query("SELECT * FROM db_chat");
			$df = $mysql->query("SELECT * FROM db_chat ORDER BY Uid DESC LIMIT 1");
			$ff = $df->fetch();
			if($ff['UserId'] != $_SESSION['id'])
			{
				$music = "if($.cookie(\"volume\")!==\"off\") {var audiom = $(\"#audiom\")[0]; audiom.play();}";
			}
			else
			{
				$music = '';
			}
			if($co != $sq->rowCount()) 
			{$dd = "<script type=\"text/javascript\">".$music." process('','/process/chat.php?action=load','processing','messege','reload');</script>";}
			else {$dd = '';}
			echo json_encode($result = array('messege' => $msg, "processing" => $dd, "allmessege" => $_SESSION['CountMsg']));
		}
		else
		{
			echo json_encode($result = array('messege' => 'Нет сообщений'));
		}
	}
}
else
{
	echo json_encode($result = array('messege' => 'Ошибка!!!'));
}