<?php
session_start();

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");


if(isset($_POST['sender_id']) && isset($_POST['recipient_id']) && isset($_POST['msg_id']))
{
require 'config.php';


function check_input($par) {
  $par = trim($par);
  $par = stripslashes($par);
  $par = htmlspecialchars($par);
  return $par;
}



$msg_id=check_input($_POST['msg_id']);
$sender_id=check_input($_POST['sender_id']);
$recipient_id=check_input($_POST['recipient_id']);
$message=check_input($_POST['message']);



$msg_id = mysqli_escape_string($con, $msg_id);
$sender_id = mysqli_escape_string($con, $sender_id);
$recipient_id = mysqli_escape_string($con, $recipient_id);
$message=mysqli_escape_string($con, $message);




$auth=check_input($_POST['auth']);
$auth = mysqli_escape_string($con, $auth);



$sql="SELECT * FROM users WHERE user_id = '$sender_id' AND auth = '$auth'";
$result=$con->query($sql) or die ("error: Server error ".mysqli_error($con));
$count=mysqli_num_rows($result);

if ($count == 0)
{
        $suc = "User Does Not Exist"; 
         $status = false; 

}
else
{



$sql1="SELECT * FROM users WHERE  user_id='$sender_id'";
$result1=$con->query($sql1) or die ("error: Server error ".mysqli_error($con));
$count1=mysqli_num_rows($result1);

if($count1 == 1)
{

$rows = mysqli_fetch_array($result1);
$fname = $rows['firstname'];
$lname = $rows['lastname'];
$sender_id = $rows['user_id'];
$sender_name = $fname." ".$lname;
}


$sql2="SELECT * FROM users WHERE  user_id='$recipient_id'";
$result2=$con->query($sql2) or die ("error: Server error ".mysqli_error($con));
$count2=mysqli_num_rows($result2);

if($count2 == 1)
{
$rowsx = mysqli_fetch_array($result2);
$fname = $rowsx['firstname'];
$lname = $rowsx['lastname'];
$recipient_id = $rowsx['user_id'];
$recipient_name = $fname." ".$lname;

}


date_default_timezone_set("Africa/Lagos");

  $date_t = date("d-M-Y"); 
  $time_t = date("H:i"); 
  $date_t2 = date("d-m-Y");




  $sqlx=$con->query("INSERT INTO messages  (msg_id, sender, sender_id, recipient, recipient_id, message, date_t, time_t, date_t2, status) 
      VALUES ('$msg_id', '$sender_name', '$sender_id', '$recipient_name', '$recipient_id', '$message',  '$date_t', '$time_t', '$date_t2', 'New')") or die("Error: ".mysqli_error($con));
      

$suc = "Successful"; 
$status = true; 

}
}

$con->close();

$output = array('status' => $status, 'success'=>$suc, 'msg_id' => $msg_id, 'message' => $message, 'sender' => $sender_name, 'sender_id' => $sender_id, 'recipient' => $recipient_name, 'recipient_id' => $recipient_id);
echo json_encode($output); //output JSON data

?>
