<?php

ob_start();
// Initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    // header("Location: http://stresstracker.org/Geocode.php");
    // exit;
    header("Location: ".$baseurl."Geocode.php");
    exit;
  }



// Define variables and initialize with empty values
  $username = $password = $ZipCode = $City = $State = "";
  $username_err = $password_err = "";

// Processing form data when form is submitted
  if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Check if username is empty
    if(empty(trim($_POST["username"]))){
      $username_err = "Please enter username.";
    } else{
      $username = trim($_POST["username"]);

    }

    // Check if password is empty
    if(empty(trim($_POST["password"]))){
      $password_err = "Please enter your password.";
    } else{
      $password = trim($_POST["password"]);

    }

    // Validate credentials
    if(empty($username_err) && empty($password_err)){

      // Prepare a select statement
      $sql = "SELECT id, username, password, zip_code, country, city, state, email_verified, prosess_step_status  FROM users WHERE username = ?";

      if($stmt = $mysqli->prepare($sql)){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("s", $param_username);

        // Set parameters
        $param_username = $username;

        // Attempt to execute the prepared statement
        if($stmt->execute()){
          // Store result
          $stmt->store_result();

          // Check if username exists, if yes then verify password
          if($stmt->num_rows == 1){ 
            // Bind result variables
            $stmt->bind_result($id, $username, $hashed_password, $ZipCode, $country, $City, $State, $Is_verified, $prosess_step_status);
            if($stmt->fetch()){
              if(password_verify($password, $hashed_password)){
                if($Is_verified == 'True'){
                // Password is correct, so start a new session
                session_start();

                // Store data in session variables
                $_SESSION["loggedin"] = true;
                $_SESSION["id"] = $id;
                $_SESSION["ZipCode"] = $ZipCode;
                $_SESSION["username"] = $username;

                $_SESSION["City"] = $City;
                $_SESSION["State"] = $State;
                $_SESSION['Country'] = $country;
                $_SESSION["homelat"] = $Homelat;
                $_SESSION["homelon"] = $Homelon;
                $_SESSION["prosess_step_status"] = $prosess_step_status;
                

                $sqlupdatelogstatus = "UPDATE users SET logged_in_out = 'Logged_In' WHERE username='$username'";
                $stmt = $mysqli->prepare($sqlupdatelogstatus);
                $stmt->execute();
                /*if($prosess_step_status==0)
                {
                  // Redirect user to welcome page
                header("Location: ".$baseurl."selectplan.php");
                }
                else
                {*/
                  // Redirect user to welcome page
                header("Location: ".$baseurl."Geocode.php");
                //}
                
                }else{
                $password_err = "You are not verified.";
              }
              

              } else{
                            // Display an error message if password is not valid
                $password_err = "The password you entered was not valid.";
              }
            }
          } else{
                    // Display an error message if username doesn't exist
            $username_err = "No account found with that username.";
          }
        } else{
          echo "Oops! Something went wrong. Please try again later.";
        }
            // Close statement
        $stmt->close();
      }
    }
    // Close connection
    $mysqli->close(); 
  }

  ob_end_flush();

  if (isset($_SESSION['success_msg_time']) && 
    (time() -   $_SESSION['success_msg_time'] > 2)) {
   // session_destroy();   
    session_unset($_SESSION["success_msg_time"]);  
    session_unset($_SESSION["success_msg"]);  
   }

  ?>


  <div class="st-index-right">
    <div class="st-login">
      <h2>LOGIN TO  <br> TRACK YOUR STRESS</h2>
      <p> NOT SIGNED UP? <a href="register.php">JOIN NOW</a></p>
      <?php
        if(isset($_SESSION['success_msg']) && $_SESSION['success_msg'] != ''){
            echo '<div class="alert alert-success">'.$_SESSION['success_msg'].'</div>';
          }
      ?>
      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" autocomplete="off">
        <div class="row">
          <div class="col-md-12">
            <div class="form-group  <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">              
              <input type="text" class="form-control" name="username" placeholder="USERNAME" value="<?php echo $username; ?>">
              <span class="help-block"><?php echo $username_err; ?></span>
            </div>
          </div>
          <div class="col-md-12">
            <div class="form-group  <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">              
              <input type="password" name="password" class="form-control" placeholder="PASSWORD">
              <span class="help-block"><?php echo $password_err; ?></span>
            </div>
          </div>
          <div class="col-md-12">
            <div class="form-group text-center">              
              <div class="forgot-link"><a id="forgotpassword" href="forgotpassword.php">FORGOT PASSWORD?</a></div>
            </div>
          </div>
          <div class="col-md-12">
            <div class="form-group text-center">              
              <input type="submit" class="btn btn-primary"  value="LOGIN"  class="btn btn-primary">
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>