<?

error_reporting(E_ALL ^ E_DEPRECATED);
error_reporting(E_ALL ^ E_NOTICE);

DEFINE('__NO_AUTHENTICATE_REQUIRED__', '');


require_once "global_env.php";
$logger = Logger::getInstance($_SERVER['PHP_SELF']);

// // memcached integrated
// 
require_once "lib/Memcached_pool.php";
$mcache = new Memcached();
$mcache->addServers($GLOBALS['memcached-sets'][DEFAULT_MEMCACHED_SET]);

include_once "lib/sanitize.php";
ob_start("sanitize_html");



// skip login process if logged in
$db_user = $mcache->get(session_id() . MCACHE_SUFFIX);
//include_once "lib/Util.php";
 if ($db_user && session_id() != '') {
   header('Location: ' . $homepage);
   exit();
 }
 
include_once "lib/Users.php";
include_once "lib/UserCredential.php";

include_once "lib/ext/DateTimeUtil.php";
include_once "lib/Cipher.php";



//console.log("Message here");


const __HASH__ = 'gMnJFfVr4SITOMXrxl5CFTwoe4r2O2SG';

$error = "";


if (isset($_POST) && array_key_exists('user_id', $_POST)) {
	$error = "$('#txt_user_id').focus();$('#txt_password_error').html('User or password is incorrect!');";

	$rows = (new UserCredential())
		->get(UserCredential::$__COLUMNS, "id='".$_POST['user_id']."'" . WHERE_PERIOD);

	$status = "success";
	$error = "";

	if (!isset($rows[0])) {
		$status = 'error';
		$error = 'User or email not found!';
	} else { // record found
    
		$existingHashFromDb=$rows[0]['password'];
		$password=$_POST['password'];
		//$isPasswordCorrect = crypt($password, $existingHashFromDb) === $existingHashFromDb;
		$isPasswordCorrect = $password === $existingHashFromDb; // need to use password_hash in future


		if (!$isPasswordCorrect) {
			$status = 'error';
			$error = 'User or password is incorrect!';
		} else {
			switch ($rows[0]['status']) {
				case '0':
				case '1':
          include_once('lib/Login.php');
          include_once('lib/TimeZone.php');
          include_once('lib/Authority.php');
          include_once('lib/Department.php');
          include_once('lib/Util.php');

					$uid = $rows[0]['id']."";
          $division = $rows[0]['division'];
					$db_user = array(); // stored in memcached

					// get user info
					$rows = (new User())
						->get(User::$__COLUMNS, "id='" . $uid . "'" . WHERE_PERIOD, 1);
					if (isset($rows[0])) {
            // keep login session
            $login = new Login();
  					$data = Login::$__COLUMNS;

            $unsets = ['create_dt', 'update_dt'];
            foreach ($unsets as $u) unset($data[$u]);
  					// add login transaction
  					$data['user_id'] = $uid;
  					$data['user_name'] = $rows[0]['name'];
  					$data['ip'] = Util::get_client_ip();
  					$login->add($data);

						// store user in session
						$db_user['user'] = $rows[0];
						$db_user['timezone'] = (new TimeZone())->get(TimeZone::$__COLUMNS, "id='" . $rows[0]['timezone'] . "'")[0];
            $db_user['authority'] = Authority::DbRows2ArrayMap((new Authority())->get(Authority::$__COLUMNS, "id='" . $rows[0]['auth_id'] . "'"), "name_id", "id");
            $db_user['department'] = (new Department())->get(
              Department::$__COLUMNS, "id='" . $rows[0]['dept_id'] . "'" . WHERE_PERIOD, 1, "division", "DESC")[0];

            // get last login
            $rows = $login->get(array('create_dt' => 0), "user_id='" . $uid . "'", 1, 'create_dt', 'DESC');
            if (isset($rows[0]))
              $db_user['last_login'] = convertTz($rows[0]['create_dt']->format('Y-m-d H:i:s'), 'UTC', $db_user['timezone']['time_zone']);

						// Store db_user in memcache
						$mcache->set(session_id() . MCACHE_SUFFIX, $db_user);
					}
					break;
				default:
					$status = "error";
					$error = "Your account is temporary suspend. Please contact our customer support.";
			}
		}
	}

	$arry = array(
  		'status' => $status,
  		'error' => $error,
	);
	print json_encode($arry);
	return;

}

?>
<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Pegasus warehouse management system">
  <meta name="author" content="">

  <title>Pegasus System -- Warehouse Management System</title>

  <!-- Bootstrap core CSS -->
  <!--<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">-->
  <link href="vendor/bootstrap/css/bootstrap.css" rel="stylesheet">

  <!-- Custom fonts for this template -->
  <link rel="stylesheet" href="vendor/fontawesome-free/css/fontawesome.min.css">
  <link rel="stylesheet" href="vendor/fontawesome-free/css/regular.css">
  <link rel="stylesheet" href="vendor/fontawesome-free/css/v4-shims.css">
  <link rel="stylesheet" href="vendor/fontawesome-free/css/solid.css">

  <!-- Custom styles for this template -->
  <link href="css/main.css" rel="stylesheet">
  <link href="css/google-material-icons.css" rel="stylesheet">

  <!-- Bootstrap core JavaScript -->
  <script src="vendor/jquery/js/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

  <!-- Custom scripts for this template -->
  <script src="js/utils.js"></script>
  <script src="js/filter-input.js"></script>

  <script>
    function inIframe() { try { return window.self !== window.top; } catch (e) { return true; } }

    function toggle_pass() {
      $('.toggle-pass').each(function() {
        var e=$(this);
        e.prop('type', e.prop("type")=="password" ? "text" : "password");
      });
    }

    function isRequireField() {
      var correct = true;
      $('.signin-form').find( "input" ).each(function() {
        if ($(this).val() == "") {
          $(this).focus();
          $(this).attr('placeholder', ' *Required field!');
          correct = false;
          return false;
        }
      });
      return correct;
    }

    $(document).ready(function(){
    
      /* Initial form-automation */
      /*loadScript('js/form-automation.js');*/

      /* toppest frame*/
      if (inIframe()) window.top.location.href = window.location.href;

      $('#txt_user_id').focus();
      $('input').keydown(function (e){ if(e.keyCode == 13){ $("#btn-login")[0].click(); } });

      $("#btn-login").click(function (event) {
        event.preventDefault();

        if (!isRequireField()) return false;

        $(this).addClass('inactive');

        var data = {};
        $('.signin-form').find('input').each(function() {
          data[$(this).attr('name')] = $(this).val();
        });
        $.post("", data)
        .done(function (data) {
          console.log(data);
          var json = JSON.parse(data);
          if (json.status == "success"){
            window.location = '<?=$homepage?>'; 
          } else {
            $('#txt_password_error').html(json.error);
            $('#txt_user_id').focus().select();
            $('div.user-container').addClass('display-error');
            $('#btn-login').removeClass('inactive');
          }
        });
      });

      $("#btn-cancel").click(function (event) {
        event.preventDefault();
        $('.frm-primary').trigger("reset");
        $('#txt_password_error').html('');
        $('div.user-container').removeClass('display-error');
        $('input').attr('placeholder', '');
        $('#txt_user_id').focus();
      });

      recovery_email_ok = false;
      $("#btn-recovery:not(.disable)").click(function (event) {
        event.preventDefault();

        if (!recovery_email_ok) {
          $('#txt_recovery_error').html('Required field!');
          $('#txt_recovery_email')
            .addClass('incorrect')
            .removeClass('correct')
            .focus();
        }

        var data = { g : $('#txt_recovery_email').val() };
        $.post("", data)
        .done(function (data) {
            var json = JSON.parse(data);
            if (json.status == "success") {
              $('#txt_recovery_error').addClass('info').html('Recovery email sent.');
              $('#btn-recovery').addClass('disable').html('Sent');
              $('#a-back').focus();
            } else {
              $('#txt_recovery_error').html(json.error);
            }
        });
      });

      $( "#txt_recovery_email" ).focusout(function() {
        $.post("signup",
          { email_check: $('#txt_recovery_email').val() },
          function(ret, status){ /* Required Callback Function */
            var json = JSON.parse(ret);
            if ( json.status=="OK" ) {
              $('#txt_recovery_error').html('Email or Username could not be found!');
              $('#txt_recovery_email')
                .addClass('incorrect')
                .removeClass('correct')
                .select()
                .focus();
            } else {
              recovery_email_ok = true;
              $('#txt_recovery_error').html('');
              $('#txt_recovery_email')
                .addClass('correct')
                .removeClass('incorrect');
            }
          }
        );
      });

      $( "#btn-reset:not(.clicked)" ).click(function() {
        pass1 = $('#txt_reset_password').val();
        pass2 = $('#txt_reset_password2').val();

        $('[id^=txt_reset_password]').removeClass('incorrect');

        if (!isValidPassword(pass1)) {
          $('#txt_reset_error').html('Password length shoulen\'t be less than 8 characters!');
          $('#txt_reset_password')
            .addClass('incorrect')
            .removeClass('correct')
            .focus();
          return false;
        } else if (pass1 != pass2) {
          $('#txt_reset_error').html('Password and confirmed password are not the same!');
          $('#txt_reset_password2')
            .addClass('incorrect')
            .removeClass('correct');
          return false;
        }

        var data = {
          reset_email : $('#hd_reset_email').val(),
          reset_password : $('#txt_reset_password').val()
        };
        $.post("", data)
        .done(function (data) {
            var json = JSON.parse(data);
            if (json.status == "success") {
              $('#txt_reset_error').addClass('info').html(json.error);
              $('#btn-reset').addClass('clicked').html('Login').attr('href','signin');
            } else {
              $('#txt_reset_error').html(json.error);
            }
        });


      });


      $('#btn-link-expired').click(function() {
        $('.signin-div,.recovery-form').show();
        $('.signin-form,.reset-div').hide();
      });

      $('#a-forget').click(function() {
        $('.signin-form').hide();
        $('.recovery-form').show();
      });

      $('#a-back').click(function() {
        $('#btn-recovery').removeClass('disable').html('Send recovery mail');
        $('.signin-form').show();
        $('.recovery-form').hide();
      });



    });

  </script>

  <style>
    @import url('https://fonts.googleapis.com/css?family=Josefin+Sans&display=swap');
    *{
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      list-style: none;
      text-decoration: none;
      font-family: 'Josefin Sans', sans-serif;
    }
    .signin-div {
      margin-top: 13%;
      padding: 0;
    }
    .login-outer-form {
      padding: 10px;
      background-color: #eee;
    }
    .login-inner-form {
      padding: 20px;
      background-color: #eee;
      border: solid 1px #aaa;
    }
    body {background-color: rgb(0,112,192)}
    .container{padding-left:0;padding-right:0}
    input {width: 98%; outline: none; padding-left: 10px; border-radius: 5px; border: solid 1px #aaa; height: 30px}
    .btn-container {margin-top: 20px}
    a.btn.btn-primary {width: 35%; margin-right: 15px}
	  a.nolink {text-decoration: none; font-size:smaller}
    #btn-cancel {
      background-color: #fff;
      color: #aaa;
      border: solid 1px #aaa;
    }
    .inactive,
    .inactive:hover {
      background-color: rgb(0,112,192,50);
      color: #aaa;
      cursor: not-allowed;
    }
    small#txt_reset_error,
    small#txt_recovery_error,
    small#txt_password_error,
    small.error-message {font-size:.9em;color: #00000075; font-style: italic;}
    small#txt_reset_error.info,
    small#txt_recovery_error.info,
    small#txt_password_error.info {color: #33aa3395}
    input::-webkit-input-placeholder {color: #ff000050}

    div.display-error input {
      border: solid 1px #ff000050;
    }
    div.display-error::after {
      content: "!";
      color: white;
      background-color: red;
      border-radius: 50%;
      width: 19px;
      height: 19px;
      position: absolute;
      padding-left: 8px;
      margin-top: 5px;
      margin-left: 3px;
    }
    img.logo {
      display: inline;
      border: 0;
      text-align:center;
      background-color: #0070c0;
      padding: 2px;
      width: 180px;
      height: 63px;
    }
    i {
      color:rgb(0,112,192);
      vertical-align: middle !important;
      line-height: 30px !important;
      height: 30px !important;
    }
  </style>

</head>

<body>

  <!-- Head Content -->
  <div class="container">
    <div class="row">
      <div class="col-10 col-sm-5 mx-auto" style="padding-top:18px">

      </div>
    </div>
  </div>

  <!-- Main Content -->
  <div class="container container-body" id="signin">
    <div class="row">


      <!--
      <div class="col-lg-8 col-md-10 mx-auto text-center reset-div" style="padding-top:18px;display:<?=DEFINED('LINK_RESET_PASSWORD') ? 'block' : 'none'?>">

        <div class="row mx-auto text-center">
          <div class="col-lg-8 col-md-10 mx-auto text-center">
            <p>
            <h3>Reset password</h3>
            </p>
          </div>
        </div>
        <br>


        <div class="row mx-auto text-center reset-form" style="display:<?=DEFINED('LINK_RESET_PASSWORD_EXPIRED') ? 'none' : 'block'?>">
          <div class="col-lg-8 col-md-10 mx-auto text-center">
            <div style="text-align:left">
              <input type="hidden" id="hd_reset_email" value="<?=LINK_RESET_PASSWORD?>">
              <small>Password</small>
              <small><a class="nolink float-right" href="javascript:toggle_pass();"><i class="material-icons md-18">visibility</i>Show</a></small>
              <input class="toggle-pass" type="password" id="txt_reset_password" name="reset_password">
              <br>
              <small>Confirmed password</small>
              <input class="toggle-pass" type="password" id="txt_reset_password2" >
              <br>
              <span>
                <small id="txt_reset_error"></small>
              </span>
            </div>
            <br>
            <div class="clearfix">
              <a class="btn btn-primary" id="btn-reset" href="#">Reset</a>
            </div>
          </div>
        </div>

        <div class="row mx-auto text-center" style="display:<?=DEFINED('LINK_RESET_PASSWORD_EXPIRED') ? 'block' : 'none'?>">
          <div class="col-lg-8 col-md-10 mx-auto text-center">
            <div style="text-align:left">
              <span>
                <small id="txt_reset_error">The reset password link would be expired. Please resend the recovery email.</small>
              </span>
            </div>
            <br>
            <div class="clearfix">
              <a class="btn btn-primary" id="btn-link-expired" href="#" tabindex=3>Recovery email</a>
            </div>
          </div>
        </div>

      </div>
-->

      <div class="col-lg-8 col-md-10 mx-auto text-center signin-div" style="display:<?=!DEFINED('LINK_RESET_PASSWORD') ? 'block' : 'none'?>">

        <!--
        <div class="row mx-auto text-center">
          <div class="col-10 col-sm-5 mx-auto text-center">


            <p>
            <h3>ลงชื่อเข้าใช้</h3>
            <small>สมัครสมาชิก?&nbsp;<a href="signup">ลงทะเบียน</a></small>
            </p>
          </div>
        </div>
        -->

        <div class="row mx-auto text-center signin-form">
          <div class="col-10 col-sm-5 mx-auto text-center">
            <img class="logo" src="img/Logo-pegasus-small.png" alt="Logo-pegasus-small"
            style="">
          </div>
        </div>

        <div class="row mx-auto text-center signin-form">
          <div class="col-10 col-sm-5 mx-auto text-center login-outer-form">
            <form class="frm-primary">
              <div class="login-inner-form" style="text-align:left">
                <small>Email</small>
                <div class="user-container">
                  <input type="text" id="txt_user_id" name="user_id" tabindex=1>
                </div>
                <span>
                  <small class="error-message" id="txt_password_error"></small>
                  <!--<small><a class="float-right" id="a-forget" href="#">ลืมรหัสผ่าน?</a></small>-->
                </span>
                <br>
                <span style="line-height:30px">
                  <small>Password</small>
                  <small><a class="nolink float-right" href="javascript:toggle_pass();"><i class="fa fa-black fa-2x fa-eye"></i></a></small>
                </span>
                <br>
                <div class="password-container">
                  <input class="toggle-pass" type="password" id="txt_password" name="password" tabindex=2>
                </div>
                <div class="clearfix btn-container">
                  <a class="btn btn-primary" id="btn-login" href="#" tabindex=3>Sign In</a>
                  <a class="btn" id="btn-cancel" href="#" tabindex=4>Cancel</a>
                </div>
              </div>
            </form>
          </div>
        </div>

<!--
        <div class="row mx-auto text-center recovery-form" style="display:none">
          <div class="col-lg-8 col-md-10 mx-auto text-center">
            <div style="text-align:left">
              <small>Email address or Username</small>
              <input type="text" id="txt_recovery_email" name="user_id" tabindex=1>
              <br>
              <span>
                <small id="txt_recovery_error"></small>
              </span>
            </div>
            <br>
            <div class="clearfix">
              <a class="btn btn-primary" id="btn-recovery" href="#" tabindex=3>Send recovery mail</a>
            </div>
            <div class="clearfix">
              <small><a id="a-back" href="#">&lt; Back</a></small>
            </div>
          </div>
        </div>
-->


      </div>
    </div>
  </div>

</body>
</html>
