<?php // pineapple_fpwd.php 

  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 Forgot Password");
	
  //print "<pre>";
  //print_r($_SERVER);
  //print "</pre>";

  // Render form if post message has not been recieved yet
  if( !isset($_POST['email']) )
  {
    ?>
      <form method="post" action="<?=$_SERVER['PHP_SELF']?>">
        E-Mail Address: <input type="text" name="email"/><br />
        <input type="submit" value="Submit" onclick="sendemail()"/>
      </form>
    <?php
  }
  else
  {
    $randomstr = substr(md5(time()),0,6);
		$db = db_connect("pontech_pineapplepnp");
    
    // todo: This code exists in two places.  Ghetto (signup)
    $record = db_get_record($db, "select count(*) as count from user where email=?", array($_POST['email']));
    
    if( $record['count'] == '0')
    {
      ?>
      <h1>The entered email is not associated with an account.</h1>
      <p>Please click <a href="pineapple_signup.php">here</a> to register for instant
           access.</p>
      <?php
      goto php_exit;
    }
		
		$message = "Please click on the following link to reset your password
		http://pineapplepnp.com/pineapple_reset_password.php?id=$randomstr";

		mail($_POST['email'],"Reset Password", $message, "From:Pineapple PnP <support@pineapplepnp.com>");
		
		// delete record of previous recovery attemp
		$sql = "DELETE FROM password_recover WHERE email = ?";

		// execute sql statement
    $sth = $db->prepare($sql);
    $sth->execute(array($_POST['email']));
  
		// append record with random string
		$sql = "INSERT INTO password_recover SET email = ?, resetstr = ?";

		// execute sql statement
    $sth = $db->prepare($sql);
    $sth->execute(array($_POST['email'],$randomstr));
		?>
      <h1>A message has been sent to your email.</h1>
		<?php
  }
  
  php_exit:
  
	// This is the end of the HTML body, scripting starts after this.
	pineapple_script_end();
	// This is the end of the HTML file, scripting starts after this.
	pineapple_html_end();

?>