<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

include 'config.php';


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



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

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



$sql="SELECT * FROM users WHERE user_id = '$user_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
{




$data = array();
$sql=$con->query("SELECT * FROM messages WHERE recipient_id='$user_id' OR sender_id = '$user_id' GROUP BY msg_id ORDER BY id DESC") or die("Error2 : ". mysqli_error($con));

  while($rows=mysqli_fetch_assoc($sql))
   {



$recipient_id =  $rows['recipient_id'];
$sender_id =  $rows['sender_id'];

if($sender_id == $user_id)
{
$pro_pic= $p_url."/profiles/".$recipient_id.".png?time=".time();
}
else
{
$pro_pic= $p_url."/profiles/".$sender_id.".png?time=".time();
}


$msg_id =  $rows['msg_id'];
$sqlx=$con->query("SELECT * FROM messages WHERE  msg_id = '$msg_id'  ORDER BY id DESC") or die("Error2 : ". mysqli_error($con));
$rowx=mysqli_fetch_array($sqlx);
$msg = $rowx ['message'];

 $data[] = [ 
        'id' => $rows['id'],
        'message_id' => $rows['msg_id'],
        'recipient' => $rows['recipient'],
        'recipient_id' => $rows['recipient_id'],
        'sender' => $rows['sender'],
        'sender_id' => $rows['sender_id'],
        'pro_pic' => $pro_pic,
        'message' => $msg,
        'date_t' => $rows['date_t'],
        'time_t' => $rows['time_t'],
       
    ];
    $status = true;
    $suc = "Success";
 
   }
   if($data == null)
   {
        $status = false;
        $suc="No Messages";
        $data = ''; 
   }


}

$con->close();

$output = array('success'=>$suc, 'status' => $status, 'data'=> $data);
echo json_encode($output); //output JSON data



?>
