<?php // pineapple_login.php

  // 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";		// this file has the menu, header and css code for the site
	require_once "./mysql/helper.php";	// this is general purpose mysql helper code, code work anywhere

	// This line renders the menu and header for the site
	pineapple_html_begin("Pineapple PNP", "Pineapple Login");

  print "<pre>";
  print_r($_POST);
  print "</pre>";
  
	if( isset($_POST['email']) )
		$email = $_POST['email'];
	elseif( isset($_SESSION['email']) )
		$email = $_SESSION['email'];
	
	if( isset($_POST['password']) )
		$password = $_POST['password'];
	elseif( isset($_SESSION['password']) )
		$password = $_SESSION['password'];

  // No attempt at login has occrued, present user with login page
	if(!isset($email)) {
		?>
      You must be logged in to use this service
		<?php
	}
  else
  {
    if( $_SESSION['admin'] == '0' ) {
		?>
      You must have admin rights to use this page.
		<?php
    }
    else{
      if( !isset($_POST['phone']) ){
        ?>
          <p><form method="post" action="<?=$_SERVER['PHP_SELF']?>">
            phone number: <input type="text" name="phone" size="8" /><br />
            Message: <input type="text" name="message" SIZE="8" /><br />
          <input type="submit" value="Send" />
          </form></p>
        <?php
      }
      else
      {
        $key = "07f04995-ff6c-466f-88e3-288122b0777e";    
        $secret = "ASzp7h4kyUKB5kFBSDmqFg=="; 
        $phone_number = $_POST['phone'];
        $user = "application\\" . $key . ":" . $secret;    
        $message = array("message"=>$_POST['message']);    
        $data = json_encode($message);    
        $ch = curl_init('https://messagingapi.sinch.com/v1/sms/' . $phone_number);    
        curl_setopt($ch, CURLOPT_POST, true);    
        curl_setopt($ch, CURLOPT_USERPWD,$user);    
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);    
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));    
        $result = curl_exec($ch);    
        if(curl_errno($ch)) {    
            echo 'Curl error: ' . curl_error($ch);    
        } else {    
            echo $result;    
        }   
        curl_close($ch);    
      }
    }
  }

exit_page:
  // This is the end of the HTML body, scripting starts after this.
  pineapple_script_end();
?>
  <script>
  </script>
<?php
	// This is the end of the HTML file, scripting starts after this.
  pineapple_html_end();

//$username = $result->fetchColumn(3);
?>