<?php
// register.php

require_once __DIR__ . '/lib/bootstrap.php';

require_once __DIR__ . '/lib/strings.php';

// 1) DB-Verbindung (einmal)
$conn = db_connect();

$errors = [];
$values = [
        'email' => '',
        'displayName' => ''
];

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $email = '';
    if (isset($_POST['email']))
    {
        $email = trim((string)$_POST['email']);
    }

    $displayName = '';
    if (isset($_POST['displayName']))
    {
        $displayName = trim((string)$_POST['displayName']);
    }

    $pw = '';
    if (isset($_POST['pw']))
    {
        $pw = (string)$_POST['pw'];
    }

    $pw2 = '';
    if (isset($_POST['pw2']))
    {
        $pw2 = (string)$_POST['pw2'];
    }

    $profilePicture = 'assets/images/profilePictures/default.png';

    $values['email'] = $email;
    $values['displayName'] = $displayName;

    // Validierung
    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        $errors[] = 'Bitte eine gültige E-Mail-Adresse eingeben.';
    }

    if ($displayName === '' || str_length($displayName) < 3 || str_length($displayName) > 50)
    {
        $errors[] = 'Bitte einen Benutzernamen mit 3–50 Zeichen eingeben.';
    }

    if ($pw === '' || str_length($pw) < 8)
    {
        $errors[] = 'Bitte ein Passwort mit mindestens 8 Zeichen wählen.';
    }

    if ($pw !== $pw2)
    {
        $errors[] = 'Die Passwörter stimmen nicht überein.';
    }

    // Duplicate-Checks
    if (!$errors)
    {
        $stmt = mysqli_prepare($conn, 'SELECT userID FROM users WHERE email = ? LIMIT 1');
        if (!$stmt)
        {
            $errors[] = 'Datenbankfehler.';
        }
        else
        {
            mysqli_stmt_bind_param($stmt, 's', $email);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            if ($result && mysqli_fetch_assoc($result))
            {
                $errors[] = 'Diese E-Mail ist bereits registriert.';
            }
            mysqli_stmt_close($stmt);
        }
    }

    if (!$errors)
    {
        $stmt = mysqli_prepare($conn, 'SELECT userID FROM users WHERE displayName = ? LIMIT 1');
        if (!$stmt)
        {
            $errors[] = 'Datenbankfehler.';
        }
        else
        {
            mysqli_stmt_bind_param($stmt, 's', $displayName);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            if ($result && mysqli_fetch_assoc($result))
            {
                $errors[] = 'Dieser Benutzername ist bereits vergeben.';
            }
            mysqli_stmt_close($stmt);
        }
    }

    // Insert
    if (!$errors)
    {
        $hash = password_hash($pw, PASSWORD_DEFAULT);
        $stmt = mysqli_prepare(
                $conn,
                "INSERT INTO users (email, passwordHash, displayName, isActive, createdAt, profilePicture) VALUES (?, ?, ?, 1, NOW(), ?)"
        );

        if (!$stmt)
        {
            $errors[] = 'Datenbankfehler.';
        }
        else
        {
            mysqli_stmt_bind_param($stmt, 'ssss', $email, $hash, $displayName, $profilePicture);
            $ok = mysqli_stmt_execute($stmt);
            
            if ($ok)
            {
                $newUserId = mysqli_insert_id($conn);
                
                // Get USER roleID
                $roleStmt = mysqli_prepare($conn, "SELECT roleID FROM roles WHERE name = 'USER' LIMIT 1");
                if ($roleStmt) {
                    mysqli_stmt_execute($roleStmt);
                    $roleResult = mysqli_stmt_get_result($roleStmt);
                    if ($roleRow = mysqli_fetch_assoc($roleResult)) {
                        $userRoleId = $roleRow['roleID'];
                        
                        $insertRoleStmt = mysqli_prepare($conn, "INSERT INTO userRoles (userID, roleID) VALUES (?, ?)");
                        if ($insertRoleStmt) {
                            mysqli_stmt_bind_param($insertRoleStmt, 'ii', $newUserId, $userRoleId);
                            mysqli_stmt_execute($insertRoleStmt);
                            mysqli_stmt_close($insertRoleStmt);
                        }
                    }
                    mysqli_stmt_close($roleStmt);
                }
                
                mysqli_stmt_close($stmt);

                mysqli_close($conn);
                header('Location: login.php?registered=1');
                exit;
            }

            mysqli_stmt_close($stmt);
            $errors[] = 'Registrierung fehlgeschlagen.';
        }
    }
}

include 'header.php';
?>

<main class="auth" role="main">
    <section class="auth__grid" aria-label="Registrierung Bereich">
        <div class="auth__card">
            <header class="auth__header">
                <h2 class="auth__title">Registrierung</h2>
            </header>

            <?php if ($errors): ?>
                <div class="auth__alert" role="alert">
                    <ul>
                        <?php foreach ($errors as $e): ?>
                            <li><?php echo htmlspecialchars($e, ENT_QUOTES, 'UTF-8'); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form class="auth__form" action="register.php" method="POST" autocomplete="on">
                <div class="auth__field">
                    <label for="email">E-Mail</label>
                    <input type="text" id="email" name="email" autocomplete="email" required
                           value="<?php echo htmlspecialchars($values['email'], ENT_QUOTES, 'UTF-8'); ?>">
                </div>

                <div class="auth__field">
                    <label for="displayName">Username</label>
                    <input type="text" id="displayName" name="displayName" inputmode="text" autocomplete="username"
                           required
                           value="<?php echo htmlspecialchars($values['displayName'], ENT_QUOTES, 'UTF-8'); ?>">
                </div>

                <div class="auth__field">
                    <label for="pw">Passwort</label>
                    <input type="password" id="pw" name="pw" autocomplete="new-password" required>
                </div>

                <div class="auth__field">
                    <label for="pw2">Passwort wiederholen</label>
                    <input type="password" id="pw2" name="pw2" autocomplete="new-password" required>
                </div>

                <div class="auth__actions">
                    <input class="auth__submit" type="submit" value="Registrieren">
                </div>
            </form>

            <div class="auth__links">
                <p class="auth__muted">Schon registriert? <a href="login.php">Einloggen</a></p>
            </div>
        </div>
    </section>
</main>

<?php
mysqli_close($conn);
include 'footer.php';
?>
