<?php require_once('connect.php'); 
if(isset($_SESSION['user_id']) && trim($_SESSION['user_id'])!=='') { 
    // print '<script> window.location.replace("'.$baseurl.'c_panel/welcome/"); </script>';
    print '<script> window.location.replace("'.$baseurl.'c_panel/welcome/"); </script>'; 
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Admin Panel</title>
    <link rel="stylesheet" href="vendor/fontawesome/css/font-awesome.css" />
    <link rel="stylesheet" href="vendor/metisMenu/dist/metisMenu.css" />
    <link rel="stylesheet" href="vendor/animate.css/animate.css" />
    <link rel="stylesheet" href="vendor/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="fonts/pe-icon-7-stroke/css/pe-icon-7-stroke.css" />
    <link rel="stylesheet" href="fonts/pe-icon-7-stroke/css/helper.css" />
    <link rel="stylesheet" href="styles/style.css">
    <script type="text/javascript" src="https://www.grabull.com/crm/js/jquery-1.7.min.js"></script>
    <script>
    function forgotPassword() 
     {  
        $.ajax({
          type : "POST",
          url : "php/forgot.php",
          beforeSend : function()
          {
            $("#loader").css({"display":"block"});
          },
          success : function(response)
          {
            $("#loader").css({"display":"none"});
            // document.write(response);
            // alert(response);
            var result = JSON.parse(response);
            if(result.status.trim() == "ok")
            {
              alert(result.cause);
              window.location = "reset_password.php";
            }
            else{
              alert(result.cause);
            }
            
          }
        });
     } 
 
 function trycapcha()
   {
    var text = ""; 
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for( var i=0; i < 5; i++ ) { text += possible.charAt(Math.floor(Math.random() * possible.length)); }
	$('#orgcaptcha').val(text); 
	$('#canvasArea').html('');
	var newCanvas = $('<canvas/>',{ 'class':'canvasbg', id: 'myCanvas'}).prop({ width: 150, height: 35});
    $('#canvasArea').append(newCanvas);
	var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.font = "20px Georgia";
    ctx.clearRect(20, 20, 10, 25);
    ctx.fillText(text, 10, 25);
    ctx.font = "30px Verdana";
   }
  $(document).ready(function() {  trycapcha(); });

</script>
<style>
    select.error,  input.error, textarea.error { border: red 1px solid !important; color: #333333 !important; }
    .error {  color: red !important; }
    .success {  color: green !important; }
    .btn-captcha {
        color: #333  !important;
        background-color: #fff !important;
        border-color: #ccc  !important;
    }
.canvasbg { border:1px solid #d3d3d3; text-align:center; font-weight:bold; color:#000; font-size:16px; letter-spacing:4px; font-family:Consolas; background:url(captcha.jpg) center top no-repeat; }

#loader{
  width:100%;
  height:100vh;
  position: absolute;
  top:0px;
  left: 0px;
  background: rgba(0,0,0,0.6);
  z-index: 1000;
  display: none;
}
#loader-spin
{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size:100px;
  color:white;
  z-index: 1500;
}
</style>
</head>
<body class="blank">
  <div id="loader">
    <i class="fa fa-spinner fa-spin" id="loader-spin" aria-hidden="true"></i>
  </div>
<div class="color-line"></div>
<div class="login-container">
    <div class="row">
        <div class="col-md-12">
            <div class="text-center m-b-md">
                <h3>LOGIN TO WEBSITE BACKENED</h3>
                <small>This is the best app ever!</small>
            </div>
      <?php $userid=$userpw=''; 
          
      if (isset($_SESSION['login_attempt_blocked']) && (time() - $_SESSION['login_attempt_blocked'] > 500)) { 
         $_SESSION['login_attempt']=4; unset($_SESSION['login_attempt_blocked']); 
      }
      if(!isset($_SESSION['login_attempt'])) { 
         $_SESSION['login_attempt']=4; 
      }
               
      if($_SERVER['REQUEST_METHOD'] == 'POST' && $_SESSION['login_attempt']>0)
      {
			if(trim($_POST['user_id'])!=='' && trim($_POST['user_pw'])!=='')
         {
               if(trim($_POST['orgcaptcha'])==trim($_POST['capcha'])){

        					$userData = $getData->runQuery("SELECT * FROM `user_login` where `user_id`='".trim($_POST['user_id'])."' AND `user_pw`='".md5(trim($_POST['user_pw']))."' limit 1");
                            
        					if($userData[0]['user_id']!=''){
                        session_regenerate_id(true);
        					   $loginkey= generateRandomString(10);
        					   $user_verify=md5($userData[0]['user_id']).$loginkey;
                    	         $_SESSION['log_dt']=date('Ymdhis');	
                                 $_SESSION['user_id']=$userData[0]['user_id'];
                                 $_SESSION['usertype']="admin";
                                 $_SESSION['user_name']=$userData[0]['user_name'];
                                 $_SESSION['user_verify']=$user_verify;
                                 $_SESSION['login_key']=$loginkey;
                                 $_SESSION['type']=$userData[0]['type'];
                                 $user_verify=md5(trim($row['user_name'])).$loginkey;
                                 $logData = $db_handle->runQuery("INSERT INTO `log_details` (`sr_no`, `date`, `details`,`logout`, `user`, `status`, `ip`) VALUES (NULL, '".date('Y-m-d G:i:s')."', 'Try to Login', NULL, '".$userData[0]['user_id']."', 'Login Success', '".$ip."');");
                                 $updateData = $db_handle->runQuery("UPDATE `user_login` SET `login_key`='".$loginkey."', `blocked`='' where `user_id`='".$userData[0]['user_id']."' limit 1");
                                 print '<script> window.location.replace("'.$baseurl.'c_panel/welcome/"); </script>';
                     }else{

                        $userData = $getData->runQuery("SELECT * FROM `master` where `user_id`='".trim($_POST['user_id'])."' AND `user_pw`='".md5(trim($_POST['user_pw']))."' limit 1");

                           if($userData[0]['user_id']!=''){
                              session_regenerate_id(true);
               					$loginkey= generateRandomString(10);
               					$user_verify=md5($userData[0]['user_id']).$loginkey;
                  	         $_SESSION['log_dt']=date('Ymdhis');	
                               $_SESSION['user_id']=$userData[0]['user_id'];
                               $_SESSION['user_name']=$userData[0]['user_name'];
                               $_SESSION['user_verify']=$user_verify;
                               $_SESSION['login_key']=$loginkey;
                               $_SESSION['type']=$userData[0]['type'];
                               //$_SESSION['type']="employee";  // type
                               $user_verify=md5(trim($row['user_name'])).$loginkey;
                               $logData = $db_handle->runQuery("INSERT INTO `log_details` (`sr_no`, `date`, `details`,`logout`, `user`, `status`, `ip`) VALUES (NULL, '".date('Y-m-d G:i:s')."', 'Try to Login', NULL, '".$userData[0]['user_id']."', 'Login Success', '".$ip."');");
                               $updateData = $db_handle->runQuery("UPDATE `master` SET `login_key`='".$loginkey."', `blocked`='' where `user_id`='".$userData[0]['user_id']."' limit 1");
                               
                               print '<script> window.location.replace("'.$baseurl.'c_panel/welcome/"); </script>';
               				}

                           $userData = $getData->runQuery("SELECT * FROM `employee` where `user_id`='".trim($_POST['user_id'])."' AND `user_pw`='".md5(trim($_POST['user_pw']))."' limit 1");
            					
            				   if($userData[0]['user_id']!=''){
                              session_regenerate_id(true);
               					$loginkey= generateRandomString(10);
            					    $user_verify=md5($userData[0]['user_id']).$loginkey;
                  	         $_SESSION['log_dt']=date('Ymdhis');	
                               $_SESSION['user_id']=$userData[0]['user_id'];
                               $_SESSION['user_name']=$userData[0]['user_name'];
                               $_SESSION['user_verify']=$user_verify;
                               $_SESSION['login_key']=$loginkey;
                               $_SESSION['type']=$userData[0]['type'];
                               //$_SESSION['type']="employee";  // type
                               $user_verify=md5(trim($row['user_name'])).$loginkey;
                               $logData = $db_handle->runQuery("INSERT INTO `log_details` (`sr_no`, `date`, `details`,`logout`, `user`, `status`, `ip`) VALUES (NULL, '".date('Y-m-d G:i:s')."', 'Try to Login', NULL, '".$userData[0]['user_id']."', 'Login Success', '".$ip."');");
                               $updateData = $db_handle->runQuery("UPDATE `employee` SET `login_key`='".$loginkey."', `blocked`='' where `user_id`='".$userData[0]['user_id']."' limit 1");
                               
                              
                               print '<script> window.location.replace("'.$baseurl.'c_panel/welcome/"); </script>';
            				   }
                           $_SESSION['login_attempt']=($_SESSION['login_attempt']-1);
                           $msg= '<i class="error">ERROR: Invalid user id and /or password..!</i>'; 
           					   $logData = $db_handle->runQuery("INSERT INTO `log_details` (`sr_no`, `date`, `details`,`logout`, `user`, `status`, `ip`) VALUES (NULL, '".date('Y-m-d G:i:s')."', 'Try to Login', NULL, '".trim($_POST['user_id'])."', 'Login Failed', '".$ip."');");
        					}
               }else{
                     $_SESSION['login_attempt']=($_SESSION['login_attempt']-1);
                     $userid=trim($_POST['user_id']); 
                     $userpw=trim($_POST['user_pw']); $msg= '<i class="error">ERROR: Invalid captcha..!</i>';

                     $logData = $db_handle->runQuery("INSERT INTO `log_details` (`sr_no`, `date`, `details`,`logout`, `user`, `status`, `ip`) VALUES (NULL, '".date('Y-m-d G:i:s')."', 'Try to Login', NULL, '".$userid."', 'Invalid Captcha', '".$ip."');");
					}  
			}else{
            $msg= '<i class="error">ERROR: Invalid user id and /or password..!</i>'; 
         }  
      }
      ?>
        <div class="hpanel">
            <div class="panel-body">
            <form autocomplete="off" name="loginform" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" id="demo-form2" data-parsley-validate class="form-horizontal">
                <div class="col-sm-12 col-xs-12 col-md-12">
                <div class="form-group">
                    <label for="user_id" class="uname" data-icon="u" >Enter Username</label>
                    <input type="text" name="user_id" id="user_id" value="<?php print $userid; ?>" autocomplete="false" class="form-control" placeholder="please enter login id" maxlength="25" required />
                </div>
                <div class="form-group">
                    <label for="user_pw" class="youpasswd" data-icon="p">Your Password</label>
                    <input class="form-control" id="user_pw" value="<?php print $userpw; ?>" autocomplete="false" name="user_pw" type="password" placeholder="please enter login password" maxlength="25" required />
                </div>
                </div>
                <div class="form-group">
                <label class="col-sm-12 control-label required" style="font-weight:normal;" for="capcha">Enter the code in the box below (case sensitive)</label>
                <div class="col-sm-5 col-xs-12">
                  <input placeholder="enter code here" autocomplete="false" value="" onClick="removeerror(this.id)" id="capcha" name="capcha" required class="form-control" type="text">
                <span id="capcha_error"></span>
                 <div style="clear:both; height:5px;"></div>
                 </div>
                 <div class="col-sm-5 col-xs-8" id="canvasArea"></div>
                 <div class="col-sm-2 col-xs-4">
                     <input id="orgcaptcha" name="orgcaptcha" value="" type="hidden">
           			<a href="javascript:void(0)" style="line-height:30px; font-size:20px;" onClick="trycapcha();" title="change captcha"><i class="fa fa-repeat"></i></a>
                 </div>
              </div>
              <div style="clear:both; height:10px;"></div>
              <div class="form-group">
               <?php 
                    if($_SESSION['login_attempt']>0) { if($_SESSION['login_attempt']<4) { print '<span style="color:red; line-height:25px;"><i class="fa fa-hand-o-right"></i> Attempt remainging '.$_SESSION['login_attempt'].'</span>'; } ?>
                <button class="btn btn-success btn-block" type="submit" value="Login">Login</button>
                <div id="loginVerifyResult" align="center"><?php print $msg; ?></div>
                <?php } else { print '<h6 style="color:red;"><i class="fa fa-times"></i> User blocked for 5 minuts, please try after 5 minuts..!</h6>'; 
                if(!isset($_SESSION['login_attempt_blocked']) || empty($_SESSION['login_attempt_blocked'])) { $_SESSION['login_attempt_blocked']=time(); }
                } ?>
                <div style="margin-top:8px;"><a href="javascript:void(0)" onClick="forgotPassword();" class="pull-right" style="font-size:13px;"><i class="fa fa-pencil"></i> Forgot Password?</a></div>
            </form>
            </div>
        </div>
    </div>
    </div>
    <div class="row">
        <div class="col-md-12 text-center">
            <strong>Design By:-</strong> - WebSupports Services 
        </div>
    </div>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</body>

</html>