<?php
require_once 'db.php';
include_once "ewcfg12.php";
include_once ((EW_USE_ADODB) ? "adodb5/adodb.inc.php" : "ewmysql12.php");
include_once "phpfn12.php";
include_once "class.user - Copy.php";

// grab recaptcha library
require_once "phpinc/recaptchalib.php";

$secretKey   = '6LfM3yUTAAAAAIN9C0U154G3M04Gxb76YdWtsI_4';
$response    = false;

$loginError      = false;
$registerError   = false;
$registerOk      = false;
$lostpwdError    = false;
$lostpwdOk       = false;

$user = new USER($DB_con);


if($_SERVER['REQUEST_METHOD'] == 'POST'){
  if(!empty($_POST['g-recaptcha-response'])){
    $objRecaptcha = new ReCaptcha($secretKey);
    $response = $objRecaptcha->verifyResponse($_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response']);
  }
  if(isset($response->success) && 1 == $response->success){
    //Human is detected you can write script to perform actual action
      if(isset($_POST['btn-login'])) {
          ///////////////////////////
          /// LOGIN CHECK
          //////////////////////////
          $uname = ew_RemoveXSS(ew_StripSlashes($_POST['armyno']));
          $upass = ew_RemoveXSS(ew_StripSlashes($_POST['userpassword']));
          if($user->login($uname,$upass)) {
              $user->log($uname, 1, "");
              $user->redirect('index.php');
          } else {
             $loginError = true;
             $errorMsg   = "Invalid login credential";
             $user->log($uname, 2, $errorMsg);
          }
      } else if(isset($_POST['btn-register'])) {
          ///////////////////////////
          /// REGISTRATION CHECK
          //////////////////////////
          $uname  = trim(ew_RemoveXSS(ew_StripSlashes($_POST['armyno'])));
          $umail  = trim(ew_RemoveXSS(ew_StripSlashes($_POST['useremail'])));
          $upass  = trim(ew_RemoveXSS(ew_StripSlashes($_POST['userpassword']))); 
          $upass2 = trim(ew_RemoveXSS(ew_StripSlashes($_POST['userpasswordconfirm']))); 
          $fname  = "";
          $lname  = "";
        
          if($uname=="") {
              $registerError = true;
              $errorMsg      = "Sila isi No Tentera."; 
          }
          else if($umail=="") {
              $registerError = true;
              $errorMsg      = "Sila isikan alamat Emel."; 
          }
          else if(!filter_var($umail, FILTER_VALIDATE_EMAIL)) {
              $registerError = true;
              $errorMsg      = 'Sila isikan alamt emel yang sah.';
          }
          else if($upass=="") {
              $registerError = true;
              $errorMsg      = "Sila isikan kata laluan";
          }
          else if($upass!==$upass2) {
              $registerError = true;
              $errorMsg      = "Kata laluan tidak sama.";
          }
          else if(strlen($upass) < 6){
              $registerError = true;
              $errorMsg      = "Min 6 karektor untuk kata laluan."; 
          }
          else
          {
             try
             {
                $stmt = $DB_con->prepare("SELECT USERID,USEREMAIL FROM WEBUSER WHERE USERID=:uname OR USEREMAIL=:umail");
                $stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
                $row=$stmt->fetch(PDO::FETCH_ASSOC);
           
                if($row['USERID']==$uname) {
                    $registerError = true;
                    $errorMsg      = "No Tentera telah didaftar.";
                    $user->log($uname, 5, $errorMsg);
                }
                else if($row['USEREMAIL']==$umail) {
                    $registerError = true;
                    $errorMsg      = "Alamat emel telah didaftar.";
                    $user->log($uname, 5, $errorMsg);
                }
                else
                {
                    $stmt2 = $DB_con->prepare("DECLARE @uname varchar(10) SET @uname=:uname SELECT top 1 ArmyNo FROM VIEW_INDUKTAULIAH_MASTER WHERE LEFT(ArmyNo,7)=(SELECT CASE WHEN LEN(@uname) > 7 THEN @uname ELSE RIGHT ('0000000'+ CAST (@uname AS varchar), 7) END)", array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
                    $stmt2->execute(array(':uname'=>$uname));
                    $userRow=$stmt2->fetchAll(PDO::FETCH_ASSOC);
                    //die($stmt2->rowCount());
                    if(count($userRow) == 0)
                    {
                        $registerError = true;
                        $errorMsg      = "No Tentera tidak sah.";
                        $user->log($uname, 5, $errorMsg);
                    }
                    else
                    {
                        $stmt3 = $DB_con->prepare("SELECT top 1 NAME FROM TBMILITARIES WHERE MILITARYID=:uid");
                        $stmt3->execute(array(':uid'=>$uname));
                        $row3  = $stmt3->fetch(PDO::FETCH_ASSOC);
                        $fname = $row3['NAME'];
                     
                        if($user->register($fname,$lname,$uname,$umail,$upass)) 
                        {
                            $user->sendactivation($uname,$upass,$umail);
                            $user->log($uname, 4, "");
                            $registerError = true;  // set to true to display msg
                            $registerOk    = true;  // set to true to change msg to ok green
                            $errorMsg      = "Success. Check email for activation";
                            //$user->redirect('register.php?joined');
                        }
                    }
                }
            }
            catch(PDOException $e)
            {
                $registerError = true;
                $errorMsg      = $e->getMessage();
                $user->log($uname, 5, $errorMsg);
            }
         }
      } else if(isset($_POST['btn-forgotpwd'])) {
          ///////////////////////////
          /// FORGOT PASSWORD CHECK
          //////////////////////////
          $uname  = trim(ew_RemoveXSS(ew_StripSlashes($_POST['armyno'])));

          if($uname=="") {
              $lostpwdError = true;
              $errorMsg     = "No Tentera mesti diisikan!";
          } else {
              try
              {
                  $stmt = $DB_con->prepare("SELECT USERID,USEREMAIL FROM WEBUSER WHERE USERID=:uname");
                  $stmt->execute(array(':uname'=>$uname));
                  $row=$stmt->fetch(PDO::FETCH_ASSOC); 

                  if($row['USERID']==$uname) {
                      $user->sendforgotpassword($uname);
                      //$user->redirect('forgotpwd.php?joined');
                      $user->log($uname, 15, "");
                      $lostpwdError = true;  // set to true to display msg
                      $lostpwdOk    = true;  // set to true to change msg to ok green
                      $errorMsg     = "Success. Check email for password reset.";
                      
                  } else {
                      $lostpwdError = true;
                      $errorMsg     = "No Tentera tidak sah.";                  
                  }
              } catch(PDOException $e) {
                  $lostpwdError = true;
                  $errorMsg     = $e->getMessage();
              }
          }
        
      }
      
  } else {
    $loginError = true;
    $errorMsg   = "You are not human!";
  }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>i-Wira - Sistem Semakan Caruman Atas Talian</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.6 -->
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <!--<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">-->
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="dist/css/AdminLTE.min.css">
    <link rel="stylesheet" href="dist/css/skins/skin-blue.min.css">

    <style type="text/css">
      /* #####################################################################
         #
         #   Project       : Modal Login with jQuery Effects
         #   Author        : Rodrigo Amarante (rodrigockamarante)
         #   Version       : 1.0
         #   Created       : 07/28/2015
         #   Last Change   : 08/02/2015
         #
         ##################################################################### */
         
      @import url(http://fonts.googleapis.com/css?family=Roboto);

      * {
          font-family: 'Roboto', sans-serif;
      }

      #login-modal .modal-dialog {
          
      }

      #login-modal input[type=text], input[type=password] {
        margin-top: 10px;
      }

      #div-login-msg,
      #div-lost-msg,
      #div-register-msg {
          border: 1px solid #dadfe1;
          height: 30px;
          line-height: 28px;
          transition: all ease-in-out 500ms;
      }

      #div-login-msg.success,
      #div-lost-msg.success,
      #div-register-msg.success {
          border: 1px solid #68c3a3;
          background-color: #c8f7c5;
      }

      #div-login-msg.error,
      #div-lost-msg.error,
      #div-register-msg.error {
          border: 1px solid #eb575b;
          background-color: #ffcad1;
      }

      #icon-login-msg,
      #icon-lost-msg,
      #icon-register-msg {
          width: 30px;
          float: left;
          line-height: 28px;
          text-align: center;
          background-color: #dadfe1;
          margin-right: 5px;
          transition: all ease-in-out 500ms;
      }

      #icon-login-msg.success,
      #icon-lost-msg.success,
      #icon-register-msg.success {
          background-color: #68c3a3 !important;
      }

      #icon-login-msg.error,
      #icon-lost-msg.error,
      #icon-register-msg.error {
          background-color: #eb575b !important;
      }



      /* #########################################
         #    override the bootstrap configs     #
         ######################################### */

      .modal-backdrop.in {
          filter: alpha(opacity=50);
          opacity: .7;
      }

      .modal-content {
          background-color: #ececea;
          border: 1px solid #bdc3c7;
          border-radius: 0px;
          outline: 0;
      }

      .modal-header {
          min-height: 16.43px;
          padding: 15px 15px 15px 15px;
          border-bottom: 0px;
      }

      .modal-body {
          position: relative;
          padding: 5px 15px 5px 15px;
      }

      .modal-footer {
          padding: 15px 15px 15px 15px;
          text-align: left;
          border-top: 0px;
      }

      .checkbox {
          margin-bottom: 0px;
      }

      .btn {
          border-radius: 0px;
      }

      .btn:focus,
      .btn:active:focus,
      .btn.active:focus,
      .btn.focus,
      .btn:active.focus,
      .btn.active.focus {
          outline: none;
      }

      .btn-lg, .btn-group-lg>.btn {
          border-radius: 0px;
      }

      .btn-link {
          padding: 5px 10px 0px 0px;
          color: #95a5a6;
      }

      .btn-link:hover, .btn-link:focus {
          color: #2c3e50;
          text-decoration: none;
      }

      .glyphicon {
          top: 0px;
      }

      .form-control {
        border-radius: 0px;
      }

      /* #########################################
         Resize Google ReCaptcha hack
         ######################################### */
      #rc-imageselect, .g-recaptcha {
            transform:scale(0.87);
            -webkit-transform:scale(0.87);
            transform-origin:0 0;
            -webkit-transform-origin:0 0;
      }
    </style>    
    <!--
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>    
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    -->
    
    <!-- jQuery 2.2.3 -->
    <script src="plugins/jQuery/jquery-2.2.3.min.js"></script>
    <!-- Bootstrap 3.3.6 -->
    <script src="bootstrap/js/bootstrap.min.js"></script>

    <!-- Google reCAPTCHA API -->
    <!--<script src='https://www.google.com/recaptcha/api.js'></script>-->
    <script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
</head>
<body>

<div class="container">
    <div class="row">
      <br>
      <img class="img-responsive hidden-lg hidden-md center-block" src="dist/img/LTATLogo3.png">
      <img class="img-responsive hidden-sm hidden-xs center-block" src="dist/img/logo_ltat_587x70.png"><br>
      <h1 class="text-center">      
      i-Wira<br>      
      <small>Sistem Semakan Caruman Atas Talian</small>
      </h1>
      
      <br><br><br>
      
      <p class="text-center"><a href="#" class="btn btn-primary btn-lg" role="button" data-toggle="modal" data-target="#login-modal">LOGIN MASUK</a></p>
    </div>
</div>

<!-- BEGIN # MODAL LOGIN -->
<div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header" align="center">
              <img  id="img_logo" src="dist/img/LTATLogo3.png">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
              </button>
            </div>
                  
            <!-- Begin # DIV Form -->
            <div id="div-forms">        
                <!-- Begin # Login Form -->
                <form id="login-form" action="<?php echo ew_CurrentPage() ?>" method="post">
                <div class="modal-body center-block">
                    <div id="div-login-msg">
                        <div id="icon-login-msg" class="glyphicon glyphicon-chevron-right"></div>
                        <span id="text-login-msg">Type your username and password.</span>
                    </div>
                    <input id="login_username" name="armyno"       class="form-control" type="text"     placeholder="No Tentera" required>
                    <input id="login_password" name="userpassword" class="form-control" type="password" placeholder="Kata Laluan" required>
                    <!--
                    <div class="checkbox">
                        <label>
                            <input type="checkbox"> Remember me
                        </label>
                    </div>
                    -->
                    <!-- Google Recaptcha here -->
                    <p><div class="g-recaptcha" data-size="normal" data-sitekey="6LfM3yUTAAAAAJBkHNnZNKtx0xARtQ3N-FwwX_HQ"></div>

                    <div class="callout callout-info">
                      <p>Sila pastikan akaun anda telah diaktifkan melalui emel sebelum login.</p>
                    </div>
                    
                </div>
                <div class="modal-footer">
                    <div>
                        <button type="submit" name="btn-login" class="btn btn-primary btn-lg btn-block" value="Login">Login</button>
                    </div>
                    <div>
                        <button id="login_lost_btn" type="button" class="btn btn-link">Lost Password?</button>
                        <button id="login_register_btn" type="button" class="btn btn-link">Register</button>
                    </div>
                </div>
                </form>
                <!-- End # Login Form -->
                
                <!-- Begin | Lost Password Form -->
                <form id="lost-form" style="display:none;" action="<?php echo ew_CurrentPage() ?>" method="post">
                <div class="modal-body center-block">
                    <div id="div-lost-msg">
                        <div id="icon-lost-msg" class="glyphicon glyphicon-chevron-right"></div>
                        <span id="text-lost-msg">Type your Army No.</span>
                    </div>
                    <input id="lost_armyno" name="armyno" class="form-control" type="text" placeholder="No Tentera" required>
                    
                    <!-- Google Recaptcha here -->
                    <p><div class="g-recaptcha" data-size="normal" data-sitekey="6LfM3yUTAAAAAJBkHNnZNKtx0xARtQ3N-FwwX_HQ"></div>
                </div>
                <div class="modal-footer">
                    <div>
                        <button type="submit" name="btn-forgotpwd" class="btn btn-primary btn-lg btn-block" value="Forgot Password">Send Email</button>
                    </div>
                    <div>
                        <button id="lost_login_btn" type="button" class="btn btn-link">Log In</button>
                        <button id="lost_register_btn" type="button" class="btn btn-link">Register</button>
                    </div>
                </div>
                </form>
                <!-- End | Lost Password Form -->
                
                <!-- Begin | Register Form -->
                <form id="register-form" style="display:none;" action="<?php echo ew_CurrentPage() ?>" method="post">
                <div class="modal-body center-block">
                    <div id="div-register-msg">
                        <div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
                        <span id="text-register-msg">Register an account.</span>
                    </div>
                    <input id="register_username"         name="armyno"              class="form-control" type="text"     placeholder="No Tentera" required>
                    <input id="register_email"            name="useremail"           class="form-control" type="text"     placeholder="Emel" required>
                    <input id="register_password"         name="userpassword"        class="form-control" type="password" placeholder="Kata Laluan"  data-minlength="6" pattern="(?=^.{6,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required>
                    <input id="register_password_confirm" name="userpasswordconfirm" class="form-control" type="password" placeholder="Sah Kata Laluan" data-minlength="6" data-match="#register_password" required>
                    <!-- Google Recaptcha here -->
                    <p><div class="g-recaptcha" data-size="normal" data-sitekey="6LfM3yUTAAAAAJBkHNnZNKtx0xARtQ3N-FwwX_HQ"></div>
                    
                </div>
                <div class="modal-footer">
                    <div>
                        <button type="submit" name="btn-register" class="btn btn-primary btn-lg btn-block" value="Register">Register</button>
                    </div>
                    <div>
                        <button id="register_login_btn" type="button" class="btn btn-link">Log In</button>
                        <button id="register_lost_btn" type="button" class="btn btn-link">Lost Password?</button>
                    </div>
                </div>
                </form>
                <!-- End | Register Form -->
                
            </div>
            <!-- End # DIV Form -->
                  
        </div>
		</div>

    <!-- END # MODAL LOGIN -->
<script type="text/javascript">
/* #####################################################################
   #
   #   Project       : Modal Login with jQuery Effects
   #   Author        : Rodrigo Amarante (rodrigockamarante)
   #   Version       : 1.0
   #   Created       : 07/29/2015
   #   Last Change   : 08/04/2015
   #
   ##################################################################### */
   
$(function() {
    
    var $formLogin        = $('#login-form');
    var $formLost         = $('#lost-form');
    var $formRegister     = $('#register-form');
    var $divForms         = $('#div-forms');
    var $modalAnimateTime = 100;
    var $msgAnimateTime   = 150;
    var $msgShowTime      = 7000;

    <?php if($loginError):?>
          $('#login-modal').modal('show');
          msgChange($('#div-login-msg'), $('#icon-login-msg'), $('#text-login-msg'), "error", "glyphicon-remove", "<?php echo $errorMsg; ?>");      
    <?php endif;?>

    <?php if($registerError):?>
          $('#login-modal').modal('show');
          
          <?php if ($registerOk){ ?>
              msgChange($('#div-login-msg'), $('#icon-login-msg'), $('#text-login-msg'), "success", "glyphicon-ok", "<?php echo $errorMsg; ?>");      
          <?php
          } else {
          ?>
              window.setTimeout(function(){
                 // do whatever you want to do
                 $('#login_register_btn').trigger("click");
              }, 300);
              //msgChange($('#div-login-msg'), $('#icon-login-msg'), $('#text-login-msg'), "error", "glyphicon-remove", "<?php echo $errorMsg; ?>");      
              msgChange($('#div-register-msg'), $('#icon-register-msg'), $('#text-register-msg'), "error", "glyphicon-remove", "<?php echo $errorMsg; ?>");      
          <?php    
          }
          ?>
    <?php endif;?>

   <?php if($lostpwdError):?>
          $('#login-modal').modal('show');
          
          <?php if ($lostpwdOk){ ?>          
              //msgChange($('#div-lost-msg'), $('#icon-lost-msg'), $('#text-lost-msg'), "success", "glyphicon-ok", "<?php echo $errorMsg; ?>");      
              msgChange($('#div-login-msg'), $('#icon-login-msg'), $('#text-login-msg'), "success", "glyphicon-ok", "<?php echo $errorMsg; ?>");      
          <?php
          } else {
          ?>
              window.setTimeout(function(){
                 // do whatever you want to do
                 $('#login_lost_btn').trigger("click");
              }, 300);
              msgChange($('#div-lost-msg'), $('#icon-lost-msg'), $('#text-lost-msg'), "error", "glyphicon-remove", "<?php echo $errorMsg; ?>");      
          <?php    
          }
          ?>
    <?php endif;?>    
    
    $('#login_register_btn').click( function () { modalAnimate($formLogin, $formRegister) });
    $('#register_login_btn').click( function () { modalAnimate($formRegister, $formLogin); });
    $('#login_lost_btn').click( function ()     { modalAnimate($formLogin, $formLost); });
    $('#lost_login_btn').click( function ()     { modalAnimate($formLost, $formLogin); });
    $('#lost_register_btn').click( function ()  { modalAnimate($formLost, $formRegister); });
    $('#register_lost_btn').click( function ()  { modalAnimate($formRegister, $formLost); });
    
    function modalAnimate ($oldForm, $newForm) {
        var $oldH = $oldForm.height();
        var $newH = $newForm.height();
        $divForms.css("height",$oldH);
        $oldForm.fadeToggle($modalAnimateTime, function(){
            $divForms.stop().animate({height: $newH}, $modalAnimateTime, function(){
                $newForm.fadeToggle($modalAnimateTime);
            });
        });
    }
    
    function msgFade ($msgId, $msgText) {
        $msgId.fadeOut($msgAnimateTime, function() {
            $(this).text($msgText).fadeIn($msgAnimateTime);
        });
    }
    
    function msgChange($divTag, $iconTag, $textTag, $divClass, $iconClass, $msgText) {
        var $msgOld = $divTag.text();
        msgFade($textTag, $msgText);
        $divTag.addClass($divClass);
        $iconTag.removeClass("glyphicon-chevron-right");
        $iconTag.addClass($iconClass + " " + $divClass);
        setTimeout(function() {
            msgFade($textTag, $msgOld);
            $divTag.removeClass($divClass);
            $iconTag.addClass("glyphicon-chevron-right");
            $iconTag.removeClass($iconClass + " " + $divClass);
  		}, $msgShowTime);
    }
    
    
});
</script>

<script>
    var CaptchaCallback = function() {
      $('.g-recaptcha').each(function(index, el) {
        grecaptcha.render(el, {'sitekey' : '6LfM3yUTAAAAAJBkHNnZNKtx0xARtQ3N-FwwX_HQ'});
      });
    };
</script>
</body>
</html>
