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

dbconnect();
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if ($_POST['firstname'] == "") { store_msg("Firstname required", "danger"); redirect(APPS);}
elseif ($_POST['surname'] == "") { store_msg("Surname required", "danger"); redirect(APPS);}
elseif ($_POST['gender'] == "") { store_msg("Select Gender", "danger"); redirect(APPS);}
elseif ($_POST['dob'] == "") { store_msg("Select date of birth", "danger"); redirect(APPS);}
elseif ($_POST['email'] == "") { store_msg("Email required", "danger"); redirect(APPS);}
elseif (email_exist($_POST['email'])) { store_msg("Email Address already exist", "danger"); redirect(APPS);}
elseif ($_POST['phone'] == "") { store_msg("Mobile number required", "danger"); redirect(APPS);}
elseif ($_POST['address'] == "") { store_msg("Address required", "danger"); redirect(APPS);}
elseif ($_POST['city'] == "") { store_msg("City required", "danger"); redirect(APPS);}
elseif ($_POST['state'] == "") { store_msg("State required", "danger"); redirect(APPS);}
elseif ($_POST['zip'] == "") { store_msg("Zip or Postal code required", "danger"); redirect(APPS);}
elseif ($_POST['country'] == "") { store_msg("Country required", "danger"); redirect(APPS);}
elseif ($_POST['identification'] == "") { store_msg("Select ID type", "danger"); redirect(APPS);}
elseif ($_POST['idno'] == "") { store_msg("ID number required", "danger"); redirect(APPS);}
elseif ($_POST['expiry'] == "") { store_msg("Select ID expiry date", "danger"); redirect(APPS);}
elseif (empty($_SESSION['captcha']) || strtolower(trim($_REQUEST['captcha'])) != $_SESSION['captcha']) { store_msg("Invalid Word Verification", "danger"); redirect(APPS);}
//elseif (!empty($_FILES['photo']['name']) && !valid_photo($_FILES['photo']['name'])) { store_msg("Invalid photo file format", "danger"); redirect(APPS);}
//elseif (!empty($_FILES['photo']['size']) && !valid_size($_FILES['photo']['size'])) { store_msg("Photo image size exceeded 2 MB", "danger"); redirect(APPS);}

else{
$sname = clean_data($_POST['surname']);
$fname = clean_data($_POST['firstname']);
$names = $fname.' '.$sname;
$gender = clean_data($_POST['gender']);
$dob = clean_data($_POST['dob']);
$email = clean_data($_POST['email']);
$phone = clean_data($_POST['phone']);
$address = clean_data($_POST['address']);
$city = clean_data($_POST['city']);
$state = clean_data($_POST['state']);
$zip = clean_data($_POST['zip']);
$country = clean_data($_POST['country']);
$idtype = clean_data($_POST['identification']);
$idno = clean_data($_POST['idno']);
$expiry = clean_data($_POST['expiry']);
$status = '0';
$now = date('d/m/Y H:m');

$stmt = $pdo->prepare('INSERT INTO '.USERS_TABLE_NAME.' (first_name, last_name, user_names, user_email, user_phone, user_gender, dob, user_add, user_city, user_state, postcode, country, id_type, id_number, id_expiry, user_status, user_registered) VALUES (:fname, :lname, :names, :email, :phone, :gender, :dob, :address, :city, :state, :postcode, :country, :idtype, :idno, :expiry, :status, NOW())');

$stmt->execute(array(':fname' => $fname, ':lname' => $sname, ':names' => $names, ':email' => $email, ':phone' => $phone, ':gender' => $gender, ':dob' => $dob, ':address' => $address, ':city' => $city, ':state' => $state, ':postcode' => $zip, ':country' => $country, ':idtype' => $idtype, ':idno' => $idno, ':expiry' => $expiry, ':status' => $status));

if ($pdo->lastInsertId()) {
// Send EMAIL
$message = "
<html>
<head>
<title>".WEB_NAME."</title>
</head>
<body>
<img src=".LOGO_URL." alt=".WEB_NAME."/><br><br>
<p>ONLINE APPLICATION SUBMITTED:<br><br>
FIRST NAME: ".$fname." <br>
SURNAME: ".$sname." <br>
EMAIL: ".$email." <br>
PHONE NUMBER: ".$phone." <br>
GENDER: ".$gender." <br>
DATE OF BIRTH: ".$dob." <br>
ADDRESS: ".$address." <br>
CITY: ".$city." <br>
STATE: ".$state." <br>
POST CODE: ".$zip." <br>
COUNTRY: ".$country." <br>
ID TYPE: ".$idtype." <br>
ID NUMBER: ".$idno." <br>
ID EXPIRY: ".$expiry." <br>
</p><br><br><br>
===========
Date Registered: ".$now." <br>
<p>".WEB_NAME."</p>
</body>
</html>
";


if (!empty($_FILES['photo']['tmp_name'])) {

// upload photo
$digits = rand(pow(10, 12-1), pow(10, 12)-1);
$photoid = time().$digits;
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
$tmp_name = $_FILES['photo']['tmp_name'];
$name = $_FILES['photo']['name'];
$size = $_FILES['photo']['size'];
$type = $_FILES['photo']['type'];
if(strlen($name))
{
//list($txt, $ext) = explode(".", $name);
$ext = pathinfo($name, PATHINFO_EXTENSION);
//if(in_array($ext,$valid_formats))
//{ store_msg("Invalid photo file format", "danger"); redirect(APPS);}

$filename = stripslashes($_FILES['photo']['name']);
$extension = strtolower($ext);

//if($size > 2097152) // Image size max 2 MB
//{ store_msg("Photo image size exceeded 2 MB", "danger"); redirect(APPS);}

define( 'DESIRED_IMAGE_WIDTH', 256 );
define( 'DESIRED_IMAGE_HEIGHT', 256 );

  $source_path = $_FILES[ 'photo' ][ 'tmp_name' ];

  list( $source_width, $source_height, $source_type ) = getimagesize( $source_path );

  switch ( $source_type )
  {
    case IMAGETYPE_GIF:
      $source_gdim = imagecreatefromgif( $source_path );
      break;

    case IMAGETYPE_JPEG:
      $source_gdim = imagecreatefromjpeg( $source_path );
      break;

    case IMAGETYPE_PNG:
      $source_gdim = imagecreatefrompng( $source_path );
      break;
  }

  $source_aspect_ratio = $source_width / $source_height;
  $desired_aspect_ratio = DESIRED_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT;

  if ( $source_aspect_ratio > $desired_aspect_ratio )
  {
    // Triggered when source image is wider
    $temp_height = DESIRED_IMAGE_HEIGHT;
    $temp_width = ( int ) ( DESIRED_IMAGE_HEIGHT * $source_aspect_ratio );
  }
  else
  {
    // Triggered otherwise (i.e. source image is similar or taller)
    $temp_width = DESIRED_IMAGE_WIDTH;
    $temp_height = ( int ) ( DESIRED_IMAGE_WIDTH / $source_aspect_ratio );
  }

  // Resize the image into a temporary GD image

  $temp_gdim = imagecreatetruecolor( $temp_width, $temp_height );
  imagecopyresampled($temp_gdim, $source_gdim, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height);

  // Copy cropped region from temporary image into the desired GD image

  $x0 = ( $temp_width - DESIRED_IMAGE_WIDTH ) / 2;
  $y0 = ( $temp_height - DESIRED_IMAGE_HEIGHT ) / 2;

  $desired_gdim = imagecreatetruecolor( DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT );
  imagecopy($desired_gdim, $temp_gdim, 0, 0, $x0, $y0, DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT);

$filename = "users/". $photoid .".".$ext;
$cphoto = "$photoid".".$ext";

imagejpeg($desired_gdim,$filename,100);

imagedestroy($source_gdim);
imagedestroy($desired_gdim);

}

// Attach Photo
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($tmp_name, "r");
$content = fread($handle, $size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("appxweb");

//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: ".WEB_NAME." <".WEB_EMAIL.">" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message));

//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $type; name=".$name."\r\n";
$body .="Content-Disposition: attachment; filename=".$name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;

$subject = "ONLINE APPLICATION SUBMITTED";
@mail(WEB_EMAIL,$subject,$body,$headers);


$sql = "UPDATE `".USERS_TABLE_NAME."` SET user_photo = '{$cphoto}' WHERE user_email = '{$email}' LIMIT 1";
$stmt = $pdo->query($sql);
}else{

// Send the email
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "Content-Transfer-Encoding: 7bit \n";
$headers .= "From: ".WEB_NAME." <".WEB_EMAIL.">" . "\r\n";
$subject = "ONLINE APPLICATION SUBMITTED";
mail(WEB_EMAIL,$subject,$message,$headers);

}

store_msg("Application Successfully Submitted! Your Account details will be emailed upon verification and creation. <a href=".HOME_URL.">Click here to continue</a>", "success");
redirect(APPS);
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title><?php echo WEB_TITLE ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimal-ui" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <!-- for ios 7 style, multi-resolution icon of 152x152 -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-barstyle" content="black-translucent">
  <link rel="apple-touch-icon" href="assets/images/favicon.png">
  <meta name="apple-mobile-web-app-title" content="<?php echo SMS_SENDER ?>">
  <!-- for Chrome on Android, multi-resolution icon of 196x196 -->
  <meta name="mobile-web-app-capable" content="yes">
  <link rel="shortcut icon" sizes="196x196" href="assets/images/favicon.png">
  
  <!-- style -->
  <link rel="stylesheet" href="assets/animate.css/animate.min.css" type="text/css" />
  <link rel="stylesheet" href="assets/glyphicons/glyphicons.css" type="text/css" />
  <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css" type="text/css" />
  <link rel="stylesheet" href="assets/material-design-icons/material-design-icons.css" type="text/css" />
  <link rel="stylesheet" href="assets/styles/intlTelInput.css" type="text/css" />
  <link rel="stylesheet" href="assets/styles/countrySelect.css" type="text/css" />

  <link rel="stylesheet" href="assets/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
  <!-- build:css assets/styles/app.min.css -->
  <link rel="stylesheet" href="assets/styles/app.css" type="text/css" />
  <!-- endbuild -->
  <link rel="stylesheet" href="assets/styles/font.css" type="text/css" />
  <?php echo $colors; ?>

</head>
<body>
  <div class="app" id="app">

<!-- ############ LAYOUT START-->
<div class="white h-v row-col">
  <div class="row-cell v-m animated fadeIn">
    <div class="m-b text-center">
      <img src="assets/images/logo.png" class="m-b">
      <?php if (!empty($_SESSION['msg_text'])) {
          $msg = create_alert($_SESSION['msg_text'], $_SESSION['msg_type']);
          echo $msg;
          clear_msg(); }
      ?>
      <h5 class="m-b-md">Please complete the form below to setup an account</h5>
    </div>
    <form id="Splsh" method="post" action="" enctype="multipart/form-data" ui-jp="parsley">
    <div class="p-x-lg">
        <div class="row">
          <div class="col-lg-10 offset-lg-1">
            <div class="row row-sm">
            <h6 class="_400 main text-center">PERSONAL INFORMATION</h6>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="text" name="firstname" class="md-input" data-parsley-error-message="Firstname is required" required>
                  <label>First Name</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="text" name="surname" class="md-input" data-parsley-error-message="Surname is required" required>
                  <label>Surname</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group">
                  <select name="gender" class="md-input" data-parsley-error-message="Select Gender" required>
					<option value="">Select</option>
					<option value="Male">Male</option>
					<option value="Female">Female</option>
    			  </select>
                  <label>Select Gender</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                    <input type="text" name="dob" class="md-input" ui-jp="datetimepicker" ui-options="{
                        viewMode: 'years',
                        format: 'YYYY-MM-DD',
                        icons: {
                          time: 'fa fa-clock-o',
                          date: 'fa fa-calendar',
                          up: 'fa fa-chevron-up',
                          down: 'fa fa-chevron-down',
                          previous: 'fa fa-chevron-left',
                          next: 'fa fa-chevron-right',
                          today: 'fa fa-screenshot',
                          clear: 'fa fa-trash',
                          close: 'fa fa-remove'
                        }
                      }"  data-parsley-error-message="Date of birth is required"  required>
                	<label>Date of Birth</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="email" name="email" class="md-input" data-parsley-error-message="Email Address is required" required>
                  <label>Email Address</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group">
                  <input type="tel" id="phone" name="phone" class="md-input" placeholder="Mobile Number" data-parsley-error-message="Mobile Number is required" required>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="text" name="address" class="md-input" data-parsley-error-message="Address is required" required>
                  <label>Address</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="text" name="city" class="md-input" data-parsley-error-message="City is required" required>
                  <label>City</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="text" name="state" class="md-input" data-parsley-error-message="State is required" required>
                  <label>State</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="text" name="zip" class="md-input" data-parsley-error-message="Zip/Post Code is required" required>
                  <label>Zip/Post Code</label>
                </div>
              </div>
              <div class="col-sm-12">
                <div class="md-form-group">
                  <input type="tel" id="country" name="country" class="md-input" placeholder="Country" data-parsley-error-message="Country is required" required>
                </div>
              </div>
              <h6 class="_400 main text-center">PERSONAL IDENTIFICATION</h6>
              <div class="col-sm-12">
                <div class="md-form-group">
                  <select name="identification" class="md-input" data-parsley-error-message="Select ID type" required>
					<option value="">Select</option>
					<option value="Passport">International Passport</option>
					<option value="Driver's Licence">Driver's Licence</option>
					<option value="Social Security Number">Social Security Number</option>
    			  </select>
                  <label>Identification Type</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="text" name="idno" class="md-input" data-parsley-error-message="Identification Number is required" required>
                  <label>Identification Number</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                    <input type="text" name="expiry" class="md-input" ui-jp="datetimepicker" ui-options="{
                        viewMode: 'years',
                        format: 'YYYY-MM-DD',
                        icons: {
                          time: 'fa fa-clock-o',
                          date: 'fa fa-calendar',
                          up: 'fa fa-chevron-up',
                          down: 'fa fa-chevron-down',
                          previous: 'fa fa-chevron-left',
                          next: 'fa fa-chevron-right',
                          today: 'fa fa-screenshot',
                          clear: 'fa fa-trash',
                          close: 'fa fa-remove'
                        }
                      }"  data-parsley-error-message="Expiry Date is required"  required>
                	<label>Expiry Date</label>
                </div>
              </div>
              <h6 class="_400 main text-center">PASSPORT PHOTO</h6>
              <div class="col-sm-12">
                <div class="md-form-group">
                  <input type="file" name="photo" class="md-input">
                  <label>Upload your photo</label>
                </div>
              </div>
              <div class="col-sm-6">
                <img src="captcha.php" id="captcha" /><br><a href="#" onclick="document.getElementById('captcha').src='captcha.php?'+Math.random(); document.getElementById('captcha-form').focus();" id="change-image">Reload<i class="material-icons">&#xe863;</i></a>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="text" name="captcha" class="md-input" data-parsley-error-message="Word Verification is required" required>
                  <label>Word Verification</label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="form-group row m-t-lg m-b-lg">
          <div class="text-center">
            <button type="submit" class="btn rounded btn-outline main mainbd p-x-md">Submit Application</button>
          </div>
        </div>

    </div>
    </form>
  </div>
</div>

<!-- ############ LAYOUT END-->

  </div>
<!-- build:js scripts/app.html.js -->
<!-- jQuery -->
  <script src="libs/jquery/jquery/dist/jquery.js"></script>

  <script src="scripts/intlTelInput.js"></script>
    <script>
      $("#phone").intlTelInput({
        utilsScript: "scripts/utils.js"
      });
  </script>
  <script src="scripts/countrySelect.js"></script>
  <script>
    $("#country").countrySelect({
    //defaultCountry: "jp",
    //onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
    //preferredCountries: ['ca', 'gb', 'us']
    });
  </script>

<!-- Bootstrap -->
  <script src="libs/jquery/tether/dist/js/tether.min.js"></script>
  <script src="libs/jquery/bootstrap/dist/js/bootstrap.js"></script>
<!-- core -->
  <script src="libs/jquery/underscore/underscore-min.js"></script>
  <script src="libs/jquery/jQuery-Storage-API/jquery.storageapi.min.js"></script>
  <script src="libs/jquery/PACE/pace.min.js"></script>

  <script src="scripts/config.lazyload.js"></script>

  <script src="scripts/palette.js"></script>
  <script src="scripts/ui-load.js"></script>
  <script src="scripts/ui-jp.js"></script>
  <script src="scripts/ui-include.js"></script>
  <script src="scripts/ui-device.js"></script>
  <script src="scripts/ui-form.js"></script>
  <script src="scripts/ui-nav.js"></script>
  <script src="scripts/ui-screenfull.js"></script>
  <script src="scripts/ui-scroll-to.js"></script>
  <script src="scripts/ui-toggle-class.js"></script>

  <script src="scripts/app.js"></script>

  <!-- ajax -->
  <script src="libs/jquery/jquery-pjax/jquery.pjax.js"></script>
  <script src="scripts/ajax.js"></script>
<!-- endbuild -->
</body>
</html>
