<?php

include("../config.php");
session_start();

if(isset($_SESSION["user_login"])){
	$userid = $_SESSION["user_login"];
}else{
		header("location: ../register-login.php");
	}
	

		//get user info
		
		$stmt="SELECT * FROM users WHERE userid = :userid";
		$stmt=$pdo->prepare($stmt);
		$stmt->bindParam("userid", $userid, PDO::PARAM_STR);
		$stmt->execute();
		$row=$stmt->fetch();
		$userimage = (!empty($row["profilepix"]) ? "../img/users/".$row["profilepix"]: "../img/avatar.png");
		
	
		
		if(isset($_GET["user"])){
			$sender = intval($_GET["user"]);
		}else{
			header("location:dashboard.php");
		}


	
		//get all user messages with the $_GET id
	$stmt=$pdo->prepare("SELECT * FROM contact WHERE userid=:userid AND receiver=:receiver OR userid=:receiver AND receiver=:userid ORDER BY id ASC");
		$stmt->bindParam(":userid", $userid, PDO::PARAM_STR);
		$stmt->bindParam(":receiver", $sender, PDO::PARAM_STR);
		$stmt->execute();
		$messages=$stmt->fetchAll();
		$counMsg = $stmt->rowCount();
		
		
		
		
		//get user profile info
		$stmt=$pdo->prepare("SELECT * FROM users WHERE userid = :userid");
		$stmt->bindParam("userid", $sender, PDO::PARAM_STR);
		$stmt->execute();
		$senderInfo=$stmt->fetch();
		$senderImg = (!empty($senderInfo["profilepix"]) ? "../img/users/".$senderInfo["profilepix"]: "../img/avatar.png");
		
	
	
?>

<style>

.receiver{
	color:#444;
	font-size:16px;
	padding:10px;
	background:#ebffe9;
	border-radius:20px;
	margin-top:18px;
    margin-bottom: -10px;
	display:flex;
	line-height:1.6;
	color:#3c4d5c;
	border:1px solid #afc1ad;
	max-width:600px;
	word-wrap: anywhere;
}
.receiver-con{
	display: grid;
	margin-top:0px;
    place-content: flex-end;
}


.msg-con{
	height:450px;
	overflow:auto;
	border:1px solid #e1e1e1;
	padding:10px;
	background-image: radial-gradient(ellipse closest-side, rgba(225, 225, 225, 10%),#f7f7f7), 
	url(../img/chat.jpg); background-repeat:no-repeat; background-position:center; border-radius:10px;
}
.sender{
	font-size:16px;
	padding:10px;
	background:#f4f6f7;
	border-radius:20px;
	line-height:1.6;
	margin-top:15px;
	color:#3c4d5c;
	display:inline-block;
	border:1px solid #e1e1e1;
	max-width:600px;
	word-wrap: anywhere;
}
.sender-con{
	margin-top:0px;
	display: flex;
	flex-flow: wrap;
    place-content: flex-start;
}

.time1{
color: #808182;
font-size: 12px;
text-align: left;
margin: 6px 40px;
}

.time2{
	color:#808182;
	font-size:11px;
	text-align:right;
	margin-right: 6px;
}


.Service-body{
background:#fffaf5!important;
border-radius: 5px;
min-height: 70px;
}

.service{
	margin:20px 10px -10px;
	color:#11931f;
	font-size:18px;
	font-weight:500;
}


</style>


<!DOCTYPE html>

<html lang="en">

<head>

        <meta charset="utf-8" />

        <title><?php echo htmlspecialchars($senderInfo["fullName"]);?></title>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <meta content="A fully featured cryptocurrency investment platform" name="description" />

        <meta content="Coderthemes" name="author" />

        <meta http-equiv="X-UA-Compatible" content="IE=edge" />

      

            <link rel="stylesheet" type="text/css" href="w3.css">

        <!-- Bootstrap Css -->

        <link href="assets/css/bootstrap.min.css" id="bootstrap-stylesheet" rel="stylesheet" type="text/css" />

        <!-- Icons Css -->

        <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />

        <!-- App Css-->

        <link href="assets/css/app.min.css" id="app-stylesheet" rel="stylesheet" type="text/css" />

		<link href="../css/style7eda3860.css" rel="stylesheet">

    </head>



    <body>


	<div class='coversoverlay'>
	<center><img src="../img/loader.gif" style="width:60px; margin-top:20%;"></center>
	</div>

  <!-- Begin page -->
  <div id="wrapper" style="overflow:auto!important">

    
	
	
	
	
   <!-- Topbar Start -->
	<?php
	include("header.php");
	?>
    <!-- end Topbar -->
	
	
    <!-- ========== Left Sidebar Start ========== -->
    <div class="left-side-menu">

      <div class="slimscroll-menu">

        <!-- User box -->
        <div class="user-box text-center ">

          <div class="dropdown">
            <a href="#" class="user-name dropdown-toggle h5 mt-2 mb-1 d-block" data-toggle="dropdown" aria-expanded="false"></a>
            <div class="dropdown-menu user-pro-dropdown">




            </div>
          </div>


        </div>

        <!--- Sidemenu -->
        <?php include("sidebar.php");?>
		
        <!-- End Sidebar -->
        <div class="clearfix"></div>



                </div>

                <!-- Sidebar -left -->



            </div>

            <!-- Left Sidebar End -->






            <div class="content-page" style="padding:0px;">

                <div class="content" style="width: 100%;color: white;">



                    <!-- Start Content-->

                    <div class="container-fluid" >

                        <div id="google_translate_element"></div>

                         <div class="row">

                            <div class="col-md-12" style="padding-left:0px; padding-right:0px">
                            
						
						
				<div class="col-md-7" style="margin-top:20px!important;margin: auto;">
                <div class="card-box">
				
				
				
				
				
				<div class="msg-con">
				<br>
				<center>
				<img src="<?php echo $senderImg;?>" alt="User Avatar" class="img-size-50 mr-3" 
					style="width:70px; height:70px;border-radius:50%;border:2px solid #d3d6d7">
              <div class="media-body">
                
				<h4 class="dropdown-item-title" style="margin-left:-20px;">
                  <?php $namer = explode(" ",$senderInfo["fullName"]); echo $namer[0];?>
                </h4>
				</center>
				<br><div class="dropdown-divider"></div><br>
				
				
				<?php
				
				if($counMsg > 0){
				foreach($messages as $message){ 
				$chatImg = '../img/chats/'.$message["image"];
				?>
				
				
				<div class="<?php if($message["userid"]== $sender){echo "sender-con";}else{echo "receiver-con";}?>">
				
				<?php if($message["userid"]== $sender){
				echo '<img src="'.$senderImg.'" alt="User Avatar" style="width:30px;height:30px; margin:20px 5px 0px 1px; border-radius:50%;">';}?>
				
				<?php 
				//Service charges is set
				if(!empty($message["serviceTitle"])){echo '<div class="service">'. htmlspecialchars($message["serviceTitle"]).
				" | $".intval($message["amount"])."</div><br><p>";}?>
				
				<div class="<?php if($message["userid"]== $sender){echo "sender";}else{echo "receiver";}
				if(!empty($message["amount"])){echo " Service-body";}?>">
				<?php 
				if(!empty($message["message"])){echo htmlspecialchars($message["message"]);}
				if(!empty($message["image"])){echo '<a href="'.$chatImg.'">
				<img src="'.$chatImg.'" alt="Image" style="width:200px;border-radius:5px"></a>';}
				
				if($message["userid"]!= $sender && empty($message["image"])){echo "&nbsp; <div><i style='font-size:12px; float:right;margin-top:6px;' class='fa fa-check'></i></div>";}
				?>
				
				
				</div>
				<p><br>
				</div>
				<div class="<?php if($message["userid"]== $sender){echo 'time1';}else{echo 'time2';}?>">
				<?php echo date("jS F, Y", strtotime($message["received"]));?></div><br><p>
				<?php } } ?>
				
				<div id="here" class="receiver-con"></div>
				
				</div>
				
				
				
			<div class="form-group" style="margin:20px auto 20px auto">
			<textarea name="message" class="form-control" id="messages" style="height:100px;" placeholder="Enter your message"></textarea>
			
			
			<div class="input-group-append" style="margin-top:-10px;position:relative;z-index:5;">
			<label for="image" class="input-group-text" style="font-size:20px;cursor:pointer;border-radius:0px;margin-left:1px;">
			<input type='file' name='image' class='display-none' id='image' accept="image/*" />
			   <i class="fa fa-camera"></i></label>
               <button id="send" class="btnss btn btn-block" style="cursor:pointer;color:#fff;border-radius:0px;">Send</button>
               </div>
			</div>		
					
					
					
					
		<!--			
		<p><div class="dropdown-divider"></div>
		<img src="../img/blaze.png" width="30"> 
		<div style="margin:-20px 38px;"><a href="https://wa.me/qr/NJ6WYLM6NICXK1" style="color:#1e558c;">ChatBox by Gabson&nbsp; 
		<i class="fas fa-caret-right"></i></a></div>
		-->
		
		<br>	
					
					
					
					</div>
					</div>
					</div> <!-- container-fluid -->



                </div> <!-- content -->
                </div> 
              
					</div> 
	
					</div>
               


       

        <!-- Vendor js -->

        <script src="assets/js/vendor.min.js"></script>



        <!-- knob plugin -->

        <script src="assets/libs/jquery-knob/jquery.knob.min.js"></script>



        <!--Morris Chart-->

        <script src="assets/libs/morris-js/morris.min.js"></script>

        <script src="assets/libs/raphael/raphael.min.js"></script>



        <!-- Dashboard init js-->

        <script src="assets/js/pages/dashboard.init.js"></script>



        <!-- App js -->

        <script src="assets/js/app.min.js"></script>

   
   
   
   
   
   
   
   
   
   <script>
   
   $(document).ready(function(){
	
	$('.coversoverlay').hide();
		 
		
		 //srcoll top
			let div = $(".msg-con");
			div.scrollTop(div.prop('scrollHeight'));
		 
		 
		 
		 
		 
		 
 
 //send message
 
 $("#send").click(function(){
	 
		let messages = $("#messages").val();
		let receiver = <?php echo $sender;?>;
		
		if(messages == ""){
			$("#messages").focus();
			$("#messages").selectionEnd= end +7;
			
			return false;
			
		}else{
		
		$.ajax({
			url:'../processChat.php',
			method:'POST',
			data:{messages:messages, receiver:receiver},
			success:function(data){
				$("#here").append(data);
				
				
			//srcoll top
			let div = $(".msg-con");
			div.scrollTop(div.prop('scrollHeight'));
		 
		 
				
			}
		});
		
		}
		
		});
	
 
 
 
 
 
 
 
 
 
 
 
 
 
 //Upload picture

 $('#image').change(function(){
  var form_data = new FormData();
  var files = $('#image')[0].files;


   for(var i=0; i<files.length; i++)
   {
    var name = document.getElementById("image").files[i].name;
    var ext = name.split('.').pop().toLowerCase();
    if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1) 
    {

	//Toast error
    Toast.fire({
       icon: 'error',
       title: 'Please select a valid image file'
	})
	
	return false;
    }
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("image").files[i]);
    var f = document.getElementById("image").files[i];
    var fsize = f.size||f.fileSize;
    if(fsize > 9194304) //9mb
    {
      
	//Toast error
    Toast.fire({
       icon: 'error',
       title: 'Image is too large. Allowed max size is 9MB'
	})
return false;
    }
    else
    {
     form_data.append("image[]", document.getElementById('image').files[i]);
    }
   }
  

	if(files.length > 0){
   $.ajax({
    url:"../processChat.php?receiver=<?php echo $sender;?>",
    method:"POST",
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    beforeSend:function(){$(".coversoverlay").show();},   
    success:function(data){
				
		//hide Loader
		$(".coversoverlay").hide();
		
		//Embed image
		$("#here").append(data);
		
		console.log(data);
		
			//srcoll the chat container
				$(".msg-con").scrollTop($('.msg-con')[0].scrollHeight); 
				
				
    }
   });
	}


 })
 
 
 
 
 
 
 
 
 
 //Update notification to read when clicked - button in header.php
	$(".getMsg").click(function(){
		
		let senderID = this.id
		
		$.ajax({
			url:'../processChat.php',
			method:'POST',
			data:{senderID:senderID},
			success:function(data){ }
		});
		
	});
 
 
 
 
	 
   });
   
   
   
   
   </script>
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
    </body>

</html>