<?php
ob_start();
session_start();





/*
 * required files
 */
require_once ('./models/PHP-MySQLi-Database-Class/MysqliDb.php');
require_once("./models/config.php"); // connect with db and load site info
require_once("./models/functions.php"); // site functions





/*
 * page variables
 */
$page_name = 'Log In';
$page_name_single = '';





/*
 * if user is logged in redirect to dashboard
 */
if ((isset($_SESSION['sess_user_id']) || (trim(isset($_SESSION['sess_user_id'])) != ''))) {
  header("location: dashboard.php");  // is logged in
  exit();
} else { // not logged in
}





/*
 * process login form
 */
if (isset($_POST['login_submit'])) {

  /*
   * check for robot submission
   */
  $super_important_field = mysqli_real_escape_string($con, $_POST['super_important_field']);
  if ($super_important_field != '') {
    header("location: login.php?error=1");
    die();
  }

// continue
  $username = mysqli_real_escape_string($con, $_POST['login_email']);
  $password = mysqli_real_escape_string($con, $_POST['login_pass']);

  if ($username == '') {
    $errors[] = 'Please enter the Username';
  }
  if ($password == '') {
    $errors[] = 'Please enter the Password';
  }

  /*
   * check for user
   */
  $db->where('(username="' . $username . '" or email="' . $username . '")');
  $db->where('is_active', 1);
//  $db->where('is_role', 0);
  $db->where('is_delete', 0);
//  $db->orWhere('email', $username);
  $user_info = $db->getOne('users');
  if ($db->count == 0) {
    $errors[] = 'No such user exists or your account is not active yet';
  }

  /*
   * fetch user data
   */
  $userData = $user_info;

  if ($errors == '') {
    $hash = hash('sha256', $userData['salt'] . hash('sha256', $password));
    if ($hash != $userData['password']) { //incorrect password
      $errors[] = 'Incorrect Password';
    } else {
      /*
       * start session
       */
      ob_start();
      session_start();
      session_regenerate_id();
      $_SESSION['sess_user_id'] = $userData['id'];
      $_SESSION['sess_username'] = $userData['username'];
      $_SESSION['sess_user_email'] = $userData['email'];

      session_write_close();

      $user_id = $_SESSION['sess_user_id'];

      /*
       * update login timestamp
       */
      $data = Array(
          'last_login' => $db->now()
      );
      $db->where('id', $user_id);
      if ($db->update('users', $data)) {
        header('Location: dashboard.php');
        die();
      } else {
        header("location: login.php?error=1");
        die();
      }
    }
  }
}


/*
 * process forgot password form
 */

//Forms posted
if (isset($_POST['forgot_submit'])) {

  /*
   * check for robot submission
   */
  $super_important_field = $_POST['super_important_field2'];
  if ($super_important_field != '') {
    header("location: login.php?error=1");
    exit();
  }

  // continue
  $username = $_POST['forgot_pass_email'];

  if ($username == '') {
    $errors[] = 'Please enter username / email';
  }

  /*
   * check for user
   */

  /*
   * check for user
   */
  $db->where('(username="' . $username . '" or email="' . $username . '")');
  $db->where('is_active', 1);
  $db->where('is_delete', 0);
//  $db->orWhere('email', $username);
  $user_info = $db->getOne('users');
  if ($db->count == 0) {
    $errors[] = 'No such user exists or your account is not active yet';
  }

  if ($errors == '') {
    $subject = 'Password Reset Request For ' . $site_name;


    $userData = $user_info;

    require "./models/phpmailer/class.phpmailer.php"; // include the class name
    $email = $userData['email'];
    $mail = new PHPMailer; // call the class

    $pass = rand(99999, 999999);
    $salt = createSalt();
    $pass = hash('sha256', $salt . hash('sha256', $pass));

    $data = Array(
        'password' => $pass,
        'salt' => $salt,
        'password_updated' => $db->now(),
    );
    $db->where('id', $userData['id']);
    $db->update('users', $data);


    if ($smtp_status == 1) {

      $mail->IsSMTP(); // enable SMTP
      $mail->SMTPDebug = false; // debugging: 1 = errors and messages, 2 = messages only

      if ($smtp_auth == 1) {
        $mail->SMTPAuth = true; // authentication enabled
      } else {
        $mail->SMTPAuth = false; // authentication disabled
      }


      $mail->SMTPSecure = $smtp_secure; // secure transfer enabled REQUIRED for GMail
      $mail->Host = $smtp_host;
      $mail->Port = $smtp_port; // or 587
      $mail->Username = $smtp_user;
      $mail->Password = $sms_password;
    }

    $mail->IsHTML(true);
    $mail->SetFrom($site_email, $site_name); //From address of the mail
    // put your while loop here like below,
    $mail->Subject = $subject; //Subject od your mail
    $mail->AddAddress($email, ""); //To address who will receive this email
    $mail->MsgHTML('Dear ' . $username . ", <br><br>Your password is:" . $pass . '<br><br>Thanks.'); //Put your body of the message you can place html code here
    //$mail->AddAttachment("images/asif18-logo.png"); //Attach a file here if any or comment this line,
    // $send = $mail->Send(); //Send the mails
    if ($mail->Send()) {
      header('Location: login.php?success=Password has been sent to ' . $email . '');
      die();
    } else {
      //   echo $base_url . "reset_password.php?salt = " . $salt . '&mail=' . $username . '&user_type=' . $user_type;
      $errors[] = "There was a problem sending Email, Please Try again later";
    }
  }

  //
}
?><!DOCTYPE html>
<html>
  <head lang="en">

    <title><?= $page_name ?> | <?php echo $site_name; ?> - <?php echo $site_slogan; ?></title>
    <meta name="description" content="<?php echo $site_name . '.' . $site_slogan
?>">

    <?php require_once './includes/head.php'; ?>


  </head>
  <body>



    <div class="page-center">
      <div class="page-center-in">
        <div class="container-fluid">



          <form role="form" method="POST" action="<?= $_SERVER ['PHP_SELF'] ?>" class="sign-box" autocomplete="off">



            <header class="sign-title"><?= $page_name ?> (<?php echo $site_name; ?>)</header>

            <?php
            if ($error == 1) {
              echo ' <div class="alert alert-danger">Something went wrong, please try again.</div>';
            }

            if ($errors != '') {
              echo '<div class="alert alert-block alert-danger fade in">';
              foreach ($errors as $error) {
                echo '' . $error . '.<br>';
              }
              echo '</div>';
            }

            if ($success != '') {
              echo '<div class = "alert alert-block alert-success fade in">';
              //foreach ($successes as $success) {
              echo '<p>' . $success . '.</p>';
              //}
              echo '</div>';
            }
            ?>
            <input type="text" value="<?= $super_important_field ?>" class="hidden" name="super_important_field" id="super_important_field"/>
            <div class="form-group">
              <input type="text" class="form-control validate[required]" id="login_email" name="login_email"  placeholder="Username" autocomplete="off" autofocus=""/>
            </div>

            <div class="form-group">
              <input type="password" class="form-control validate[required]" id="login_pass" name="login_pass" placeholder="Password" autocomplete="off"/>
            </div>

            <button type="submit" class="btn btn-rounded" name="login_submit" id="login_submit">Enter</button>

            <p class="sign-note"><a href="#forgot_password" data-target="#forgot_password" data-toggle="modal">Forgot Password?</a></p>

          </form>




        </div>
      </div>
    </div><!--.page-center-->



    <!-- Forgot Password -->
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
      <input type="text" value="<?= $super_important_field ?>" class="hidden" name="super_important_field2" id="super_important_field2"/>
      <div class="modal fade" id="forgot_password" tabindex="-1" role="dialog" aria-labelledby="forgot_password">
        <div class="modal-dialog modal-sm" role="document">
          <div class="modal-content text-center">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title">Forgot Password?</h4>
            </div>
            <div class="modal-body">
              <label for="forgot_pass_email" class="sr-only">Username / Email</label>
              <input type="text" class="form-control validate[required,maxSize[255]]" id="forgot_pass_email" name="forgot_pass_email" placeholder="Username / Email">
            </div>
            <div class="modal-footer text-center">
              <button type="button" class="btn btn-default btn-rounded"  data-dismiss="modal">Cancel</button>
              <button type="submit" class="btn btn-rounded" name="forgot_submit" id="forgot_submit">Send</button>
            </div>
          </div>
        </div>
      </div>
    </form>
    <!-- Forgot Password -->



    <?php require_once './includes/footer.php'; ?>

  </body>
</html>