<?php
declare(strict_types=1);

session_start();

require_once "connection.php";

// Secure session cookie settings
ini_set('session.use_strict_mode', '1');

if (isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit;
}

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Validate CSRF token
    if (
        !isset($_POST['csrf_token']) ||
        !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
    ) {
        $error = "Invalid request. Please refresh and try again.";
    } else {

        $user = trim($_POST['user'] ?? '');
        $pass = $_POST['pass'] ?? '';

        if ($user === '' || $pass === '') {
            $error = "Please enter username and password.";
        } else {

            // Prepared statement prevents SQL injection
            $sql = "SELECT id, `user`, `pass`
                    FROM login
                    WHERE `user` = ?
                    LIMIT 1";

            $stmt = mysqli_prepare($con, $sql);

            if (!$stmt) {
                error_log(mysqli_error($con));
                $error = "Something went wrong. Please try again.";
            } else {

                mysqli_stmt_bind_param($stmt, "s", $user);
                mysqli_stmt_execute($stmt);

                $result = mysqli_stmt_get_result($stmt);
                $admin = mysqli_fetch_assoc($result);

                mysqli_stmt_close($stmt);

                // Verify hashed password
                if ($admin && password_verify($pass, $admin['pass'])) {

                    // Prevent session fixation
                    session_regenerate_id(true);

                    // Clear old session data
                    $_SESSION = [];

                    $_SESSION['admin_id'] = (int)$admin['id'];
                    $_SESSION['admin_user'] = $admin['user'];
                    $_SESSION['start'] = true;

                    // Refresh CSRF token
                    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

                    header("Location: index.php");
                    exit;

                } else {
                    $error = "Invalid username or password.";
                }
            }
        }
    }
}
?>


<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Login Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="assets/logo/fav-icon.jpg">
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" />
    <link href="assets/css/icons.min.css" rel="stylesheet" />
    <link href="assets/css/app.min.css" rel="stylesheet" />

    <style>
    body {
        margin: 0;
        padding: 0;
        height: 100vh;
        overflow: hidden;
    }

    /* Background with blur */
    .bg-blur {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: url('./assets/logo/banner.jpg') center/cover no-repeat;
        filter: blur(3px);
        /* Minimum blur */
        transform: scale(1.05);
        /* Removes blur-edge cut */
        z-index: -1;
    }

    /* Centering container */
    .login-wrapper {
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .login-card {
        width: 100%;
        max-width: 450px;
        border-radius: 12px;
        backdrop-filter: blur(3px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
    }

    .login-title {
        background: #000;
        color: #fff;
        padding: 15px;
        text-align: center;
        border-radius: 12px 12px 0 0;
        font-size: 20px;
        letter-spacing: 1px;
    }

    .logo-img {
        height: 90px;
        padding: 8px;
        border: 1px solid #343a40;
        border-radius: 10px;
    }
    </style>
</head>

<body>

    <!-- BLURRED BACKGROUND -->
    <div class="bg-blur"></div>

    <!-- CENTERED LOGIN -->
    <div class="login-wrapper">
        <div class="card login-card">

            <div class="login-title">LOGIN ADMIN</div>

            <div class="card-body">

                <div class="text-center mb-3">
                    <img src="../images/logo.png" class="logo-img" alt="logo">
                </div>

               <form method="post" action="login.php">
                   <?php if (!empty($error)): ?>
    <div class="alert alert-danger">
        <?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?>
    </div>
<?php endif; ?>
                  <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">

                    <div class="mb-3">
                        <label class="form-label">Username</label>
                        <input type="text" class="form-control" name="user" placeholder="Enter username" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Password</label>
                        <div class="input-group auth-pass-inputgroup">
                            <input type="password" class="form-control" id="password-input" name="pass"
                                placeholder="Enter password" required>

                            <button class="btn btn-light" type="button" id="toggle-password">
                                <i class="mdi mdi-eye-outline" id="toggle-icon"></i>
                            </button>
                        </div>
                    </div>


                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" required>
                        <label class="form-check-label">Remember me</label>
                    </div>

                    <div class="d-grid">
                        <button class="btn btn-dark" type="submit" name="submit">Log In</button>
                    </div>

                     

                </form>

            </div>

        </div>
    </div>

    <!-- JS -->
    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/app.js"></script>



    <script>
    const passwordInput = document.getElementById("password-input");
    const toggleBtn = document.getElementById("toggle-password");
    const toggleIcon = document.getElementById("toggle-icon");

    toggleBtn.addEventListener("click", function() {
        const type = passwordInput.getAttribute("type");

        if (type === "password") {
            passwordInput.setAttribute("type", "text");
            toggleIcon.classList.remove("mdi-eye-outline");
            toggleIcon.classList.add("mdi-eye-off-outline");
        } else {
            passwordInput.setAttribute("type", "password");
            toggleIcon.classList.remove("mdi-eye-off-outline");
            toggleIcon.classList.add("mdi-eye-outline");
        }
    });
    </script>


</body>

</html>