<?php
session_start();
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
header('Content-Type: application/json; charset=utf-8');


if(isset($_POST['user_id']))
{
require 'config.php';


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



$auth=check_input($_POST['auth']);
$user_id=check_input($_POST['user_id']);
$q=check_input($_POST['q']);


$auth = mysqli_escape_string($con, $auth);
$user_id=mysqli_escape_string($con, $user_id);
$q=mysqli_escape_string($con, $q);



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

$rows = mysqli_fetch_array($result);
$phone = $rows['phone'];
$email = $rows['email'];


$sqlx="SELECT * FROM users WHERE firstname LIKE  '%$q%'  AND user_id != '$user_id' OR lastname LIKE '%$q%'  AND user_id != '$user_id'  ORDER BY id DESC LIMIT 0, 50";
$resultx=$con->query($sqlx) or die ("error: Server error ".mysqli_error($con));

$countx=mysqli_num_rows($resultx);
if ($countx >= 1)
{

$data = array();

while($rows=mysqli_fetch_assoc($resultx))
   {
      
$user_idx = $rows['user_id'];


$sql2=$con->query("SELECT * FROM messages WHERE recipient_id='$user_id' AND sender_id = '$user_idx' OR recipient_id='$user_idx' AND sender_id = '$user_id'") or die("Error2 : ". mysqli_error($con));
$count2=mysqli_num_rows($sql2);
if ($count2 >= 1)
{
$row2 = mysqli_fetch_array($sql2);
$msg_id = $row2['msg_id'];
$msg_stat = "Exist";
}
else
{
$msg_stat = "New";
}
 
      
    $data[] = [ 
        'id' => $rows['id'],
        'user_id' => $rows['user_id'],
        'firstname' => $rows['firstname'],
        'lastname' => $rows['lastname'],
        'pro_pic' => $rows['pro_pic'],
        'msg_status' => $msg_stat, 
        'msg_id' => $msg_id
    ];
 
    
    
    $suc="Success";
 
   }
   if($data == null)
   {
      $suc="User not found";
       $data = ''; 
   }



}
else
{
  $suc="No Followers";
  $data = ''; 
    
}
}
}
$con->close();

header('Content-Type: application/json; charset=utf-8');
$output = array('success'=>$suc,  'data'=> $data);
echo json_encode($output); //output JSON data
//mysql_close($con);
?>

