<?php
declare(strict_types=1);

// =============================================
// 1. SECURE SESSION CONFIGURATION
// =============================================

ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_httponly', '1');

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'secure' => true, // Website must use HTTPS
    'httponly' => true,
    'samesite' => 'Lax'
]);

session_start();

// =============================================
// 2. DATABASE CONNECTION
// =============================================

require_once "connection.php";

// =============================================
// 3. REDIRECT ALREADY LOGGED-IN ADMIN
// =============================================

if (
    isset($_SESSION['admin_id']) &&
    is_int($_SESSION['admin_id']) &&
    $_SESSION['admin_id'] > 0 &&
    ($_SESSION['start'] ?? false) === true
) {
    header("Location: index.php");
    exit;
}

// =============================================
// 4. GENERATE CSRF TOKEN
// =============================================

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

// =============================================
// 5. LOGIN ERROR
// =============================================

$error = '';

// =============================================
// 6. HANDLE LOGIN
// =============================================

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

    try {

        // Validate CSRF token
        if (
            !isset($_POST['csrf_token']) ||
            !isset($_SESSION['csrf_token']) ||
            !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
        ) {
            throw new RuntimeException(
                "Invalid request. Please refresh the page and try again."
            );
        }

        // Get username and password
        $user = trim($_POST['user'] ?? '');
        $pass = $_POST['pass'] ?? '';

        if (
            !is_string($user) ||
            !is_string($pass) ||
            $user === '' ||
            $pass === '' ||
            strlen($user) > 100 ||
            strlen($pass) > 4096
        ) {
            throw new RuntimeException(
                "Invalid username or password."
            );
        }

        // =============================================
        // 7. PREPARED SQL STATEMENT
        // =============================================

        $sql = "SELECT id, `user`, `pass`
                FROM login
                WHERE `user` = ?
                LIMIT 1";

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

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

        mysqli_stmt_execute($stmt);

        mysqli_stmt_bind_result(
            $stmt,
            $adminId,
            $adminUser,
            $hashedPassword
        );

        $adminFound = mysqli_stmt_fetch($stmt);

        mysqli_stmt_close($stmt);

        // =============================================
        // 8. VERIFY PASSWORD HASH
        // =============================================

        if (
            $adminFound &&
            password_verify($pass, $hashedPassword)
        ) {

            // =============================================
            // 9. REGENERATE SESSION ID
            // =============================================

            if (!session_regenerate_id(true)) {
                throw new RuntimeException(
                    "Unable to create secure session."
                );
            }

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

            // Set authenticated admin session
            $_SESSION['admin_id'] = (int)$adminId;

            $_SESSION['admin_user'] = $adminUser;

            $_SESSION['start'] = true;

            $_SESSION['last_activity'] = time();

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

            // Redirect to dashboard
            header("Location: index.php");
            exit;

        } else {

            // Same message for invalid username and password
            $error = "Invalid username or password.";

        }

    } catch (RuntimeException $e) {

        $error = $e->getMessage();

    } catch (Throwable $e) {

        error_log("Admin Login Error: " . $e->getMessage());

        $error = "Something went wrong. Please try again.";

    }
}

?>

<!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">

    <meta name="description" content="Admin Dashboard Login">

    <!-- Favicon -->
    <link rel="shortcut icon" href="assets/logo/fav.png">

    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css"
        id="bootstrap-style"
        rel="stylesheet"
        type="text/css">

    <!-- Icons CSS -->
    <link href="assets/css/icons.min.css"
        rel="stylesheet"
        type="text/css">

    <!-- App CSS -->
    <link href="assets/css/app.min.css"
        id="app-style"
        rel="stylesheet"
        type="text/css">

    <!-- App JS -->
    <script src="assets/js/plugin.js"></script>

    <style>

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {

            background:
                linear-gradient(
                    0deg,
                    #0000006e 0%,
                    #00000063 20%
                ),
                url("./assets/logo/banner.jpg");

            background-size: cover;

            background-position: center;

            background-repeat: no-repeat;

            min-height: 100vh;

            overflow-x: hidden;

        }

        .login-card {

            border-radius: 10px;

            box-shadow:
                0 8px 30px rgba(0, 0, 0, 0.25);

        }

        .login-logo {

            height: 70px;

            width: auto;

            object-fit: contain;

        }

        .login-button {

            background: #f1b44c;

            color: #000;

            font-weight: 700;

            border: none;

        }

        .login-button:hover {

            background: #dfa334;

            color: #000;

        }

        .password-toggle {

            cursor: pointer;

        }

    </style>

</head>


<body>

    <div class="account-pages">

        <div class="container">

            <div class="row justify-content-center">

                <div class="col-md-8 col-lg-6 col-xl-5 mt-5">

                    <div class="card overflow-hidden login-card">


                        <!-- HEADER -->

                        <div class="bg-primary-subtle">

                            <div class="row">

                                <div class="col-12 text-center">

                                    <div class="text-primary p-4">

                                        <h5 class="text-primary">
                                            LOGIN ADMIN
                                        </h5>

                                    </div>

                                </div>

                            </div>

                        </div>


                        <div class="card-body pt-0">


                            <!-- LOGO -->

                            <div class="auth-logo">

                                <div class="avatar-md profile-user-wid mb-4">

                                    <span class="avatar-title bg-light">

                                        <img
                                            src="assets/logo/logo.png"
                                            alt="Website Logo"
                                            class="login-logo">

                                    </span>

                                </div>

                            </div>


                            <div class="p-2">


                                <!-- LOGIN FORM -->

                                <form
                                    class="form-horizontal"
                                    method="POST"
                                    action="login.php"
                                    autocomplete="on">


                                    <!-- CSRF TOKEN -->

                                    <input
                                        type="hidden"
                                        name="csrf_token"
                                        value="<?php echo htmlspecialchars(
                                            $_SESSION['csrf_token'],
                                            ENT_QUOTES,
                                            'UTF-8'
                                        ); ?>">


                                    <!-- ERROR MESSAGE -->

                                    <?php if (!empty($error)): ?>

                                        <div
                                            class="alert alert-danger"
                                            role="alert">

                                            <?php echo htmlspecialchars(
                                                $error,
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ); ?>

                                        </div>

                                    <?php endif; ?>


                                    <!-- USERNAME -->

                                    <div class="mb-3">

                                        <label
                                            for="username"
                                            class="form-label">

                                            Username

                                        </label>

                                        <input
                                            type="text"
                                            class="form-control"
                                            id="username"
                                            name="user"
                                            placeholder="Enter username"
                                            maxlength="100"
                                            autocomplete="username"
                                            required>

                                    </div>


                                    <!-- PASSWORD -->

                                    <div class="mb-3">

                                        <label
                                            for="password"
                                            class="form-label">

                                            Password

                                        </label>


                                        <div class="input-group auth-pass-inputgroup">

                                            <input
                                                type="password"
                                                class="form-control"
                                                id="password"
                                                name="pass"
                                                placeholder="Enter password"
                                                autocomplete="current-password"
                                                required>


                                            <button
                                                class="btn btn-light password-toggle"
                                                type="button"
                                                id="password-addon"
                                                aria-label="Show password">

                                                <i
                                                    class="mdi mdi-eye-outline"
                                                    id="password-icon">
                                                </i>

                                            </button>

                                        </div>

                                    </div>


                                    <!-- LOGIN BUTTON -->

                                    <div class="mt-3 d-grid">

                                        <button
                                            class="btn login-button waves-effect waves-light"
                                            type="submit"
                                            name="submit"
                                            value="1">

                                            Log In

                                        </button>

                                    </div>


                                    <!-- FORGOT PASSWORD -->

                                    <div class="mt-4 text-center">

                                        <a
                                            href="forget.php"
                                            class="text-muted">

                                            <i class="mdi mdi-lock me-1"></i>

                                            Forgot your password?

                                        </a>

                                    </div>


                                </form>


                            </div>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </div>


    <!-- JAVASCRIPT -->

    <script src="assets/libs/jquery/jquery.min.js"></script>

    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>

    <script src="assets/libs/metismenu/metisMenu.min.js"></script>

    <script src="assets/libs/simplebar/simplebar.min.js"></script>

    <script src="assets/libs/node-waves/waves.min.js"></script>

    <script src="assets/js/app.js"></script>


    <!-- PASSWORD SHOW / HIDE -->

    <script>

        const passwordInput = document.getElementById("password");

        const passwordButton = document.getElementById("password-addon");

        const passwordIcon = document.getElementById("password-icon");


        passwordButton.addEventListener("click", function() {

            if (passwordInput.type === "password") {

                passwordInput.type = "text";

                passwordIcon.classList.remove("mdi-eye-outline");

                passwordIcon.classList.add("mdi-eye-off-outline");

                passwordButton.setAttribute("aria-label", "Hide password");

            } else {

                passwordInput.type = "password";

                passwordIcon.classList.remove("mdi-eye-off-outline");

                passwordIcon.classList.add("mdi-eye-outline");

                passwordButton.setAttribute("aria-label", "Show password");

            }

        });

    </script>


</body>

</html>
