include_once "../config.php";
include_once "dbopen.php";
include_once "../libs/smileysComposer.php";
header('Content-Type: application/json');
echo '{';
if (isset($_REQUEST['userid']) && isset($_REQUEST['gameid']) && isset($_REQUEST['message'])) {
    $userid = $_REQUEST['userid'];
    $gameid = $_REQUEST['gameid'];
    $message = htmlentities($_REQUEST['message'], ENT_QUOTES);
    $username = $_REQUEST['message'];
    if (!mysqli_query($con, "INSERT INTO chatting (send_id,text,room) VALUES ('{$userid}','{$message}','{$gameid}')")) {
        echo '"code" : 503,';
        echo '"status" : "Chat message not saved."';
    } else {
        echo '"code" : 200,';
        echo '"status" : "Chat saved successfully!",';
        echo '"messages" : [';
        echo '{';
        echo '  "dir" : "sent",';
        echo '  "text" : "' . insertsmiley($message) . '",';
        echo '  "username" : "me",';
        echo '  "time" : "' . date('h:i a', time()) . '"';
        echo '}';
        echo ']';
    }
} else {
    echo '"code" : 502,';
    echo '"status" : "Invalid Request. Please check the details."';
}
echo '}';
include_once "dbclose.php";
     $sql .= " and a.send_id <> {$userid} and a.Cstatus='N'";
 }
 $result = mysqli_query($con, $sql);
 if (mysqli_num_rows($result) > 0) {
     $updateIds = "";
     echo '"code" : 200,';
     echo '"status" : "New chat message available.",';
     echo '"messages" : [';
     $i = 0;
     while ($row = mysqli_fetch_assoc($result)) {
         if ($i > 0) {
             echo ",";
         }
         echo '{';
         echo '  "dir" : "' . ($row["send_id"] == $userid ? 'sent' : 'recieved') . '",';
         echo '  "text" : "' . insertsmiley($row["text"]) . '",';
         echo '  "username" : "' . ($row["send_id"] == $userid ? 'me' : $row["username"]) . '",';
         echo '  "time" : "' . $row["time"] . '"';
         echo '}';
         if ($i > 0) {
             $updateIds .= ",";
         }
         $updateIds .= $row["id"];
         $i++;
     }
     echo ']';
     mysqli_query($con, "update chatting set Cstatus='Y' where id in (" . $updateIds . ")");
 } else {
     echo '"code" : 201,';
     echo '"status" : "No new chat message."';
 }