<?php
//error_reporting(E_ALL);
//ini_set('display_errors', True);

echo "Informprocess.php <br>";



	if (!isset($_SESSION)) session_start();
	if(!$_POST) exit;

	include dirname(__FILE__).'/settings/settings.php';
	include dirname(__FILE__).'/functions/emailValidation.php';

	/*	---------------------------------------------------------------------------
		: TEST VALUES
		---------------------------------------------------------------------------

		$firstname = "firstname";
		$lastname = "lastname";
		$telephone = "8885551212";
		$emailaddress = "email@address.com";
		$ageofhome = "ageofhome";

		$stairtreadmaterial = "stairtreadmaterial";
		$stairriser = "stairriser";
		$totalstairtread = "stotalstairtread";
		$totallanding = "totallanding";
		$stairwidth = "stairwidth";
		$stairriser = "stairriser";
		$stairdepth = "stairdepth";
		$railingmaterial = "railingmaterial";

		$railingprofile = "railingprofile";
		$railinglength = "railinglength";
		$numberposts = "numberposts";
		$postsize = "postsize";
		$postfinishing= "postfinishing";
		$balustermat = "balustermat";
		$balusterdirection = "balusterdirection";

		$totalsqf = "totalsqf";
		$floordoors = "floordoors";
		$floormat = "floormat";
		$removecarpet = "removecarpet";

		$refinish = "refinish";
		$refinishstair = "refinishstair";

		$message = "message";
		$captcha = "captcha";
		$date1 = "to";
		$date2 = "from";

		$uploadfile1 = uniqid();
		$fileUploaded1 = $uploadfile1.$_FILES['uploadfile1']['name']; */


/*	---------------------------------------------------------------------------
	: Register all form field variables here
	--------------------------------------------------------------------------- */
	$bizemail = strip_tags(trim($_POST["bizemail"]));

	$firstname = strip_tags(trim($_POST["firstname"]));
	$lastname = strip_tags(trim($_POST["lastname"]));
	$telephone = strip_tags(trim($_POST["telephone"]));
	$emailaddress = strip_tags(trim($_POST["emailaddress"]));
	$address = strip_tags(trim($_POST["address"]));
	$ageofhome = strip_tags(trim($_POST["ageofhome"]));

	$stairtreadmaterial = strip_tags(trim($_POST["stairtreadmaterial"]));
	$stairriser = strip_tags(trim($_POST["stairriser"]));
	$totalstairtread = strip_tags(trim($_POST["totalstairtread"]));
	$totallanding = strip_tags(trim($_POST["totallanding"]));
	$stairwidth= strip_tags(trim($_POST["stairwidth"]));
	$stairriser = strip_tags(trim($_POST["stairriser"]));
	$stairdepth = strip_tags(trim($_POST["stairdepth"]));
	$railingmaterial = strip_tags(trim($_POST["railingmaterial"]));

	$railingprofile = strip_tags(trim($_POST["railingprofile"]));
	$railinglength = strip_tags(trim($_POST["railinglength"]));
	$numberposts = strip_tags(trim($_POST["numberposts"]));
	$postsize = strip_tags(trim($_POST["postsize"]));
	$postfinishing= strip_tags(trim($_POST["postfinishing"]));
	$balustermat = strip_tags(trim($_POST["balustermat"]));
	$balusterdirection = strip_tags(trim($_POST["balusterdirection"]));

	$totalsqf = strip_tags(trim($_POST["totalsqf"]));
	$floordoors = strip_tags(trim($_POST["floordoors"]));
	$floormat = strip_tags(trim($_POST["floormat"]));
	$removecarpet = strip_tags(trim($_POST["removecarpet"]));

	$refinish = strip_tags(trim($_POST["refinish"]));
	$refinishstair = strip_tags(trim($_POST["refinishstair"]));

	$message = strip_tags(trim($_POST["message"]));
	$captcha = strip_tags(trim($_POST["captcha"]));
	$date1 = strip_tags(trim($_POST["to"]));
	$date2 = strip_tags(trim($_POST["from"]));

	//echo "date1 & date2: " . $date1 ." : " . $date2 . "<br>";


// loading and creating the filenames for attachments
// first test to see if there are attachments

$attachment1 = 0;		$attachment2 = 0;		$attachment3 = 0;		$attachment4 = 0;


	if(isset($_FILES['uploadfile1']['name'])) {
		$uploadfile1 = uniqid();
		$fileUploaded1 = $uploadfile1.$_FILES['uploadfile1']['name'];
		$attachment1 = 1;
	}

	if(isset($_FILES['uploadfile2']['name'])) {
		$uploadfile2 = uniqid();
		$fileUploaded2 = $uploadfile2.$_FILES['uploadfile2']['name'];
		$attachment2 = 1;
	}

	if(isset($_FILES['uploadfile3']['name'])) {
		$uploadfile13 = uniqid();
		$fileUploaded3 = $uploadfile3.$_FILES['uploadfile3']['name'];
		$attachment3 = 1;
	}

	if(isset($_FILES['uploadfile4']['name'])) {
		$uploadfile4 = uniqid();
		$fileUploaded4 = $uploadfile4.$_FILES['uploadfile4']['name'];
		$attachment4 = 1;
	}


/*
	$uploadfile1 = uniqid();
	$fileUploaded1 = $uploadfile1.$_FILES['uploadfile1']['name'];

	$uploadfile2 = uniqid();
	$fileUploaded2 = $uploadfile2.$_FILES['uploadfile2']['name'];

	$uploadfile3 = uniqid();
	$fileUploaded3 = $uploadfile3.$_FILES['uploadfile3']['name'];

	$uploadfile4 = uniqid();
	$fileUploaded4 = $uploadfile4.$_FILES['uploadfile4']['name'];
*/
		//echo "uploadfile1 " . 	$uploadfile1 ." : " . $fileUploaded1 . "<br>";
		//echo "uploadfile2 " . 	$uploadfile2 ." : " . $fileUploaded2 . "<br>";
		//echo "uploadfile3 " . 	$uploadfile3 ." : " . $fileUploaded3 . "<br>";
		//echo "uploadfile4 " . 	$uploadfile4 ." : " . $fileUploaded4 . "<br>";

/*	----------------------------------------------------------------------
	: Prepare form field variables for CSV export
	----------------------------------------------------------------------- */

	if($generateCSV == true){
		$csvFile = $csvFileName;
		$csvData = array(

			$_POST['bizemail'],

			$_POST['firstname'],
			$_POST['lastname'],
			$_POST['telephone'],
			$_POST['emailaddress'],
			$_POST['address'],
			$_POST["ageofhome"],

			$_POST["stairtreadmaterial"],
			$_POST["stairriser"],
			$_POST["totalstairtread"],
			$_POST["totallanding"],
			$_POST["stairwidth"],
			$_POST["stairriser"],
			$_POST["stairdepth"],
			$_POST["railingmaterial"],

			$_POST["railingprofile"],
			$_POST["railinglength"],
			$_POST["numberposts"],
			$_POST["postsize"],
			$_POST["postfinishing"],
			$_POST["balustermat"],
			$_POST["balusterdirection"],

			$_POST["totalsqf"],
			$_POST["floordoors"],
			$_POST["floormat"],
			$_POST["removecarpet"],

			$_POST["refinish"],
			$_POST["refinishstair"],

			$_POST['to'],
			$_POST['from']

		);
	}

/*	-------------------------------------------------------------------------
	: Prepare serverside validation
	------------------------------------------------------------------------- */

	$errors = array();

echo "BIZEMAIL 1: " . $bizemail ."<br>";
	/* check for business email empty use default email
	/* define the business email being used overrides setings.php */

	/* validate bizemail
	------------------------------------ */
	if(isset($_POST["bizemail"])){
		if (!$bizemail) {
			$$recipient = $bizemail;
			echo "recipients CHECK: " . $recipients ."<br>";
		} else if (!validEmail($bizemail)) {
			$errors[] = "Your must enter a valid email";
		}
	}

	/* validate firstname
	------------------------------------ */
	if(isset($_POST["firstname"])){
		if (!$firstname) {
			$errors[] = "You must enter your firstname";
		} elseif(strlen($firstname) < 2)  {
			$errors[] = "Firstname must be at least 2 characters";
		}
	}

	if(isset($_POST["lastname"])){
		if (!$firstname) {
			$errors[] = "You must enter your lastname";
		} elseif(strlen($firstname) < 2)  {
			$errors[] = "Firstname must be at least 2 characters";
		}
	}

	/* validate email address
	-------------------------------------- */
	if(isset($_POST["emailaddress"])){
		if (!$emailaddress) {
			$errors[] = "You must enter an email";
		} else if (!validEmail($emailaddress)) {
			$errors[] = "Your must enter a valid email";
		}
	}

	/* validate telephone number
	-------------------------------------- */
	if(isset($_POST["telephone"])){
		if (!$telephone) {
			$errors[] = "You must enter your telephone number";
		} elseif(!preg_match('/^[0-9]+$/', $telephone))  {
			$errors[] = "Please enter numbers only";
		} elseif(strlen($telephone) < 10)  {
			$errors[] = "Enter not less than 10 numbers";
		} elseif(strlen($telephone) > 12)  {
			$errors[] = "Enter not more than 12 numbers";
		}
	}

	/* validate service
	--------------------------------------
	if(isset($_POST["service"])){
		if (!$service) {
			$errors[] = "Please select a service";
		}
	} */

	/* validate budget
	--------------------------------------
	if(isset($_POST["budget"])){
		if (!$budget) {
			$errors[] = "Please select a budget";
		}
	} */

	/* validate fileuploads
	 * Maximum filesize set to 2MB
	 * File extensions supported doc, docx and pdf
	------------------------------------------------- */


	if(isset($_FILES['uploadfile1'])) {

		$max_filesize    =  31457280;     // 2097152; 2MB   31457280; 30MB
		$valid_file_extensions = array(".jpeg", ".jpg", ".png", ".pdf");
		$file_extension = strrchr($_FILES["uploadfile1"]["name"], ".");

		if (empty($_FILES['uploadfile1']['name'])) {
			$errors[] = "Browse to attach files";
		}

		if ($_FILES['uploadfile1']['size'] > $max_filesize) {
			$errors[] = "Uploaded files must not exceed 2MB";
		}

		if (!in_array($file_extension, $valid_file_extensions)) {
			$errors[] = "Please attach jpeg, jpg, png, pdf files only";
		}
	}

	if(isset($_FILES['uploadfile2'])) {

		$max_filesize    =  31457280;     // 2097152; 2MB   31457280; 30MB
		$valid_file_extensions = array(".jpeg", ".jpg", ".png", ".pdf");
		$file_extension = strrchr($_FILES["uploadfile2"]["name"], ".");

		if (empty($_FILES['uploadfile2']['name'])) {
			$errors[] = "Browse to attach files";
		}

		if ($_FILES['uploadfile2']['size'] > $max_filesize) {
			$errors[] = "Uploaded files must not exceed 2MB";
		}

		if (!in_array($file_extension, $valid_file_extensions)) {
			$errors[] = "Please attach jpeg, jpg, png, pdf files only";
		}
	}

	if(isset($_FILES['uploadfile3'])) {

		$max_filesize    =  31457280;     // 2097152; 2MB   31457280; 30MB
		$valid_file_extensions = array(".jpeg", ".jpg", ".png", ".pdf");
		$file_extension = strrchr($_FILES["uploadfile3"]["name"], ".");

		if (empty($_FILES['uploadfile3']['name'])) {
			$errors[] = "Browse to attach files";
		}

		if ($_FILES['uploadfile3']['size'] > $max_filesize) {
			$errors[] = "Uploaded files must not exceed 2MB";
		}

		if (!in_array($file_extension, $valid_file_extensions)) {
			$errors[] = "Please attach jpeg, jpg, png, pdf files only";
		}
	}

	if(isset($_FILES['uploadfile4'])) {

		$max_filesize    =  31457280;     // 2097152; 2MB   31457280; 30MB
		$valid_file_extensions = array(".jpeg", ".jpg", ".png", ".pdf");
		$file_extension = strrchr($_FILES["uploadfile4"]["name"], ".");

		if (empty($_FILES['uploadfile4']['name'])) {
			$errors[] = "Browse to attach files";
		}

		if ($_FILES['uploadfile4']['size'] > $max_filesize) {
			$errors[] = "Uploaded files must not exceed 2MB";
		}

		if (!in_array($file_extension, $valid_file_extensions)) {
			$errors[] = "Please attach jpeg, jpg, png, pdf files only";
		}
	}

	/* validate security captcha
	--------------------------------------- */
$captest = $_SESSION['gfm_captcha'];
//echo "captcha: " . $captcha . "<br>";
//echo "cap string form: " . $captest . "<br><br>";
	if(isset($_POST["captcha"])){
		if (!$captcha) {
			$errors[] = "You must enter the captcha code";
		} else if (($captcha) != $_SESSION['gfm_captcha']) {
			$errors[] = "Captcha code is incorrect";
		}
	}

	/* output all errors as a list
	-------------------------------------- */
	if ($errors) {
		$errortext = "";
		foreach ($errors as $error) {
			$errortext .= '<li>'. $error . "</li>";
		}
		echo '<div class="alert notification alert-error"><strong>The following errors occured:</strong><br><ul>'. $errortext .'</ul></div>';

	} else{

    	if ($_FILES['uploadfile1']['error'] == 0) {
				if ($attachment1 == 1 ) {
				move_uploaded_file($_FILES['uploadfile1']['tmp_name'], '../uploads/' .$fileUploaded1);  // this closes its bracket at the end
				};

				if ($attachment2 == 1 ) {
					if ($_FILES['uploadfile2']['error'] == 0) {
					move_uploaded_file($_FILES['uploadfile2']['tmp_name'], '../uploads/' .$fileUploaded2);
					};
				};

				if ($attachment3 == 1 ) {
					if ($_FILES['uploadfile3']['error'] == 0) {
					move_uploaded_file($_FILES['uploadfile3']['tmp_name'], '../uploads/' .$fileUploaded3);
					};
				};

				if ($attachment4 == 1 ) {
					if ($_FILES['uploadfile4']['error'] == 0) {
					move_uploaded_file($_FILES['uploadfile4']['tmp_name'], '../uploads/' .$fileUploaded4);
					};
				};

			include dirname(__FILE__).'/phpmailer/PHPMailerAutoload.php';
			include dirname(__FILE__).'/templates/goldenmessage.php';

			$mail = new PHPMailer();
			$mail->isSendmail();
			$mail->IsHTML(true);
			$mail->From = $emailaddress;
			$mail->CharSet = "UTF-8";
			$mail->FromName = $firstname;
			$mail->Encoding = "base64";
			$mail->Timeout = 200;
			$mail->ContentType = "text/html";
			$mail->addAddress($receiver_email, $receiver_name);
			$mail->Subject = $receiver_subject;

				if ($attachment1 == 1 ) {
					$mail->AddAttachment('../uploads/'.$fileUploaded1);
				};

				if ($attachment2 == 1 ) {
					$mail->AddAttachment('../uploads/'.$fileUploaded2);
				};

				if ($attachment3 == 1 ) {
					$mail->AddAttachment('../uploads/'.$fileUploaded3);
				};

				if ($attachment4 == 1 ) {
					$mail->AddAttachment('../uploads/'.$fileUploaded4);
				};

			$mail->Body = $goldmessage;
			$mail->AltBody = "Use an HTML compatible email client";

 //echo "Sending Message: <br>";
		/*	-------------------------------------------------------------------
			: Prepare sending to multiple  addresses / recepients if true
			------------------------------------------------------------------- */
			// If you want the form to be emailed to other addresses
			// Change the extra_recipients option below from (false) to (true)
			// Then enter email addresses with corresponding names seperated by comas
			// For example "john@example.com" => "John", "jack@example.com" => "Jack", "jeny@example.com" => "Jeny"
			// echo $goldmessage;
			// echo $automessage;
			$recipients = false;
			if($recipients == true){
				$recipients = array(
						"fritz@fritzherold.com" => "Fritz",
						"ma@modernartisan.ca" => "MA",
				);

				foreach($recipients as $email => $name){
					$mail->AddBCC($email, $name);
				}
			}

echo "<br>deliver to address: " . $recipients. "<br><br>";

			if($mail->Send()) {



			/*	-----------------------------------------------------------------
				: Generate the CSV file and post values if its true
				----------------------------------------------------------------- */
				if($generateCSV == true){
					if (file_exists($csvFile)) {
						$csvFileData = fopen($csvFile, 'a');
						fputcsv($csvFileData, $csvData );
					} else {
						$csvFileData = fopen($csvFile, 'a');
						$headerRowFields = array(
							"First Name",
							"Last Name",
							"Telephone",
							"Email",
							"Address",
							"ageofhome",

							"stairtreadmaterial",
							"stairriser",
							"stotalstairtread",
							"totallanding",
							"stairwidth",
							"stairriser",
							"stairdepth",
							"railingmaterial",

							"railingprofile",
							"railinglength",
							"numberposts",
							"postsize",
							"postfinishing",
							"balustermat",
							"balusterdirection",

							"totalsqf",
							"floordoors",
							"floormat",
							"removecarpet",

							"refinish",
							"refinishstair",

							"date1",
							"date2"
						);
						fputcsv($csvFileData,$headerRowFields);
						fputcsv($csvFileData, $csvData );
					}
					fclose($csvFileData);
				}

			/*	---------------------------------------------------------------------
				: Send the auto responder message if its true
				--------------------------------------------------------------------- */
				if($autoResponder == true){

					include dirname(__FILE__).'/templates/autoresponder.php';

					$automail = new PHPMailer();
					$automail->isSendmail();
					$automail->From = $receiver_email;
					$automail->FromName = $receiver_name;
					$automail->isHTML(true);
					$automail->CharSet = "UTF-8";
					$automail->Encoding = "base64";
					$automail->Timeout = 200;
					$automail->ContentType = "text/html";
					$automail->AddAddress($emailaddress, $firstname);
					$automail->Subject = "Thank you for contacting us";
					$automail->Body = $automessage;
					$automail->AltBody = "Use an HTML compatible email client";
					$automail->Send();
				}

				/* Automatically delete files from the server
				 * Delete files from the uploads folder after emailing
				 * If you want to keep files inside the folder just change
				 * The option $autoDeleteUploads = false;
				--------------------------------------------------------- */
				$autoDeleteUploads = false;
				if($autoDeleteUploads == true){
					$files = glob('../uploads/*');
					foreach($files as $file){
					  if(is_file($file))
						unlink($file);
					}
				}

				echo '<div class="alert notification alert-success">Message has been sent successfully!</div>';
			}
			else {
			  	echo '<div class="alert notification alert-error">Message not sent - an error occured!</div>';
			}
		} // close to loadfile attachment IF
	}
?>
