<?php
//Start the Session
header("X-Robots-Tag: noindex, nofollow", true);
session_start();

require('include/dbconfig.php');
require_once 'include/class.user.php';

$reg_user = new USER();

//3. If the form is submitted or not.
//3.1 If the form is submitted
if (isset($_POST['username']) and isset($_POST['upass'])) {
  //3.1.1 Assigning posted values to variables.
  $username = mysqli_real_escape_string($connection, $_POST['username']);
  $upass = mysqli_real_escape_string($connection, $_POST['upass']);

  //3.1.2 Checking the values are existing in the database or not
  $query = "SELECT * FROM account WHERE username='$username' and upass='$upass'";
  $result = mysqli_query($connection, $query);
  
  if (!$result) {
    $msg = "<div class='alert alert-danger'>
						<button class='close' data-dismiss='alert'>&times;</button>
						  System error. Please try again later.
			  </div>";
  } else {
    $count = mysqli_num_rows($result);

    $stmt = $reg_user->runQuery("SELECT * FROM account WHERE username = :username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($row) {
      $fname = $row['fname'];
      $uname = $row['uname']; // Get account number for session
      $status = $row['status'];

      $log = $reg_user->runQuery("UPDATE account SET logins = logins + 1 WHERE username = :username");
      $log->bindParam(':username', $username);
      $log->execute();
    }

    //3.1.2 If the posted values are equal to the database values, then session will be created for the user.
    if ($count == 0) {
      $msg = "<div class='alert alert-danger'>
						<button class='close' data-dismiss='alert'>&times;</button>
						  Invalid Username or Password!
			  </div>";
    } elseif ($status == 'DISABLED') {
      $msg = "<div class='alert alert-inverse'>
						<button class='close' data-dismiss='alert'>&times;</button>
						  <strong>Sorry! Your Account Has Been Disabled For Violation of Our Terms!</strong>
			  </div>";
    } elseif ($status == 'SUSPEND') {
      $msg = "<div class='alert alert-inverse'>
						<button class='close' data-dismiss='alert'>&times;</button>
						  <strong>Sorry! This Account is Suspended Contact Customercare!</strong>
			  </div>";
    } else {
      //3.1.3 If the login credentials match, create session
      $_SESSION['uname'] = $uname;
    }
  }
}
