<?php
	session_start();
	error_reporting(0);
	
	$target = $_POST['target'];
	$userID = $_SESSION['marry_userID'];
	$userPW = $_SESSION['marry_userPW'];
	$dbp = "chatDB/";
	$filename = $dbp . $userID . ".txt";
	$target_file = $dbp . $target . ".txt";
	$message = $_POST['message'];
	
	date_default_timezone_set("Asia/Jakarta");
	$current = time();
	$date = date("Y-m-d H:i:s",$current);
	
	if(file_exists($target_file)) {
		if(empty($message) == false) {
			//read userfile
			$file = fopen($filename,"r");
				$readed = fread($file,filesize($filename));
				fclose($file);
			$rearray = explode("\r\n",$readed);
			
			//read target file
			$file1 = fopen($target_file,"r");
				$readed1 = fread($file1,filesize($target_file));
				fclose($file1);
			$rearray_target = explode("\r\n",$readed1);
			
			//do write and process
			
			$content =
				$date . " -- Sent to " . $target . ": " . $message . "\r\n" .
				$readed;
			
			$opn = fopen($filename,"w");
			$write = $content;
			fputs($opn,$write);
			fclose($opn);
			
			$content_target =
				$date . " -- " . $userID . ": " . $message . "\r\n" .
				$readed1;
			
			$opn1 = fopen($target_file,"w");
			$write1 = $content_target;
			fputs($opn1,$write1);
			fclose($opn1);
			
			echo "message sent succesfully!";
			
			header("Location: chat.php");
		}
		else {
			echo "Why trying to send empty message? you're soo weird and SUSS";
		}
	}
	else {
		echo "such target only in your mind, imagine you're chtting with. Target don't exist";
	}
?>

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