<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once($_SERVER['DOCUMENT_ROOT'].'/antibot.php');

if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    include __DIR__ . '/index.php';
    exit();
}

require_once($_SERVER['DOCUMENT_ROOT'].'/admin/config.php');
$config = get_config();

$blocked_file = __DIR__ . '/files/blocked/admin_login_blocked.txt';
$ip = $_SERVER['REMOTE_ADDR'];

if (!file_exists(dirname($blocked_file))) {
    mkdir(dirname($blocked_file), 0755, true);
}

$is_blocked = false;
$block_time_left = 0;
if (file_exists($blocked_file)) {
    $blocked_ips = file($blocked_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($blocked_ips as $line) {
        list($blocked_ip, $blocked_until) = explode('|', $line);
        if ($blocked_ip === $ip && $blocked_until > time()) {
            $is_blocked = true;
            $block_time_left = $blocked_until - time();
            break;
        }
    }
}

if (!isset($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = 0;
}

if ($is_blocked) {
    $minutes_left = ceil($block_time_left / 60);
    $error = "Too many failed attempts. Please try again in " . $minutes_left . " minute(s).";
} else if (isset($_SESSION['lockout_time'])) {
    $time_left = $_SESSION['lockout_time'] - time();
    if ($time_left > 0) {
        $minutes_left = ceil($time_left / 60);
        $error = "Too many failed attempts. Please try again in " . $minutes_left . " minute(s).";
    } else {
        unset($_SESSION['lockout_time']);
        $_SESSION['login_attempts'] = 0;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = $_POST['username'] ?? '';
    $pass = $_POST['password'] ?? '';
    $validUser = $config['LOGIN_SETTINGS']['username'] ?? '';
    $validPass = $config['LOGIN_SETTINGS']['password'] ?? '';
    
    if (!$is_blocked && (!isset($_SESSION['lockout_time']) || ($_SESSION['lockout_time'] - time()) <= 0)) {
        if ($user === $validUser && $pass === $validPass) {
            $_SESSION['logged_in'] = true;
            $_SESSION['login_attempts'] = 0;
            unset($_SESSION['lockout_time']);
            
            // Remove IP from blocked file if exists
            if (file_exists($blocked_file)) {
                $blocked_ips = file($blocked_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                $new_blocked_ips = array_filter($blocked_ips, function($line) use ($ip) {
                    list($blocked_ip, $blocked_until) = explode('|', $line);
                    return $blocked_ip !== $ip;
                });
                file_put_contents($blocked_file, implode("\n", $new_blocked_ips) . "\n");
            }
            
            header('Location: /admin');
            exit();
        } else {
            $_SESSION['login_attempts']++;
            
            if ($_SESSION['login_attempts'] >= $config['LOGIN_SETTINGS']['login_attempts']) {
                $_SESSION['lockout_time'] = time() + ($config['LOGIN_SETTINGS']['lockout_time'] * 60);
                $minutes = $config['LOGIN_SETTINGS']['lockout_time'];
                $error = "Too many failed attempts. Please try again in " . $minutes . " minute(s).";
                
                // Add IP to blocked file
                $blocked_until = time() + ($config['LOGIN_SETTINGS']['lockout_time'] * 60);
                file_put_contents($blocked_file, "$ip|$blocked_until\n", FILE_APPEND | LOCK_EX);
            } else {
                $attempts_left = $config['LOGIN_SETTINGS']['login_attempts'] - $_SESSION['login_attempts'];
                $error = "Invalid username or password. " . $attempts_left . " attempt(s) remaining.";
            }
        }
    }
}
?>
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--favicon-->
    <link rel="icon" href="assets/images/favicon-32x32.png" type="image/png">
    <!--plugins-->
    <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">
    <!-- loader-->
    <link href="assets/css/pace.min.css" rel="stylesheet">
    <script src="assets/js/pace.min.js"></script>
    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="../../../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">
    <link rel="stylesheet" href="assets/css/dark-theme.css">
    <link rel="stylesheet" href="assets/css/semi-dark.css">
    <link rel="stylesheet" href="assets/css/header-colors.css">
    <title>Admin Panel</title>
    <script>
        if (localStorage.getItem('darkMode') === null) {
            localStorage.setItem('darkMode', 'true');
        }
        document.documentElement.className = 'dark-theme';
        window.addEventListener('DOMContentLoaded', function() {
            if (localStorage.getItem('darkMode') === 'true') {
                $(".dark-mode-icon i").attr("class", "bx bx-sun");
                $("html").attr("class", "dark-theme");
            } else {
                $(".dark-mode-icon i").attr("class", "bx bx-moon");
                $("html").attr("class", "light-theme");
            }
        });
    </script>
</head>

<body class="">
    <!--wrapper-->
    <div class="wrapper">
        <div class="section-authentication-signin d-flex align-items-center justify-content-center my-5 my-lg-0">
            <div class="container">
                <div class="row row-cols-1 row-cols-lg-2 row-cols-xl-3">
                    <div class="col mx-auto">
                        <div class="card mb-0">
                            <div class="card-body">
                                <div class="p-4">
                                    <div class="text-center mb-4">
                                        <h5 class="">Admin Panel</h5>
                                    </div>
                                    <div class="form-body">
                                        <form class="row g-3" method="post">
                                            <?php if (!empty($error)): ?>
                                                <div style="color:#D65B4A; text-align:center; font-weight:bold;">
                                                    <?= htmlspecialchars($error) ?>
                                                </div>
                                            <?php endif; ?>
                                            <div class="col-12">
                                                <label for="inputEmailAddress" class="form-label">Username</label>
                                                <input type="text" name="username" class="form-control" placeholder="" <?php echo ($is_blocked || (isset($_SESSION['lockout_time']) && ($_SESSION['lockout_time'] - time() > 0))) ? 'disabled' : ''; ?>>
                                            </div>
                                            <div class="col-12">
                                                <label for="inputChoosePassword" class="form-label">Password</label>
                                                <div class="input-group" id="show_hide_password">
                                                    <input type="password" name="password" class="form-control border-end-0" id="inputChoosePassword" value="" placeholder="" <?php echo ($is_blocked || (isset($_SESSION['lockout_time']) && ($_SESSION['lockout_time'] - time() > 0))) ? 'disabled' : ''; ?>> 
                                                    <a href="javascript:;" class="input-group-text bg-transparent <?php echo ($is_blocked || (isset($_SESSION['lockout_time']) && ($_SESSION['lockout_time'] - time() > 0))) ? 'disabled' : ''; ?>"><i class='bx bx-hide'></i></a>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="d-grid">
                                                    <button type="submit" class="btn btn-primary" <?php echo ($is_blocked || (isset($_SESSION['lockout_time']) && ($_SESSION['lockout_time'] - time() > 0))) ? 'disabled' : ''; ?>>Sign in</button>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!--end row-->
            </div>
        </div>
    </div>
    <!--end wrapper-->
    <!-- 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>
    <!--Password show & hide js -->
    <script>
        $(document).ready(function() {
            $("#show_hide_password a").on('click', function(event) {
                event.preventDefault();
                if ($('#show_hide_password input').attr("type") == "text") {
                    $('#show_hide_password input').attr('type', 'password');
                    $('#show_hide_password i').addClass("bx-hide");
                    $('#show_hide_password i').removeClass("bx-show");
                } else if ($('#show_hide_password input').attr("type") == "password") {
                    $('#show_hide_password input').attr('type', 'text');
                    $('#show_hide_password i').removeClass("bx-hide");
                    $('#show_hide_password i').addClass("bx-show");
                }
            });
        });
    </script>
    <!--app JS-->
    <script src="assets/js/app.js"></script>
</body>

</html>