<?php
require_once('../config/config.php');
require_once('../foo/functions.php');
session_start();

if(isset($_POST['submit']))
{

if ($_POST['msg_subject'] == ""){ redirect('messages.php?error=' . urlencode('Enter a subject for your messages'));}
elseif ($_POST['msg_cnt'] == ""){ redirect('messages.php?error=' . urlencode('Your message cannot be empty'));}
else{
$msg_subject = $_POST['msg_subject'];
$msg_cnt = $_POST['msg_cnt'];
$msg_sender = $_POST['msg_sender'];
$msg_rcvr = $_POST['msg_rcvr'];
$msg_read = $_POST['msg_read'];
$adm_read = $_POST['adm_read'];
$sender_name = $_POST['sender_name'];

dbconnect();
$sql = "SELECT * FROM `".USERS_TABLE_NAME."` WHERE user_name='{$_POST['msg_rcvr']}'";
$stmt = $pdo->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$to = $row['user_email'];

$stmt = $pdo->prepare('INSERT INTO '.MSGS_TABLE_NAME.' (msg_subject, msg_cnt, msg_sender, msg_rcvr, msg_date, msg_read, adm_read, sender_name) VALUES (:subject, :cnt, :sender, :rcvr, NOW(), :msgread, :admread, :name)');

$stmt->execute(array(':subject' => $msg_subject, ':cnt' => $msg_cnt, ':sender' => $msg_sender, ':rcvr' => $msg_rcvr, ':msgread' => $msg_read, ':admread' => $adm_read, ':name' => $sender_name));
if ($pdo->lastInsertId())
	

// Send EMAIL
	
//$email = get_email($_SESSION['user_acc']);
$message = "
<html>
<head>
<title>".WEB_NAME."</title>
</head>
<body>
<img src=".LOGO_URL." alt=".WEB_NAME."/><br><br>
<p>YOU HAVE A NEW MESSAGE IN YOUR ACCOUNT FROM YOUR ACCOUNT OFFICER,<br> 
PLEASE LOGIN TO READ YOUR MESSAGE<br><br></p>
<p><a href=".SIGN_OUT_URL.">READ MESSAGE</a></p>
</p><br><br><br>
===========
<p>".WEB_NAME."</p>
</body>
</html>
";


// Send the email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".WEB_NAME." <".WEB_EMAIL.">" . "\r\n";
$subject = "NEW MESSAGE ALERT";
mail($to,$subject,$message,$headers);


log_info($_SERVER['REMOTE_ADDR'], $_SESSION['admin_login'], $sender_name, 'Message Sent Successfully');
redirect('messages.php?msg=' . urlencode('Message Successfully Sent'));		
}
}

?>