<?php
require_once 'inc/check_login.php';
require_once 'inc/db.php';

$message = '';
$message_type = '';

$user_id = (int)$_SESSION['user_id'];

// Aktuelle Benutzerdaten laden
$stmt_fetch = mysqli_prepare($conn, "SELECT username, email, role, birthday FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt_fetch, "i", $user_id);
mysqli_stmt_execute($stmt_fetch);
$result = mysqli_stmt_get_result($stmt_fetch);
$user_data = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt_fetch);

if (!$user_data) {
    die("Benutzer nicht gefunden.");
}

$current_username = $user_data['username'];
$current_email = $user_data['email'] ?? '';
$current_role = $user_data['role'];
$current_birthday = $user_data['birthday'] ?? '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $new_username = trim($_POST['username'] ?? '');
    $new_email = trim($_POST['email'] ?? '');
    $new_birthday = trim($_POST['birthday'] ?? '');

    if (empty($new_username)) {
        $message = "Benutzername darf nicht leer sein.";
        $message_type = 'danger';
    } else {
        if (!empty($new_email) && !filter_var($new_email, FILTER_VALIDATE_EMAIL)) {
            $message = "Ungültige E-Mail-Adresse.";
            $message_type = 'danger';
        } else {
            // Standardwerte
            $db_email = (!empty($new_email)) ? $new_email : null;
            $db_birthday = (!empty($new_birthday)) ? $new_birthday : null;

            // 🔹 GEBURTSTAGSLOGIK: Nur wenn Geburtstag neu/aktualisiert wird
            $update_last_bday_year = false;
            $new_last_bday_year = null;

            if ($db_birthday !== null) {
                $today = date('Y-m-d');
                $current_year = (int)date('Y');

                $birth_month = (int)date('m', strtotime($db_birthday));
                $birth_day = (int)date('d', strtotime($db_birthday));
                $birthday_this_year = "$current_year-$birth_month-$birth_day";

                if (strtotime($birthday_this_year) < strtotime($today)) {
                    $new_last_bday_year = $current_year;
                    $update_last_bday_year = true;
                }
            }

            // 🔹 Update in DB
            mysqli_autocommit($conn, false);
            $success = true;

            // 1. Benutzerdaten aktualisieren
            $stmt = mysqli_prepare($conn, "UPDATE users SET username = ?, email = ?, birthday = ? WHERE id = ?");
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, "sssi", $new_username, $db_email, $db_birthday, $user_id);
                if (!mysqli_stmt_execute($stmt)) {
                    $success = false;
                }
                mysqli_stmt_close($stmt);
            } else {
                $success = false;
            }

            if ($success) {
                mysqli_commit($conn);
                $_SESSION['username'] = $new_username;
                $_SESSION['email'] = $new_email;

                // Neu laden
                $stmt_reload = mysqli_prepare($conn, "SELECT username, email, role, birthday FROM users WHERE id = ?");
                mysqli_stmt_bind_param($stmt_reload, "i", $user_id);
                mysqli_stmt_execute($stmt_reload);
                $user_data = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt_reload));
                mysqli_stmt_close($stmt_reload);

                $current_username = $user_data['username'];
                $current_email = $user_data['email'] ?? '';
                $current_role = $user_data['role'];
                $current_birthday = $user_data['birthday'] ?? '';

                $message = "Profil erfolgreich aktualisiert!";
                $message_type = 'success';
            } else {
                mysqli_rollback($conn);
                $message = "Fehler beim Speichern der Daten.";
                $message_type = 'danger';
            }

            mysqli_autocommit($conn, true);
        }
    }
}

require_once 'inc/header.php';
?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8 col-lg-6">
            <h2 class="mb-4">Benutzerverwaltung</h2>
            <div class="card shadow">
                <div class="card-header bg-primary-subtle text-secondary">
                    <h4 class="mb-0">Profil bearbeiten</h4>
                </div>
                <div class="card-body">
                    <?php if ($message): ?>
                        <div id="status-message" class="alert alert-<?= htmlspecialchars($message_type) ?> alert-dismissible fade show" role="alert">
                            <?= htmlspecialchars($message) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <form action="" method="post">
                        <div class="mb-3">
                            <label for="username" class="form-label fw-bold">Benutzername</label>
                            <input type="text" class="form-control" id="username" name="username" value="<?= htmlspecialchars($current_username) ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="email" class="form-label fw-bold">E-Mail-Adresse</label>
                            <input type="email" class="form-control" id="email" name="email" value="<?= htmlspecialchars($current_email ?? '') ?>">
                        </div>
                        <div class="mb-3">
                            <label for="birthday" class="form-label fw-bold">Geburtstag</label>
                            <input type="date" class="form-control" id="birthday" name="birthday" value="<?= htmlspecialchars($current_birthday ?? '') ?>">
                        </div>
                        <div class="mb-3">
                            <label for="role" class="form-label fw-bold">Rolle</label>
                            <input type="text" class="form-control" id="role" name="role" value="<?= htmlspecialchars($current_role) ?>" disabled readonly>
                        </div>

                        <div class="d-flex justify-content-between align-items-center mt-3">
                            <div>
                                <button type="submit" class="btn btn-sm btn-outline-primary">Speichern</button>
                                <a href="index.php" class="btn btn-sm btn-outline-secondary">Abbrechen</a>
                            </div>
                            <div>
                                <form action="logout_all_devices.php" method="post" onsubmit="return confirm('Möchtest du dich wirklich auf allen Geräten abmelden?');">
                                    <button type="submit" class="btn btn-sm btn-outline-danger">Auf allen Geräten abmelden</button>
                                </form>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once 'inc/footer.php'; ?>