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

// whh 2022.04.25  add the new form variables from index.html
// wgg 2022.06.21 update all varibles for new form

echo "using Informprocess.php <br>";

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

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

	/*	---------------------------------------------------------------------------
		: Busimess Email to get form
		--------------------------------------------------------------------------- */

$bizemail = "fritz@fritzherold.com";


/*	---------------------------------------------------------------------------
	: Register all form field variables here
	--------------------------------------------------------------------------- */
	$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"]));
	$companyrequest = strip_tags(trim($_POST["companyrequest"]));
	$daterequest = strip_tags(trim($_POST["daterequest"]));
	$stairtreadmaterial = strip_tags(trim($_POST["stairtreadmaterial"]));
	$stairriser = strip_tags(trim($_POST["stairriser"]));
	$totalstairtread = strip_tags(trim($_POST["totalstairtread"]));
	$totallanding = strip_tags(trim($_POST["totallanding"]));
	$carpremove = strip_tags(trim($_POST["carpremove"]));

	$walltear = strip_tags(trim($_POST["walltear"]));

	$stairwidth= strip_tags(trim($_POST["stairwidth"]));
	$stairdepth = strip_tags(trim($_POST["stairdepth"]));
	$railingmaterial = strip_tags(trim($_POST["railingmaterial"]));
	$railingprofile = strip_tags(trim($_POST["railingprofile"]));
	$nosinglength = strip_tags(trim($_POST["nosinglength"]));
	$cappinglength = strip_tags(trim($_POST["cappinglength"]));
	$trimlength = strip_tags(trim($_POST["trimlength"]));
	$rererail = strip_tags(trim($_POST["rererail"]));
	$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"]));
	$removehardwood = strip_tags(trim($_POST["removehardwood"]));
	$removetile = strip_tags(trim($_POST["removetile"]));
	$removecarpet = strip_tags(trim($_POST["removecarpet"]));
	$floormat = strip_tags(trim($_POST["floormat"]));

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

	$cablocalion = strip_tags(trim($_POST["cablocalion"]));
	$cabinetrylink = strip_tags(trim($_POST["cabinetrylink"]));
	$cabinetrylength = strip_tags(trim($_POST["cabinetrylength"]));
	$tilebacksplash = strip_tags(trim($_POST["tilebacksplash"]));
	$tilesize = strip_tags(trim($_POST["tilesize"]));
	$tilearea = strip_tags(trim($_POST["tilearea"]));
	$tilefirefeature = strip_tags(trim($_POST["tilefirefeature"]));

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

	$message = strip_tags(trim($_POST["message"]));
	$captcha = strip_tags(trim($_POST["captcha"]));

	//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'])) {
		$uploadfile3 = uniqid();
		$fileUploaded3 = $uploadfile3.$_FILES['uploadfile3']['name'];
		$attachment3 = 1;
	}

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

		//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["firstname"],
			$_POST["lastname"],
			$_POST["telephone"],
			$_POST["emailaddress"],
			$_POST["address"],
			$_POST["ageofhome"],
			$_POST["companyrequest"],
			$_POST["daterequest"],
			$_POST["stairtreadmaterial"],
			$_POST["stairriser"],
			$_POST["totalstairtread"],
			$_POST["totallanding"],
			$_POST["carpremove"],

			$_POST["walltear"],

			$_POST["stairwidth"],
			$_POST["stairdepth"],
			$_POST["railingmaterial"],
			$_POST["railingprofile"],
			$_POST["nosinglength"],
			$_POST["cappinglength"],
			$_POST["trimlength"],
			$_POST["rererail"],
			$_POST["railinglength"],
			$_POST["numberposts"],
			$_POST["postsize"],
			$_POST["postfinishing"],
			$_POST["balustermat"],
			$_POST["balusterdirection"],
			$_POST["totalsqf"],
			$_POST["floordoors"],
			$_POST["removehardwood"],
			$_POST["removetile"],
			$_POST["removecarpet"],
			$_POST["floormat"],

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

			$_POST["cablocalion"],
			$_POST["cabinetrylink"],
			$_POST["cabinetrylength"],
			$_POST["tilebacksplash"],
			$_POST["tilesize"],
			$_POST["tilearea"],
			$_POST["tilefirefeature"],

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

			$_POST['message']

			// $_POST['captcha']

		);
	}

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

	$errors = array();

echo "send to bizemail: " . $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($)) {
			$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 . " - " . $firstname;

				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 = true;
			if($recipients == true){
				$recipients = array(
						$bizemail => "Business",
				);

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

echo "sending to receiver_email: " . $receiver_email . "<br>";
echo "sending to email + name " . $email . " - " . $name . "<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(


							"firstname",
							"lastname",
							"telephone",
							"emailaddress",
							"address",
							"ageofhome",
							"companyrequest",
							"daterequest",
							"stairtreadmaterial",
							"stairriser",
							"totalstairtread",
							"totallanding",
							"carpremove",

							"walltear",

							"stairwidth",
							"stairdepth",
							"railingmaterial",
							"railingprofile",
							"nosinglength",
							"cappinglength",
							"trimlength",
							"rererail",
							"railinglength",
							"numberposts",
							"postsize",
							"postfinishing",
							"balustermat",
							"balusterdirection",
							"totalsqf",
							"floordoors",
							"removehardwood",
							"removetile",
							"removecarpet",
							"floormat",

							"refinish",
							"refinishstair",

							"cablocalion",
							"cabinetrylink",
							"cabinetrylength",
							"tilebacksplash",
							"tilesize",
							"tilearea",
							"tilefirefeature",

							"date1",
							"date2",

							"message"

						);
						fputcsv($csvFileData,$headerRowFields);
						fputcsv($csvFileData, $csvData );
					}
					fclose($csvFileData);
				}

			/*	---------------------------------------------------------------------
				: Send the auto responder message if its true - set in seting.php
				--------------------------------------------------------------------- */
				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, $lastname);
					$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
	}
?>
