<?php
session_start();

if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true) {
    header("location: dashboard.php");
    exit;
}

require_once "config/config.php";

$username = $password = "";
$username_err = $password_err = "";

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

    // Username prüfen
    if (empty(trim($_POST["username"]))) {
        $username_err = "Bitte Username eingeben.";
    } else {
        $username = trim($_POST["username"]);
    }

    $password = $_POST["password"] ?? "";


    if (empty($username_err) && empty($password_err)) {

        $sql = "
            SELECT *
            FROM users
            WHERE username = :username
            LIMIT 1
        ";

        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(":username", $username, PDO::PARAM_STR);

        if ($stmt->execute()) {

            if ($stmt->rowCount() === 1) {

                $user = $stmt->fetch(PDO::FETCH_ASSOC);

                $hash  = $user['password_hash'];
                $first = (int)$user['first_login'];

                // 1️⃣ Nur wenn wirklich First Login ODER kein Hash vorhanden
                if ($first === 1 || empty($hash)) {
                    $_SESSION['set_pw_user'] = (int)$user['id'];
                    header("location: set_password.php");
                    exit;
                }


                // 2️⃣ Passwort prüfen
                if (!password_verify($password, $hash)) {
                    $password_err = "Falsches Passwort.";
                } else {

                    session_regenerate_id(true);

                    $_SESSION["loggedin"] = true;
                    $_SESSION["id"]       = (int)$user["id"];
                    $_SESSION["username"] = $user["username"];
                    $_SESSION["name"]     = $user["name"];
                    $_SESSION["role"]     = $user["role"];

                    // last_login setzen
                    $upd = $pdo->prepare("UPDATE users SET last_login = :ts WHERE id = :id");
                    $upd->execute([
                        ':ts' => time(),
                        ':id' => (int)$user['id']
                    ]);

                    header("location: dashboard.php");
                    exit;
                }

            } else {
                $username_err = "Dieser Benutzer existiert nicht.";
            }

        } else {
            echo "Fehler. Bitte später erneut versuchen.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>ANJUMA Login</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
    body {
    background: #ffffff;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: 'Segoe UI', sans-serif;
    margin: 0;
    overflow-x: hidden;
}

.login-card {
    width: 90%;
    max-width: 380px;
    background: #fff;
    border-radius: 16px;
    padding: 30px;
    box-shadow: 0 6px 25px rgba(0,0,0,0.08);
    text-align: center;
    animation: fadeIn 0.4s ease-out;
    border: 1px solid #f1f1f1;
}

.login-logo {
    width: 200px;
    max-width: 100%;
    margin-bottom: 12px;
}

@media (max-width: 480px) {
    .login-card {
        padding: 22px;
    }
    h4 {
        font-size: 1.2rem;
    }
    .btn-login {
        padding: 10px;
        font-size: 15px;
    }
}


    .form-control {
        border-radius: 10px;
        padding: 12px;
        border: 1px solid #dcdcdc;
        font-size: 15px;
    }

    .form-control:focus {
        border-color: #0d6efd;
        box-shadow: 0 0 0 2px rgba(13,110,253,0.15);
    }

    .btn-login {
        width: 100%;
        padding: 12px;
        border-radius: 10px;
        font-size: 16px;
        background: #0d6efd;
        color: white;
        font-weight: 600;
        transition: 0.2s;
    }

    .btn-login:hover {
        background: #0b5ed7;
        transform: translateY(-2px);
    }

    .error {
        color: #d9534f;
        font-size: 0.85rem;
        margin-top: 4px;
        text-align: left;
    }
</style>
</head>

<body>

<div class="login-card">
    
    <img src="ANJUMA_LOGO.png" class="login-logo" alt="ANJUMA Logo">

    <h4 class="mb-3">Willkommen zurück</h4>

    <form action="" method="post">

        <div class="text-start mb-3">
            <label class="mb-1">Username</label>
            <input type="text" name="username" class="form-control"
                   value="<?php echo $username; ?>">
            <?php if (!empty($username_err)) echo "<div class='error'>$username_err</div>"; ?>
        </div>

        <div class="text-start mb-4">
            <label class="mb-1">Passwort</label>
            <input type="password" name="password" class="form-control">
            <?php if (!empty($password_err)) echo "<div class='error'>$password_err</div>"; ?>
        </div>

        <button type="submit" class="btn btn-login">
            Einloggen
        </button>

    </form>
</div>

</body>
</html>
