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

include 'db/config.php';


$start = $_POST['start'];
$finish = $_POST['finish'];
$user_id=$_POST['user_id'];


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

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


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



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




$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 LIMIT $start, $finish") or die("Error2 : ". mysqli_error($con));

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



$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'],
        '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





/*session_start();

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include 'db/config.php';

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

$status = false;
$suc = "Invalid request";
$data = [];

$start   = check_input($_POST['start'] ?? 0);
$finish  = check_input($_POST['finish'] ?? 20);
$user_id = check_input($_POST['user_id'] ?? '');
$auth    = check_input($_POST['auth'] ?? '');

$start   = (int)$start;
$finish  = (int)$finish;
$user_id = mysqli_real_escape_string($con, $user_id);
$auth    = mysqli_real_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 {

    /*
      Get latest message per conversation without msg_id.
      Conversation is determined by the pair of users.
    */
 /*   $query = "
        SELECT m1.*
        FROM messages m1
        INNER JOIN (
            SELECT MAX(id) AS last_id
            FROM messages
            WHERE sender_id = '$user_id' OR recipient_id = '$user_id'
            GROUP BY
                LEAST(sender_id, recipient_id),
                GREATEST(sender_id, recipient_id)
        ) m2 ON m1.id = m2.last_id
        ORDER BY m1.id DESC
        LIMIT $start, $finish
    ";

    $sql = $con->query($query) or die("Error2 : " . mysqli_error($con));

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

        $data[] = [
            'id' => $rows['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'],
            'time_t' => $rows['time_t'],
            'status_text' => $rows['status']
        ];

        $status = true;
        $suc = "Success";
    }

    if (empty($data)) {
        $status = false;
        $suc = "No Messages";
        $data = '';
    }
}

$con->close();

$output = [
    'success' => $suc,
    'status' => $status,
    'data' => $data
];

echo json_encode($output);


*/


?>
