<?php
ob_start();
include("include/connection.php");
session_start();
if (isset($_POST["login"])) {
    // if (isset($_POST["token-response"]) && $_POST["token-response"]!='') {
        
  $username = $_POST['uname'];
  $password = $_POST['password'];
  $token=$_POST['token-response'];
  $secretKey = "6LfwEHMqAAAAANvSd6aD8moRshLdWkz6aUtSmaHK";
  $ip = $_SERVER['REMOTE_ADDR'];
  $url = 'https://www.google.com/recaptcha/api/siteverify';
  $data = array('secret' => $secretKey, 'response' => $token);
  $options = array(
    'http' => array(
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($data)
    )
  );
  $context  = stream_context_create($options);
  $response = file_get_contents($url, false, $context);
  $responseKeys = json_decode($response,true);
  header('Content-type: application/json');
//   if($responseKeys["success"]) {
      
  $sql = "SELECT * FROM admin WHERE admin_id='$username' AND admin_password='$password' LIMIT 1";
  $result = mysqli_query($link, $sql);
  $usr = mysqli_fetch_array($result);
  $mobile = $usr['admin_mobile'];
  // $count = mysqli_num_rows($result)
  if ($usr) {
    if (!empty($_POST["customCheck"])) {
      setcookie("uname", $username, time() + (10 * 365 * 24 * 60 * 60));
      setcookie("password", $password,  time() + (10 * 365 * 24 * 60 * 60));
    } else {
      if (isset($_COOKIE['uname'])) {
        setcookie("uname", "");
      }
      if (isset($_COOKIE["password"])) {
        setcookie("password", "");
      }
    }
    $newuniqueid = uniqid();
    $ipaddress = get_client_ip();
    $sqlwrefdsd = "UPDATE admin_login_log SET stitus='failed' WHERE username='$username'";

    if ($link->query($sqlwrefdsd) === TRUE) {
      //echo "Record updated successfully";
    }

    $sqldsds = "INSERT INTO admin_login_log (username, ip_address, auth_token, stitus, panel)
    VALUES ('$username','$ipaddress','$newuniqueid', 'success', 'master_admin')";

    if ($link->query($sqldsds) === TRUE) {

      $cookie_name = "auth_token";
      $cookie_value = $newuniqueid;
      setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
      setcookie("admin_br_id",$usr['admin_id'], time() + (86400 * 30), "/"); // 86400 = 1 day
    }
     header("Location:dashboard.php?success=11");
     exit;
  } else {
    header("Location:login.php?error=12");
     exit;
  }
//   } else {
//     header("Location:login.php?error=13");
//      exit;
//   }
    // }else{
    //      header("Location:login.php?error=15");
    //     exit;
    // }
}
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="images/favicon.png" type="image/png" />
  <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
  <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
  <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
  <link href="assets/css/pace.min.css" rel="stylesheet" />
  <script src="assets/js/pace.min.js"></script>
  <link href="assets/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
  <link href="assets/css/app.css" rel="stylesheet">
  <link href="assets/css/icons.css" rel="stylesheet">
  <title>Code Studio Hub Admin Panel</title>
</head>
<style>
    .loginbg{
        background-image:url('images/backgroundclor.jpg');
        background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    }
</style>
<body class="loginbg">
  
   
   <div class="wrapper">
		<div class="section-authentication-signin d-flex align-items-center justify-content-center my-5 my-lg-0">
			<div class="container-fluid">
				<div class="row row-cols-1 row-cols-lg-2 row-cols-xl-3">
					<div class="col mx-auto">
						<div class="mb-4 text-center">
							<img src="images/logonotag.png" width="180" alt="" />
						</div>
						<div class="card">
							<div class="card-body">
								<div class="border p-4 rounded">
									<div class="text-center">
										<h3 class="">Sign in</h3>
									
									</div>
								
									<div class="login-separater text-center mb-4"> <span>OR SIGN IN WITH EMAIL</span>
										<hr/>
									</div>
									<div class="form-body">
										<form class="row g-3" method="POST" action="">
											<div class="col-12">
												<label for="inputEmailAddress" class="form-label">Email Address</label>
											 <input type="text" class="form-control" name="uname" placeholder="User Id" value="<?php if (isset($_COOKIE['uname'])) {
                                                                                                echo $_COOKIE['uname'];
                                                                                              } ?>">
											</div>
											<div class="col-12">
												<label for="inputChoosePassword" class="form-label">Enter Password</label>
												<div class="input-group" id="show_hide_password">
												<input type="password" class="form-control" name="password" placeholder="Password" value="<?php if (isset($_COOKIE['password'])) {
                                                                                                        echo $_COOKIE['password'];
                                                                                                      } ?>">
												</div>
											</div>
									
            <div class="input-group mb-3">
            <input type="hidden" name="token-response" id="token-response">
          </div>
										
											<div class="col-12">
												<div class="d-grid">
													<button type="submit" class="btn btn-primary" name="login"><i class="bx bxs-lock-open"></i>Sign in</button>
												</div>
											</div>
										</form>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
  <script src="plugins/jquery/jquery.min.js"></script>
  <!-- Bootstrap 4 -->
  <script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="dist/js/adminlte.min.js"></script>
  <script src="https://www.google.com/recaptcha/api.js?render=6LfwEHMqAAAAAEAAZNCe9HLXJlcBoVVOeGHlt-L1"></script>
  	<!-- Bootstrap JS -->
	<script src="assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<script src="assets/js/jquery.min.js"></script>
	<script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
	<script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
	<script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
	<script src="assets/plugins/vectormap/jquery-jvectormap-2.0.2.min.js"></script>
    <script src="assets/plugins/vectormap/jquery-jvectormap-world-mill-en.js"></script>
	<script src="assets/plugins/chartjs/js/Chart.min.js"></script>
	<script src="assets/plugins/chartjs/js/Chart.extension.js"></script>
	<script src="assets/js/index.js"></script>
	<!--app JS-->
	<script src="assets/js/app.js"></script>
	<script src="assets/plugins/datatable/js/jquery.dataTables.min.js"></script>
	<script src="assets/plugins/datatable/js/dataTables.bootstrap5.min.js"></script>
  
  	<script src="assets/plugins/notifications/js/lobibox.min.js"></script>
	<script src="assets/plugins/notifications/js/notifications.min.js"></script>
	<script src="assets/plugins/notifications/js/notification-custom-script.js"></script>
  <script>
  grecaptcha.ready(function() {
      grecaptcha.execute('6LfwEHMqAAAAAEAAZNCe9HLXJlcBoVVOeGHlt-L1', {action: 'homepage'}).then(function(token) {
        // pass the token to the backend script for verification
        document.getElementById('token-response').value=token;
      });
  });
  
  
   window.onload = function() {
    <?php
    if (isset($_GET['success']) && $_GET['success'] == 1) {
    ?>
    Lobibox.notify('success', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-check-circle',
        msg: 'Campaign added successfull'
    });
    <?php
    }
    ?>
    
    <?php
    if (isset($_GET['error']) && $_GET['error'] == 13) {
    ?>
    Lobibox.notify('error', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-x-circle',
        msg: 'invalid password'
    });
    <?php
    }
    ?>
    
    
    
    <?php
    if (isset($_GET['success']) && $_GET['success'] == 111) {
    ?>
    Lobibox.notify('success', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-check-circle',
        msg: 'Mail added successfull'
    });
    <?php
    }
    ?>
    
    <?php
    if (isset($_GET['error']) && $_GET['error'] == 546) {
    ?>
    Lobibox.notify('error', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-x-circle',
        msg: 'Security Verification Failed'
    });
    <?php
    }
    ?>
    
    
    <?php
    if (isset($_GET['success']) && $_GET['success'] == 11) {
    ?>
    Lobibox.notify('success', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-check-circle',
        msg: 'Login  successfull'
    });
    <?php
    }
    ?>
    
    <?php
    if (isset($_GET['error']) && $_GET['error'] == 33) {
    ?>
    Lobibox.notify('error', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-x-circle',
        msg: 'Invalid User ID'
    });
    <?php
    }
    ?>
    
    
    <?php
    if (isset($_GET['success']) && $_GET['success'] == 3) {
    ?>
    Lobibox.notify('success', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-check-circle',
        msg: 'Amount debited successfully'
    });
    <?php
    }
    ?>
    
    <?php
    if (isset($_GET['error']) && $_GET['error'] == 5) {
    ?>
    Lobibox.notify('error', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-x-circle',
        msg: 'No sufficient balance'
    });
    <?php
    }
    ?>
    
    <?php
    if (isset($_GET['success']) && $_GET['success'] == 4) {
    ?>
    Lobibox.notify('success', {
        pauseDelayOnHover: true,
        continueDelayOnInactiveTab: false,
        position: 'top right',
        icon: 'bx bx-check-circle',
        msg: 'Amount credited successfully'
    });
    <?php
    }
    ?>
    
    
    
    
	 }
  </script>
</body>
</html>