<?php
session_start();

include ("db.php");

if($_POST)
{	
	if(!isset($_POST['name']) || strlen($_POST['name'])<1)
	{
		//required variables are empty
		die('<div class="Msg-Error">Please let us know your name.</div>');
	}
	if(!isset($_POST['email']) || strlen($_POST['email'])<1)
	{
		//required variables are empty
		die('<div class="Msg-Error">Please let us know your email address.</div');
	}
	
	$email_address = $mysqli->escape_string($_POST['email']);
	
	if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
	
	} else {
  
		die('<div class="Msg-Error">Please provide us with a valid email address.</div');
	}
	
	if(!isset($_POST['subject']) || strlen($_POST['subject'])<1)
	{
		//required variables are empty
		die('<div class="Msg-Error">Subject cannot be blank.</div>');
	}
	if(!isset($_POST['message']) || strlen($_POST['message'])<1)
	{
		//required variables are empty
		die('<div class="Msg-Error">Message cannot be blank.</div>');
	}
	
	$rcode=$_REQUEST['code'];
	
	if($rcode != $_SESSION['rand_code']) {

		?>
	
	<script>
	d = new Date();
	$("#cap").attr("src", "captcha.php?"+d.getTime());
	$('#code').val('');
	</script> 
	
	<?php

		die('<div class="Msg-Error">Please enter the correct code.</div>');


	}

if($SettingsSql = $mysqli->query("SELECT * FROM settings WHERE id='1'")){

    $settings = mysqli_fetch_array($SettingsSql);

    $SettingsSql->close();
	
}else{
    
	 printf("Error: %s\n", $mysqli->error);
}	


$sitecontact = $settings['email'];
$fromname=isset($_POST['name'])?$_POST['name']:"";
$frommail=isset($_POST['email'])?$_POST['email']:"";
$fromsubject=isset($_POST['subject'])?$_POST['subject']:"";
$frommessage=isset($_POST['message'])?$_POST['message']:"";

require_once('include/class.phpmailer.php');

$mail             = new PHPMailer(); ;

$mail->AddReplyTo($frommail, $fromname);

$mail->SetFrom($frommail, $fromname);

$mail->AddReplyTo($frommail, $fromname);

$address = $settings['email'];
$mail->AddAddress($address, $sitecontact);

$mail->Subject = $fromsubject;

$mail->MsgHTML($frommessage);

if(!$mail->Send()) {?>
<div class="Msg-Error">Error sending mail</div>
<?php } else {?>
<div class="Msg-Ok">
<script>
$('#ContactUs').resetForm();
</script>
Message sent. We will contact you back as soon as possible.</div>

<?php }

}

?>