<?php
session_set_cookie_params([
    'lifetime' => 0,                 // Session cookie expires when the browser is closed
    'path' => '/',                   // Path for the cookie
    'secure' => true,                // Ensures cookie is only sent over HTTPS
    'httponly' => true,              // Prevents cookie access via JavaScript
    'SameSite' => 'Strict'
]);
session_start();


ini_set('session.cookie_secure', 1);    // Ensures the cookie is sent over HTTPS only
ini_set('session.cookie_httponly', 1);  // Prevents access to the cookie via JavaScript

include_once 'classes/DB.class.php';
include_once 'classes/common.php';
ini_set("display_errors", 0);



session_regenerate_id(true);

$db = new DB();

$msg = "";

$_SESSION['rcuesr_room_admin_sad_id'] = "";

if(!empty($_COOKIE['cook_rcuesr_room_admin_id'])){
    $_SESSION['rcuesr_room_admin_id'] = $_COOKIE['cook_rcuesr_room_admin_id'];
    $_SESSION['rcuesr_room_admin_name'] = $_COOKIE['cook_rcuesr_room_admin_name'];
    header("Location:event-list.php"); 
}



if ($_POST) {
    
    $AddedDateTime = DATE('Y-m-d H:i:s');
    
    $max_attempts = 5; // Maximum failed attempts
$lockout_time = 15 * 60; // Lockout time in seconds (15 minutes)

    $email_id = common::StrToDB($_REQUEST['email']);
    $email_id = base64_decode(urldecode($email_id));
    $email_id = preg_replace("/[^a-zA-Z0-9_@.-]/", "", $email_id);
    
    
    $password = common::StrToDB($_REQUEST['logpassword']);
    $password = base64_decode(urldecode($password));
    
    
    // Get the IP address
$ipAddress = $_SERVER['REMOTE_ADDR'];

// If the user is behind a proxy, get the real IP
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
 

    if (!empty($email_id) && !empty($password)) {
        
        $error_flag = "2";
        /*Checking the Number Of WrongAttempt Rows*/
        $attempt_arr = array();
        $attempt_arr = $db->selectWithCols("rcuesr_login_attempts_tbl", "attempts, last_attempt", "ip_address_val='$ipAddress'");
        
        if(count($attempt_arr)==0){
             // No failed attempts recorded for this user, proceed normally with login
    $attempts = 0;
    $last_attempt = null;
        }else{
            $attempts = $attempt_arr['0']['attempts'];
            $last_attempt = $attempt_arr['0']['last_attempt'];
        }
        
        if ($attempts >= $max_attempts) {
    // If the user has exceeded the max attempts, check if lockout time has passed
       $time_diff = strtotime($AddedDateTime) - strtotime($last_attempt);
    if ($time_diff < $lockout_time) {
        // If the lockout time hasn't passed, deny login
        $msg = "Your account is locked.";
        $error_flag = "1";
    } else {
        // Reset failed attempts if lockout time has passed
        $attempts = 0;
    }
}
        
        if($error_flag == "2"){

        $md5_pwd = md5($password);
        
       // echo "status='1' AND email_id='$email_id' AND password='$md5_pwd'";

        $UserArr = $db->selectWithCols("rcuesr_admin_login_tbl", "admin_pk_id, admin_name, admin_type", "status='1' AND email_id='$email_id' AND password='$md5_pwd'");

        if (count($UserArr) > 0) {
            $_SESSION['rcuesr_room_admin_id'] = $UserArr['0']['admin_pk_id'];
            $_SESSION['rcuesr_room_admin_name'] = $UserArr['0']['admin_name'];
            /*
            setcookie("cook_rcuesr_room_admin_id", $UserArr['0']['admin_pk_id'], time() + (86400 * 30), "/"); // 86400 = 1 day
            setcookie("cook_rcuesr_room_admin_name", $UserArr['0']['admin_name'], time() + (86400 * 30), "/"); // 86400 = 1 day
            */
            
            session_regenerate_id(true);
            
             if(count($attempt_arr)==0){
            
            $Query_str = "INSERT INTO rcuesr_login_attempts_tbl (username, ip_address_val, attempts, last_attempt) VALUES ('$email_id', '$ipAddress' ,'0', '$AddedDateTime')";
            $db->ExecuteQuery($Query_str);
             }else{
                   $Query_str = "UPDATE rcuesr_login_attempts_tbl SET attempts='0', last_attempt='$AddedDateTime' WHERE ip_address_val='$ipAddress'";
            $db->ExecuteQuery($Query_str);
             }
            
           header("Location: room-book-live.php");
        } else {
            $msg = "Email Id and Password are not matched !!";
            $attempts = $attempts+1;
            
                if(count($attempt_arr)==0){
            
            $Query_str = "INSERT INTO rcuesr_login_attempts_tbl (username, ip_address_val, attempts, last_attempt) VALUES ('$email_id', '$ipAddress' ,'$attempts', '$AddedDateTime')";
            $db->ExecuteQuery($Query_str);
             }else{
                   $Query_str = "UPDATE rcuesr_login_attempts_tbl SET attempts='$attempts', last_attempt='$AddedDateTime' WHERE ip_address_val='$ipAddress'";
            $db->ExecuteQuery($Query_str);
             }
            
            
        }
        
        }
    } else {
        $msg = "Please Enter The Username and Password !!";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <title>Admin @ RCUES</title>
        <!-- CSS -->
        <link href="css/bootstrap.min.css" rel="stylesheet"/>
        <link href="fonts/css/font-awesome.min.css" rel="stylesheet"/>
        <link href="css/custom.css" rel="stylesheet"/>
    </head>
    <!--    <body style="background:url(../images/ad1.jpg)repeat;">-->
    <body style="">
        <div id="wrapper" style="background: rgba(255, 255, 255, .8);">
            <div id="login" class="animate form">
                <section class="login_content">
                    <form role="form" id="adminloginform" action="" method="post">
                        <h1>Login Form</h1>
                        <?php if ($msg != "") { ?>
                            <div class="alert alert-danger text-center">
                                <?php echo $msg; ?>
                            </div>
                        <?php } ?>
                        <div>
                            <input type="text" name="email" id="email"  class="form-control" placeholder="Username"  />
                        </div>
                        <div>
                            <input type="password" class="form-control" name="logpassword" id="logpassword" placeholder="Password"  />
                        </div>
                        <div class="pull-right">
                            <input type="submit" name="admin_login" value="Log In" class="btn btn-success submit" />
                        </div>
                        <div class="clearfix"></div>
                        <div class="separator">
                            <div>
                                <p>© 2024 All Rights Reserved. Admin @ RCUES</p>
                            </div>
                        </div>
                    </form>
                </section>
            </div>
        </div>
    </body>
</html>

<!-- Javascripts -->
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.validate.min.js"></script>
<script src="js/jquery-validate.bootstrap-tooltip.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="js/md5.js"></script>
<script type="text/javascript">

$(document).ready(function() {
    $('#adminloginform').submit(function(e) {
        // Prevent form from submitting normally
        e.preventDefault();
           var login_email = $('#email').val();
           var login_pwd = $('#logpassword').val();
           
            login_email = encodeURIComponent(window.btoa(login_email));
            login_pwd = encodeURIComponent(window.btoa(login_pwd));


        // Replace the password field with the hashed password
        $('#logpassword').val(login_pwd);
         $('#email').val(login_email);

        // Now submit the form (which will include the hashed password)
        this.submit();
    });
});


$(document).on('contextmenu', function(e) {
    e.preventDefault(); // Disable right-click
});

    $(document).on('keydown', function(e) {
    if (e.ctrlKey) {
        // Check if the pressed key is C, V, or X
        if (e.key === 'c' || e.key === 'v' || e.key === 'x') {
            e.preventDefault(); // Prevent the default action (copy, paste, cut)
        }
    }
});

$(document).on('selectstart', function(e) {
    e.preventDefault(); // Disable text selection
});

</script>