<?php 
require_once 'config.php';
$error=false;
$errors=array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   $from_user=$_POST['from_user'];
   $to_user=$_POST['to_user'];
   $threads=mysqli_num_rows(mysqli_query($con,"SELECT * FROM chat_thread WHERE from_user='".$from_user."'OR to_user ='".$from_user."'"));
   
   if($threads<1){
  
	$createEmployee=mysqli_query($con,"INSERT INTO chat_thread (from_user,to_user,created_at,status) VALUES('".$from_user."','".$to_user."','".date('Y-m-d H:i:s')."',1)");
	 if($createEmployee){
	     	$errors['success']='Thread created Sucessfully';
	 }else{
	     $errors['success']='Somthing went wrong !!';
	 }
   }else{
	   $thread=mysqli_fetch_array(mysqli_query($con,"SELECT * FROM chat_thread WHERE from_user='".$from_user."'OR to_user ='".$from_user."'"));
	   $errors['success']='Already Thread between these two users !!';
	   $threads=array('id'=>$thread['id'],'from_user'=>$thread['from_user'],'to_user'=>$thread['to_user'],'created_at'=>$thread['created_at'],'status'=>$thread['status']);
	   $errors['thread']=$threads;
   }
 	 
	 	echo json_encode($errors);
}