<?php

require_once '../../../config.php';
require_once $configArr['engine_path'] . "/initEngine.php";

$PDO = PDO_CONNECT();

$active_chat = true;

if (isset($_SESSION['user']['user_id']) && $_SESSION['user']['user_id'] != '') {
	
    if (isset($_POST['currentRequestID']) && $_POST['currentRequestID'] != '') {
        $command = "UPDATE chat_requests SET a_status = :typing_status, in_chat = '1' WHERE request_id = :request_id AND end_date = '0000-00-00 00:00:00'";
        $result = $PDO->prepare($command);
        $result->bindParam(':request_id', $_POST['currentRequestID']);
        $result->bindParam(':typing_status', $_POST['status']);
        $result->execute();	
    }

    if (isset($_POST['operatorMsg']) && $_POST['operatorMsg'] != '') {
		
        if (!isset($_SESSION['answered_request_id'][$_POST['currentRequestID']])) { // request is answered. update db with operator info
            $command = "UPDATE chat_requests SET a_status = :typing_status, in_chat = '1' WHERE request_id = :request_id AND end_date = '0000-00-00 00:00:00'";
            $result = $PDO->prepare($command);
            $result->bindParam(':request_id', $_POST['currentRequestID']);
            $result->bindParam(':typing_status', $_POST['status']);
            $result->execute();
			$count = $result->rowCount();		
            $_SESSION['answered_request_id'][$_POST['currentRequestID']] = ''; // ensures query runs one time only	
        }
				
		$_POST['operatorMsg'] = htmlspecialchars_decode($_POST['operatorMsg']);
		$_POST['operatorMsg'] = strip_tags($_POST['operatorMsg'], '<img>');	
	    $text = stripslashes(htmlspecialchars($_POST['operatorMsg'], ENT_QUOTES, "utf-8"));
				
        $request_id = stripslashes(htmlspecialchars($_POST['currentRequestID'], ENT_QUOTES, "utf-8"));
		if ($active_chat == true){
	        $command = "INSERT IGNORE INTO chats VALUES('', :operator_id, :operator_name, :operator_avatar, :request_id, :content, '', UTC_TIMESTAMP())";
	        $result = $PDO->prepare($command);
	        $result->bindParam(':operator_id', $_SESSION['user']['user_id']);
	        $result->bindParam(':operator_name', $_SESSION['user']['username']);
	        $result->bindParam(':operator_avatar', $_SESSION['user']['avatar']);
	        $result->bindParam(':request_id', $request_id);
	        $result->bindParam(':content', $text);
	        $result->execute();
	        echo 'posted';
		}else{
			echo 'this chat has ended';
		}
        die();
    }

    if (isset($_POST['ban_user'])) {

        $user_id = stripslashes(htmlspecialchars($_POST['currentRequestID'], ENT_QUOTES, "utf-8"));
        $command = "INSERT IGNORE INTO visitors_banned VALUES('', '$user_id', UTC_TIMESTAMP())";
        $result = $PDO->prepare($command);
        $result->execute();
    }

    if (isset($_POST['status_on'])) {

        $command = "UPDATE admin_ready SET STATUS = 1 WHERE admin_id = '$admin_id'";
        $result = $PDO->prepare($command);
        $result->execute();
    }

    if (isset($_POST['status_off'])) {
        $command = "UPDATE admin_ready SET STATUS = 0 WHERE admin_id = '$admin_id'";
        $result = $PDO->prepare($command);
        $result->execute();
    }

    if (isset($_POST['request_id']) && isset($_POST['transfer']) && $_POST['transfer'] == 'request') {
        $command = "UPDATE chat_requests SET transfer_request = :from_to WHERE request_id = :request_id LIMIT 1";
        $result = $PDO->prepare($command);
        $result->bindParam(':from_to', $_POST['from_to']);
        $result->bindParam(':request_id', $_POST['request_id']);
        $result->execute();
        $count = $result->rowCount();
        if ($count == 1) {
            echo 'transfer request sent';
        } else {
            echo 'transfer chat request error';
        }
    }

    if (isset($_POST['request_id']) && isset($_POST['transfer']) && $_POST['transfer'] == 'true') {

        $text = '<transfer><i>Operator   ' . $_SESSION['user']['username'] . ' has joined the chat.</i></transfer>';
        $command = "INSERT IGNORE INTO chats VALUES('', :operator_id, :operator_name, :operator_avatar, :request_id, :content, '', UTC_TIMESTAMP())";
        $result = $PDO->prepare($command);
        $result->bindParam(':operator_id', $_SESSION['user']['user_id']);
        $result->bindParam(':operator_name', $_SESSION['user']['username']);
        $result->bindParam(':operator_avatar', $_SESSION['user']['username']);
        $result->bindParam(':request_id', $_POST['request_id']);
        $result->bindParam(':content', $text);
        $result->execute();
        $count = $result->rowCount();
        if ($count == 1) {
            $command = "UPDATE chat_requests SET transfer_request = '' WHERE request_id = :request_id LIMIT 1";
            $result = $PDO->prepare($command);
            $result->bindParam(':request_id', $_POST['request_id']);
            $result->execute();
            $success = $result->rowCount();
            if ($success == 1) {
                echo 'success';
            } else {
                echo 'transfer accept error';
            }
        } else {
            echo 'transfer accept error';
        };
    }
    if (isset($_POST['invite_user']) && $_POST['invite_user'] == 'true' && isset($_POST['user_id']) & $_POST['user_id'] != '') {
		
        $user_id = stripslashes(htmlspecialchars($_POST['user_id'], ENT_QUOTES, "utf-8"));
        $command = "SELECT * FROM visitors WHERE user_id = :user_id LIMIT 1";
        $result = $PDO->prepare($command);
        $result->bindParam(':user_id', $user_id);
        $result->execute();
		
		while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
		    $user = $row;
		}
				
		if (empty($user)){
			die();
		}
				
		// Create chat request
		
		$command = "INSERT IGNORE INTO chat_requests VALUES('', :user_id, 'Guest', '', '', :cookie_id, :os, :browser, :browser_lang, :mobile, :screen_size, :ip, :country_name, :country_code, :longitude, :latitude, UTC_TIMESTAMP(), '', '', '', '', '9' )";
		$result = $PDO->prepare($command);
		$result->bindParam(':user_id', $user['user_id']);
		$result->bindParam(':cookie_id', $user['cookie_id']);
		$result->bindParam(':os', $user['os']);
		$result->bindParam(':browser', $user['browser']);
		$result->bindParam(':browser_lang', $user['browser_lang']);
		$result->bindParam(':mobile', $user['mobile']);
		$result->bindParam(':screen_size', $user['screen_size']);
		$result->bindParam(':ip', $user['ip_address']);
		$result->bindParam(':country_name', $user['country_name']);
		$result->bindParam(':country_code', $user['country_code']);
		$result->bindParam(':longitude', $user['longitude']);
		$result->bindParam(':latitude', $user['latitude']);

		$result->execute();
		$id = $PDO->lastInsertId();
		
		if ($id == ''){
		    die();
		}
									
		$html = $user_id = stripslashes(htmlspecialchars($_POST['message'], ENT_QUOTES, "utf-8"));

		$command = "INSERT IGNORE INTO chats VALUES('', '1', 'Admin', '', $id, '$html', '', UTC_TIMESTAMP() )";
		$result = $PDO->prepare($command);
		$result->execute();
		
        $user_id = stripslashes(htmlspecialchars($_POST['user_id'], ENT_QUOTES, "utf-8"));
        $command = "UPDATE visitors SET status = '9' WHERE user_id = :user_id LIMIT 1";
        $result = $PDO->prepare($command);
        $result->bindParam(':user_id', $user_id);
        $result->execute();
        $count = $result->rowCount();
	

        if ($count == 1) {
            echo 'invite_sent';
			die();
        }
    }
    if (isset($_POST['terminate_chat']) && $_POST['terminate_chat'] == 'true' && isset($_POST['request_id']) & $_POST['request_id'] != '') {
        $html = '<terminate><i>Operator ' . $_SESSION['user']['username'] . ' has left the chat session.</i></terminate>';
				
        // check if chat was not already terminated by cron		
        $command = "SELECT * FROM `chats` WHERE request_id = :request_id AND content LIKE '%has left the chat session%'";
        $result = $PDO->prepare($command);
        $result->bindParam(':request_id', $_POST['request_id']);
        $result->execute();
        if ($result->rowCount() == 0) {
            $command = "INSERT IGNORE INTO chats VALUES('', :operator_id, '', '', :request_id, '$html' , '', UTC_TIMESTAMP() )";
            $result = $PDO->prepare($command);
            $result->bindParam(':operator_id', $_SESSION['user']['user_id']);
            $result->bindParam(':request_id', $_POST['request_id']);
            $result->execute();
        }
        $command = "UPDATE chat_requests SET end_date = UTC_TIMESTAMP(), u_status = '0', a_status = '0', in_chat = '0' WHERE request_id = :request_id";
        $result = $PDO->prepare($command);
        $result->bindParam(':request_id', $_POST['request_id']);
        $result->execute();
		// Change visitor status back to 1 to ensure invite is revoked in case it was initiated
        $command = "SELECT * FROM chat_requests WHERE request_id = :request_id";
        $result = $PDO->prepare($command);
        $result->bindParam(':request_id', $_POST['request_id']);
        $result->execute();
		
		while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
		    $data = $row;
		}
			
	    $command = "UPDATE visitors SET status = '1' WHERE cookie_id = :cookie_id AND ip_address = :ip_address LIMIT 1";
	    $result = $PDO->prepare($command);
	    $result->bindParam(':cookie_id', $data['cookie_id']);
	    $result->bindParam(':ip_address', $data['ip_address']);
	    $result->execute();
				
        echo 'terminated';
        exit;
    }

}

if (isset($_POST['action']) && $_POST['action'] == 'change_operator_status'){
		
	if ($_POST['target_status'] == 'Online'){
	    $_SESSION['user']['status'] = time();
	    $command="UPDATE `users` SET `status` = '".sql_quote($_SESSION['user']['status'])."' WHERE `user_id` = '".intval($_SESSION['user']['user_id'])."' LIMIT 1";
	    $result = $PDO->prepare($command);
	    $result->execute();
	    $_SESSION['user']['last_action'] = time();	
	}
	else{
	    $_SESSION['user']['status'] = time()-120;
	    $command="UPDATE `users` SET `status` = '".sql_quote($_SESSION['user']['status'])."' WHERE `user_id` = '".intval($_SESSION['user']['user_id'])."' LIMIT 1";
	    $result = $PDO->prepare($command);
	    $result->execute();
	}
	
	$_SESSION['user']['heartbeat'] = $_POST['target_status'];
	
}

die();