<?php

function randomNumber($length) {
  $result = '';

  for($i = 0; $i < $length; $i++) {
      $result .= mt_rand(0, 9);
  }

  return $result;
}

try {
  error_reporting(E_ALL); ini_set('display_errors', 1);
  
  // force https, for web server when live (sikp if development server.
  if( $_SERVER['HTTP_HOST'] != 'localhost:8000' )
  {
    if($_SERVER["HTTPS"] != "on"){
        header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
        exit();
    }  
  }
  
  require_once "./pineapple.php";
  require_once "./mysql/helper.php";
  require_once "./twilio-php/Services/Twilio.php"; // Twilio.com php API
  pineapple_html_begin("Pineapple PNP", "Verify Phone");

  $db = db_connect("pontech_pineapplepnp");

  //print("<pre>\n");
  //print_r($_POST);
  //print_r($_SESSION);  // Warning, printing session vars could lead to security issues
  //print("</pre>\n");
	
	if(!isset($_SESSION['email']))
  {
		echo "<br>You must sign in to edit your referrals<br>";
    goto exit_page;
  }
  
  $email = $_SESSION['email'];
  
  // verify the customer has a cell phone number on record
  $sql = "SELECT email FROM pontech_pineapplepnp.user WHERE email='$email' AND phone_num Is Null";
  $result = $db->query($sql);
  $num_rows = $result->rowCount();
  if ($num_rows > 0) {
    ?>
    <p>Please add a phone number in the <a href="pineapple_user_settings.php">settings</a> page.</p>
    <?php
    goto exit_page;
  }
  
  // Non USA numbers cannot be verified
  $sql = "SELECT country_code FROM pontech_pineapplepnp.user WHERE email='$email'";
  $result = $db->query($sql);
  $country_code = $result->fetchColumn(0);
  if ($country_code != "+1"){
    ?>
    <p>Unfortunately we cannot validate phone numbers outside of the United States at the moment. We apologize for any inconvenience this may have caused.</p>
    <?php
    goto exit_page;
  }
  
  // cell phone has already been verified
  $sql = "SELECT phone_num_verified FROM pontech_pineapplepnp.user WHERE email='$email'";
  foreach ($db->query($sql) as $row){
    $verified = $row['phone_num_verified'];
  }
  if ($verified == 1){
    ?>
      <p>Your phone number has been verified.</p>
      <?php
      goto exit_page;
  }
  
  if(isset($_POST['call_me'])){
    // delete record of previous verification attemp
    $sql = "SELECT phone_num FROM pontech_pineapplepnp.user WHERE email='$email'";
    $result = $db->query($sql);
    $phone_num = $result->fetchColumn(0);
    $sql = "SELECT country_code FROM pontech_pineapplepnp.user WHERE email='$email'";
    $result = $db->query($sql);
    $country_code = $result->fetchColumn(0);
    $sql = "DELETE FROM phone_num_verify WHERE phone_num = ?";
    $sth = $db->prepare($sql);
    $sth->execute(array($phone_num));
    
    //generate verification_code
    $verification_code = randomNumber(5);
    $verification_code_msg = "";
    
    for( $i = 0; $i < strlen($verification_code); $i++ ){
      if($verification_code_msg == ""){
        $verification_code_msg = substr( $verification_code, $i, 1 );
      }
      else{
        $verification_code_msg = $verification_code_msg . ", " . substr( $verification_code, $i, 1 );
      }
    }
    
    // append record with random string
    $sql = "INSERT INTO phone_num_verify SET phone_num = ?, verification_code = ?";

    // execute sql statement
    $sth = $db->prepare($sql);
    $sth->execute(array($phone_num,$verification_code));
    
    // call customer
    if( $_SERVER['HTTP_HOST'] != 'localhost:8000' )
    {
      // Twilio Live Account
      $account_sid = 'AC68bfd174f7b80b767f9db92fd3618faa';
      $auth_token = '45bf4155f52a60397d726869bd5b091c';          
    }
    else
    {
      // Twilio Test Account 
      $account_sid = 'ACf083d7ff296771cbec32a9b8cfec2890';
      $auth_token = 'effabd6ec18f9f859020659851612f01';
    }
    
    $client = new Services_Twilio($account_sid, $auth_token);
    $from_phone = "+19094816672";  // pontech.com land line
    
    //Your account verification code for pineapple pick and place, is, 1, 2, 3, 4.  That number again is, 1, 2, 3, 4.
    $message = "Welcome to pineapple pick and place. Your verification code is, $verification_code_msg. That number again is, $verification_code_msg. Goodbye.";
    $data = array('say'=>$message);
    
    $url = "http://pineapplepnp.com/twilio_twiml.php?" . http_build_query($data);
    
    $call = $client->account->calls->create($from_phone, $country_code . $phone_num, $url, array( 
      'Method' => 'GET',  
      'FallbackMethod' => 'GET',  
      'StatusCallbackMethod' => 'GET',    
      'Record' => 'false', 
    ));
    
    ?>
    <p><form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="hidden" name="phone_num" value="<?php echo $phone_num; ?>"/>
    Confirmation Code: <input type="text" name="verification_code" SIZE="8"/>
    <input type="submit" value="Verify"/>
    <?php
    goto exit_page;
  }
  
  if(isset($_POST['verification_code'])){
    $sql = "SELECT verification_code FROM phone_num_verify WHERE phone_num = '$_POST[phone_num]'";
    $result = $db->query($sql);
    $stored_verification_code = $result->fetchColumn(0);
    
    if($stored_verification_code == $_POST['verification_code']){
      // set phone_num_verified equal to true
      $sql = "UPDATE user SET phone_num_verified='1' WHERE phone_num = '$_POST[phone_num]'";
      $result = $db->query($sql);
      
      // delete record from verification_code
      $sql = "DELETE FROM phone_num_verify WHERE phone_num = '$_POST[phone_num]'";
      $result = $db->query($sql);
      
      ?>
      <h3>Your phone number has been verified!</h3>
      <?php
    }
    else{
      ?>
      <h3>The entered verification code does not match. </h3>
      <p>Please click <a href="pineapple_verify_phone.php">here</a> to try again.</p>
      <?php
    }
    
    goto exit_page;
  }
  
  ?>
    <h3>You will receive a call with your confirmation code. Please be prepared to write it down.</h3>
    <p><form method="post" action="<?=$_SERVER['PHP_SELF']?>">
    <input type="hidden" name="call_me" value="Call Me"/>
    <input type="submit" value="Call Me"/>
  <?php
  
  $db = NULL;
  
exit_page:

	pineapple_script_end();
	pineapple_html_end();
}
catch (PDOException $e)
{
  print ("<br />$e");
}
?>