 <?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';



$from = $_POST['from'];
$to = $_POST['to'];
$user_id = $_POST['user_id'];


$user_id=stripslashes($user_id);
$user_id=mysqli_escape_string($con, $user_id);

$to=stripslashes($to);
$to=mysqli_escape_string($con, $to);

$from=stripslashes($from);
$from=mysqli_escape_string($con, $from);

$to = date("d-m-Y", strtotime($to));
$from = date("d-m-Y", strtotime($from));


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



$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
{


$sql=$con->query("SELECT * FROM messages WHERE recipient_id='$user_id' AND date_t2 BETWEEN '$from' AND '$to' OR sender_id = '$user_id' AND date_t2 BETWEEN '$from' AND '$to' GROUP BY msg_id ORDER BY date_t DESC") or die("Error2 : ". mysqli_error($con));

$data = array();

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

 $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'],
        'message' => $rows['message'],
        'date_t' => $rows['date_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
}

?>
