<?php 
require('assets/customers_pdo.php'); //Sets up values for db.php   ### NOTE ENVIRONMENT VARIABLE HERE
header("X-XSS-Protection: 1; mode=block");

session_start();
$your_email ='b2b.receiver@gmail.com';// <<=== update to your email address
$host = 'https://2visit.me';
$errors = '';
$firstName = '';
$lastName = '';
$companyLegalName = '';
$tradingName = '';
$businessNumber = '';
$BPhone = '';
$BEmail = '';
$address1 = '';
$address2 = '';
$suburb = '';
$state = '';
$postCode = '';
$DEmail = '';
$numSites = '';
$location1 = '';
$location2 = '';
$welcomeMessage = '';
$regYYMM=date("ym",time());
$UID = bin2hex(random_bytes(16)); //Initial UID on form open. Will be passed to customers.customers on SUBMIT
$parentID = substr($UID, 0, 8);

// echo "Got $UID<br> and Parent is now $parentID";


// $RID=htmlentities($_REQUEST['ID']); 

if(isset($_REQUEST['package']) ){
  $package=htmlentities($_REQUEST['package']);
  $regEx='/[^[:digit:]]/';
  $numSites=preg_replace($regEx,'',$package);
}


if(isset($_REQUEST['OUID']) ){
//Client is returning from Confirm page
  $OLDUUID=htmlentities($_REQUEST['OUID']); //The referral ID from the signupConfirm page (correcting details).
	//Get the data they entered
	try {
		$sql_select_old="SELECT 
                firstName,
                lastName,
                companyLegalName,
                tradingName,
                businessNumber,
                BPhone,
                BEmail,
                address1,
                address2,
                suburb,
                state,
                postCode,
                DEmail,
                welcomeMessage,
                numSites,
                parentID
          FROM customers WHERE UID = ?";
		$sql_check_old = $pdo->prepare($sql_select_old);
		$sql_check_old->execute([$OLDUUID]);
		$result_old = $sql_check_old->fetch(PDO::FETCH_ASSOC);  
		// print_r($result_old);
	} //End Try check site code
	catch (PDOException $ex) {
		echo "<br>" . $ex->getMessage();
	} //close catch exception from try
	
	$firstName = $result_old["firstName"];
  $lastName = $result_old["lastName"];
  $companyLegalName = $result_old["companyLegalName"];
  $tradingName = $result_old["tradingName"];
  $businessNumber = $result_old["businessNumber"];
  $BPhone = $result_old["BPhone"];
  $BEmail = $result_old["BEmail"];
  $address1 = $result_old["address1"];
  $address2 = $result_old["address2"];
  $suburb = $result_old["suburb"];
  $state = $result_old["state"];
  $postCode = $result_old["postCode"];
  $DEmail = $result_old["DEmail"];
  $welcomeMessage = $result_old["welcomeMessage"];
  $numSites = $result_old["numSites"];
  $parentID = $result_old["parentID"];

	// Eliminate record
	try 
	{
		$sql_update = 'call removeUUID(?)';
		$stmt_update = $pdo->prepare($sql_update);
		$stmt_update->execute([$OLDUUID]);
	} 
		catch (PDOException $ex) 
		{
			echo "<br>" . $ex->getMessage();
		} //close catch exception from try

}


// // No ID sent through or ID=blank sent through
// if(!isset($_REQUEST['ID']) || empty($RID) ){
// 	echo "<p class=\"text-danger\" class=\"text-center\">No code provided. Redirecting...</p>";
// 	header( "refresh:2;url=https://$host/noSite.php");	
// 	exit();
// }


if(isset($_POST['submit']))
{
    // print_r($_POST);
    $firstName = htmlentities($_POST['firstName']);
    $lastName = htmlentities($_POST['lastName']);
    $companyLegalName = htmlentities($_POST['companyLegalName']);
    $tradingName = htmlentities($_POST['tradingName']);
    $businessNumber = htmlentities($_POST['businessNumber']);
    $BPhone = htmlentities($_POST['BPhone']);
    $BEmail = htmlentities($_POST['BEmail']);
    $address1 = htmlentities($_POST['address1']);
    $address2 = htmlentities($_POST['address2']);
    $suburb = htmlentities($_POST['suburb']);
    $state = htmlentities($_POST['state']);
    $postCode = htmlentities($_POST['postCode']);
    $DEmail = htmlentities($_POST['DEmail']);
    $location1 = htmlentities($_POST['companyLegalName']); 
    $location2 = htmlentities($_POST['tradingName']); 
    $numSites = htmlentities($_POST['numSites']);
    $welcomeMessage = htmlentities($_POST['welcomeMessage']); //This needs to be added below. Restrict # characters.
    $UID = htmlentities($_POST['UID']);
    $parentID = $_POST['parentID'];
    echo("\nPosting parent ID $parentID\n");

    ///------------Do Validations-------------
	if(empty($companyLegalName) || empty($BEmail))
	{
		$errors .= "\n Legal Business Name, Business Number (e.g businessNumber/GST Reg#) and Business email are required fields. ";	
    }
    
	if(IsInjected($BEmail))
	{
		$errors .= "\n Bad Business email value!";
    }
    if(IsInjected($DEmail))
	{
		$errors .= "\n Bad Delivery email value!";
	}
    if(empty($errors))
	{
        //Update customers table
		try {
			$cust_sql_insert = 
				'INSERT INTO 
				customers (
					          firstName,
                    lastName,
                    companyLegalName,
                    tradingName,
                    businessNumber,
                    BPhone,
                    BEmail,
                    address1,
                    address2,
                    suburb,
                    state,
                    postCode,
                    DEmail,
                    welcomeMessage,
                    UID,
                    numSites,
                    regDateYYMM,
                    parentID
					)
				VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
			$cust_stmt_insert = $pdo->prepare($cust_sql_insert);
			$cust_stmt_insert->execute(
        [       $firstName,
                $lastName,
                $companyLegalName,
                $tradingName,
                trim($businessNumber),
                $BPhone,
                $BEmail,
                $address1,
                $address2,
                $suburb,
                $state,
                $postCode,
                $DEmail,
                $welcomeMessage,
                $UID,
                $numSites,
                $regYYMM,
                $parentID
				]);
			} 
			catch (PDOException $cust_ex) {
				echo "<br>" . $cust_ex->getMessage();
			} //close catch exception from try
            

      //Tidy up the inserted data (remove null rows)
      try {
          $sql_storedProcedure = 
              'call updateCustomerCreationData()';
          $stmt_storedProcedure = $pdo->prepare($sql_storedProcedure);
          $stmt_storedProcedure->execute();
          } 
          catch (PDOException $storedProcedure_ex) {
              echo "<br>" . $storedProcedure_ex->getMessage();
          } //close catch exception from try
          //Close trigger stored procedure
                 
	

		// //send the email
		// $to = $your_email;
		// $subject="New form submission";
		// $from = $your_email;
		// $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
		
		// $body = "A user  $name submitted the contact form:\n".
		// "Name: $name\n".
		// "Email: $visitor_email \n".
		// "Phone: \n ".
		// "$visitor_phone\n".
		// "IP: $ip\n";	
		
		// $headers = "From: $from \r\n";
		// $headers .= "Reply-To: $visitor_email \r\n";
		
		// mail($to, $subject, $body,$headers);
		
		
		// header("Location: complete.php);
  } //Close post to customers.customers table
 
 
  header("Location: $host/signupConfirm4.php?UID=$UID");


} //Close ISSET check for POST to SELF

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  } //Close return true IsInjected test
  else
    {
    return false;
  } //Close return false IsInjected test
} //Close IsInjected test
print_r($errors); //Debug
?>
<!DOCTYPE html>
<html>
  <head>
     <!-- Global site tag (gtag.js) - Google Analytics -->
     <script async src="https://www.googletagmanager.com/gtag/js?id=UA-177363055-1"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'UA-177363055-1');
    </script>
    <meta charset="UTF-8">
    <link href='https://fonts.googleapis.com/css?family=Titillium+Web:400,300,600' rel='stylesheet' type='text/css'>
    <link href="assets/screen.css" media="screen, projection" rel="stylesheet" type="text/css" />
    <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>

    
  </head>
  <body>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.14.0/css/all.css">
  <div class="form" method="POST" name="signUpForm">
      
    <ul class="tab-group">
        <!-- <li class="tab"><a href="#form" <?php echo !empty($OLDUUID) ? 'id="defaultOpen"' : ''?>>Sign-up <br>Form</a></li>
        <li class="tab active"><a href="#help" <?php echo empty($OLDUUID) ? 'id="defaultOpen"' : ''?> >Form<br>Help</a></li>   -->
        <li class="tab"><a href="#form" id="defaultOpen">Sign-up <br>Form</a></li>
        <li class="tab active"><a href="#help" >Form<br>Help</a></li>  
    </ul>
      
  <div class="tab-content">

    <div class="tab-content" id="help" style="display:block">   
        <h1>How to complete:</h1>
        <h1><i class="fas fa-asterisk"></i>Fields marked with * are mandatory</h1>
        <h1><i class="far fa-registered"></i>Trading name will be used in preference to your legal name on the customer sign-in form. If left blank, legal business name will be used.</h1>          
        <h1><i class="fas fa-at"></i> Delivery email address can be used as an alternative to receive the daily update file containing your visitor records.</h1>
        <h1><i class="fas fa-location-arrow"></i> You will be able to enter up to 20 locations on the confirmation page.</h1>
        <h1><i class="fas fa-file-excel"></i> Large and Enterprise customers will be sent an Excel/CSV file to complete and return to our Support team. <i class="fas fa-file-csv"></i></h1>
        <h1><i class="fas fa-hand-sparkles"></i> You can enter a custom welcome message. Visitors will be greeted by '&lt;Trading Name&gt; &lt;welcome message&gt;'</h1>
        <h1><i class="fas fa-hand-sparkles"></i> e.g 'Acme welcomes you', or</h1>
        <h1><i class="fas fa-exclamation-triangle"></i> HR: All visitors must sign-in</h1>

        <h1><i class="fas fa-dollar-sign"></i>All currency amounts are in Australian Dollars, and do not include GST unless stated.</h1>

    </div>
    <div id="form">
        <form method="POST" name="signUpForm" 
	            action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"> 
          <h1>Complete the detials below and confirm the number of sites you need.</h1>
          <h1>Best package will be selected based on the number of requested Sites.</h1>
          <h1>You can confirm the details in the next screen.</h1>
          
          <form action="/" method="post">
          
          <div class="top-row">
          
            <div class="field-wrap">
              <label>
                <?php echo !empty($firstName) ? '' : '<i class="fas fa-user"></i>First Name: <span class="req">*</span>'?>  
              </label>
              <input name="firstName" type="text" required autocomplete="off" value="<?php echo !empty($firstName) ? $firstName : ''?>"/>
            </div>
        
            <div class="field-wrap">
              <label>
                <?php echo !empty($lastName) ? '' : '<i class="fas fa-user"></i>Last Name: <span class="req">*</span>'?>
              </label>
              <input name="lastName"type="text"required autocomplete="off" value="<?php echo !empty($lastName) ? $lastName : ''?>"/>
            </div>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($companyLegalName) ? '' : '<i class="fas fa-briefcase"></i>Legal Business Name (e.g. Acme Pty Ltd): <span class="req">*</span>'?>
            </label>
            <input name="companyLegalName" type="text"required autocomplete="on" value="<?php echo !empty($companyLegalName) ? $companyLegalName : ''?>"/>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($BEmail) ? '' : '<i class="fas fa-at"></i>Business Email Address: <span class="req">*</span>'?>
            </label>
            <input name="BEmail" type="email"required autocomplete="off" value="<?php echo !empty($BEmail) ? $BEmail : ''?>"/>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($DEmail) ? '' : '<i class="fas fa-at"></i>Delivery Address for daily registrant data:'?>
            </label>
            <input name="DEmail" type="email" autocomplete="on" value="<?php echo !empty($DEmail) ? $DEmail : ''?>"/>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($businessNumber) ? '' : '<i class="fas fa-hashtag"></i>BusinessNumber (ABN or ACN):'?>
            </label>
            <input name="businessNumber" type="text" autocomplete="on" value="<?php echo !empty($businessNumber) ? $businessNumber : ''?>"/>
          </div>
          
          <div class="field-wrap">
            <label>
              <?php echo !empty($tradingName) ? '' : '<i class="far fa-registered"></i>Trading Name (e.g. Acme): '?>
            </label>
            <input name="tradingName" type="text" autocomplete="on" value="<?php echo !empty($tradingName) ? $tradingName : ''?>"/>
          </div>
          

          <div class="field-wrap">
            <label><?php echo !empty($BPhone) ? '' : '<i class="fas fa-phone"></i>Phone Number:  <span class="req">*</span>'?>
              
            </label>
            <input name="BPhone" type="number" required autocomplete="on" value="<?php echo !empty($BPhone) ? $BPhone : ''?>"/>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($address1) ? '' : '<i class="fas fa-building"></i>Address1: <span class="req">*</span>'?>
            </label>
            <input name="address1" type="text" required autocomplete="off" value="<?php echo !empty($address1) ? $address1 : ''?>"/>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($address2) ? '' : '<i class="fas fa-building"></i>Address2:'?>
            </label>
            <input name="address2" type="text"  autocomplete="off" value="<?php echo !empty($address2) ? $address2 : ''?>"/>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($suburb) ? '' : '<i class="fas fa-building"></i>Suburb: <span class="req">*</span>'?>
            </label>
            <input name="suburb" type="text" required autocomplete="off" value="<?php echo !empty($suburb) ? $suburb : ''?>"/>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($state) ? '' : '<i class="fas fa-building"></i>State: <span class="req">*</span>'?>
            </label>
            <input name="state" type="text" required autocomplete="off" value="<?php echo !empty($state) ? $state : ''?>"/>
          </div>

          <div class="field-wrap">
            <label>
              <?php echo !empty($postCode) ? '' : '<i class="fas fa-building"></i>Post Code: <span class="req">*</span>'?>
            </label>
            <input name="postCode" type="text" required autocomplete="off" value="<?php echo !empty($postCode) ? $postCode : ''?>"/>
          </div>
          <?php if(empty($package)){
          echo("<div class=\"field-wrap\">
            <label>");
              echo(!empty($numSites) ? '' : '<i class="fas fa-hashtag"></i>Number of Sites: <span class="req">*</span>');
            echo("</label>
            <input name=\"numSites\" type=\"number\" required autocomplete=\"off\" value=\"");
            echo(!empty($numSites) ? $numSites : '');
            echo("\"/>
          </div>");
          } else {
            
            echo("<div class=\"field-wrap\">            
            <input name=\"numSites\" type=\"number\" required text=\"$numSites\" autocomplete=\"off\" value=\"$numSites\"/>
            <p><i class=\"fas fa-hashtag\"></i>Number of Sites: <span class=\"req\">*</span></p>");
          echo("</div>");
          }
          ?>
          <div class="field-wrap">
            <label>
              <?php echo !empty($welcomeMessage) ? '' : '<i class="fas fa-handshake"></i> Salutation: e.g. welcomes you to<span class="req">*</span>'?>
            </label>
            <input name="welcomeMessage" type="text" required autocomplete="on" value="<?php echo !empty($welcomeMessage) ? $welcomeMessage : ''?>"/>
          </div>
          <h2>Vistors will see:</h2>
          <h2><span style="color: red;">&lt;Trading Name&gt;</span><span style="color: white">&lt;salutation&gt;</span><span style="color: yellow">&lt;Site&gt;</span> e.g </h2>
          <h2><span style="color: red;">Acme </span><span style="color: white;">welcomes you to </span><span style="color: yellow;">Building 42</span></h2>
          <h2><i class="fas fa-user-shield"></i></i> By clicking NEXT, I agree that data collected via this service will only be used in accordance with privacy principles.</h2>
          <input type="hidden" id="UID" name="UID" value="<?php echo($UID) ?>">
          <input type="hidden" id="parentID" name="parentID" value="<?php echo($parentID)?>">
          <button type="submit" value="Submit" name='submit' class="button button-block">NEXT</button>
        </form>

    </div> <!--End Div Form-->
  </div><!-- tab-content -->
      
</div> <!-- /form -->
<script language="JavaScript" type="text/javascript" src="assets/codepenSignup.js"></script>
<script>document.getElementById("defaultOpen").click();</script>
  </body>


