<?php
include('inc/check_login.php');
require_once('inc/db.php');

// 🔹 Hilfsfunktion: DE-Format → DB-Format
function deDateToDb($deDate)
{
    if (empty($deDate)) return null;
    $parts = explode('.', $deDate);
    if (count($parts) !== 3) return null;
    $day = str_pad(trim($parts[0]), 2, '0', STR_PAD_LEFT);
    $month = str_pad(trim($parts[1]), 2, '0', STR_PAD_LEFT);
    $year = trim($parts[2]);
    if (strlen($year) === 2) {
        $year = (int)$year < 50 ? "20$year" : "19$year";
    }
    if (strlen($year) !== 4) return null;
    if (checkdate((int)$month, (int)$day, (int)$year)) {
        return "$year-$month-$day";
    }
    return null;
}

// 🔹 Hilfsfunktion: DB-Format → DE-Format
function dbDateToDe($dbDate)
{
    if (empty($dbDate) || $dbDate === '0000-00-00') return '';
    return date('d.m.Y', strtotime($dbDate));
}

$is_admin = ($_SESSION['role'] === 'admin');

$message = '';
$message_type = '';
$edit_mode = false;
$edit_user = null;

// --- Nur Admins: Löschen ---
if ($is_admin && isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    if ($id == $_SESSION['user_id']) {
        $message = "Sie können Ihren eigenen Account nicht löschen.";
        $message_type = 'danger';
    } else {
        $stmt = mysqli_prepare($conn, "DELETE FROM users WHERE id = ?");
        mysqli_stmt_bind_param($stmt, "i", $id);
        if (mysqli_stmt_execute($stmt)) {
            $message = "Benutzer erfolgreich gelöscht!";
            $message_type = 'success';
        } else {
            $message = "Fehler beim Löschen: " . mysqli_error($conn);
            $message_type = 'danger';
        }
        mysqli_stmt_close($stmt);
    }
    header("Location: users.php");
    exit();
}

// --- Nur Admins: Bearbeiten ---
if ($is_admin && isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = mysqli_prepare($conn, "SELECT id, username, email, role, birthday, last_activity FROM users WHERE id = ?");
    mysqli_stmt_bind_param($stmt, "i", $id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $edit_user = mysqli_fetch_assoc($result);
    mysqli_stmt_close($stmt);
    $edit_mode = true;

    if (!$edit_user) {
        $message = "Benutzer nicht gefunden.";
        $message_type = 'warning';
    } else {
        $edit_user['birthday_de'] = dbDateToDe($edit_user['birthday']);
    }
}

// --- Nur Admins: Speichern ---
if ($is_admin && $_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $email_raw = trim($_POST['email'] ?? '');
    $birthday_de = trim($_POST['birthday'] ?? '');
    $role = ($_POST['role'] ?? 'member') === 'admin' ? 'admin' : 'member';
    $id = !empty($_POST['id']) ? (int)$_POST['id'] : null;

    $email = !empty($email_raw) ? $email_raw : null;
    $birthday_db = deDateToDb($birthday_de);

    if (empty($username)) {
        $message = "Benutzername ist erforderlich.";
        $message_type = 'danger';
    } else {
        $success = false;
        $update_fields = [];
        $params = [];
        $types = "";

        if ($id) {
            // 🔹 UPDATE: Nur Felder aktualisieren, die sich geändert haben
            $current = mysqli_prepare($conn, "SELECT username, email, birthday, role FROM users WHERE id = ?");
            mysqli_stmt_bind_param($current, "i", $id);
            mysqli_stmt_execute($current);
            $curr_data = mysqli_fetch_assoc(mysqli_stmt_get_result($current));
            mysqli_stmt_close($current);

            if (!$curr_data) {
                $message = "Benutzer nicht gefunden.";
                $message_type = 'danger';
            } else {
                // Prüfe Änderungen
                if ($username !== $curr_data['username']) {
                    $update_fields[] = "username = ?";
                    $params[] = $username;
                    $types .= "s";
                }
                if ($email !== $curr_data['email']) {
                    $update_fields[] = "email = ?";
                    $params[] = $email;
                    $types .= "s";
                }
                if ($birthday_db !== ($curr_data['birthday'] ?: null)) {
                    $update_fields[] = "birthday = ?";
                    $params[] = $birthday_db;
                    $types .= "s";
                }
                if ($role !== $curr_data['role']) {
                    $update_fields[] = "role = ?";
                    $params[] = $role;
                    $types .= "s";
                }

                if (!empty($update_fields)) {
                    // Passwort separat
                    if (!empty($password)) {
                        $password_hashed = password_hash($password, PASSWORD_DEFAULT);
                        $update_fields[] = "password = ?";
                        $params[] = $password_hashed;
                        $types .= "s";
                    }

                    $sql = "UPDATE users SET " . implode(", ", $update_fields) . " WHERE id = ?";
                    $stmt = mysqli_prepare($conn, $sql);
                    $params[] = $id;
                    $types .= "i";

                    mysqli_stmt_bind_param($stmt, $types, ...$params);
                    $success = mysqli_stmt_execute($stmt);
                    mysqli_stmt_close($stmt);
                } else {
                    $success = true; // nichts zu ändern → Erfolg
                    $message = "Keine Änderungen vorgenommen.";
                    $message_type = 'info';
                }
            }
        } else {
            // 🔹 INSERT
            if (empty($password)) {
                $message = "Passwort ist beim Erstellen erforderlich.";
                $message_type = 'danger';
            } else {
                $password_hashed = password_hash($password, PASSWORD_DEFAULT);
                $stmt = mysqli_prepare($conn, "INSERT INTO users (username, password, email, birthday, role) VALUES (?, ?, ?, ?, ?)");
                mysqli_stmt_bind_param($stmt, "sssss", $username, $password_hashed, $email, $birthday_db, $role);
                $success = mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
            }
        }

        if (!isset($message)) {
            if ($success) {
                $message = $id ? "Benutzer erfolgreich aktualisiert!" : "Neuer Benutzer hinzugefügt!";
                $message_type = 'success';
            } else {
                $message = "Fehler beim Speichern: " . mysqli_error($conn);
                $message_type = 'danger';
            }
        }

        header("Location: users.php");
        exit();
    }
}

// --- Mitgliederliste --- 🔹 last_activity hinzugefügt
$users = [];
$result = mysqli_query($conn, "SELECT id, username, role, email, birthday, last_activity FROM users ORDER BY id ASC");
while ($row = mysqli_fetch_assoc($result)) {
    $users[] = $row;
}

require_once 'inc/header.php';
?>

<div class="container mt-5">

    <?php if ($message): ?>
        <div class="alert alert-<?= htmlspecialchars($message_type) ?> alert-dismissible fade show" role="alert">
            <?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">Benutzerübersicht</h2>
    </div>

    <?php if ($is_admin): ?>
        <div class="collapse <?= $edit_mode ? 'show' : '' ?>" id="userFormCollapse">
            <div class="card shadow mb-4">
                <div class="card-header bg-primary-subtle text-secondary">
                    <h4 class="mb-0"><?= $edit_mode ? 'Benutzer bearbeiten' : 'Neuen Benutzer hinzufügen'; ?></h4>
                </div>
                <div class="card-body">
                    <form action="users.php" method="post">
                        <?php if ($edit_mode): ?>
                            <input type="hidden" name="id" value="<?= htmlspecialchars($edit_user['id']); ?>">
                        <?php endif; ?>
                        <div class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Benutzername</label>
                                <input type="text" class="form-control" name="username" value="<?= htmlspecialchars($edit_user['username'] ?? ''); ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">E-Mail (optional)</label>
                                <input type="email" class="form-control" name="email" value="<?= htmlspecialchars($edit_user['email'] ?? ''); ?>">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Geburtsdatum (optional, TT.MM.JJJJ)</label>
                                <input type="text" class="form-control" name="birthday" placeholder="z. B. 15.08.1990" value="<?= htmlspecialchars($edit_user['birthday_de'] ?? ''); ?>">
                                <div class="form-text">Leer lassen, um kein Geburtsdatum zu speichern.</div>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Passwort</label>
                                <input type="password" class="form-control" name="password" placeholder="<?= $edit_mode ? 'Leer lassen = unverändert' : 'Erforderlich' ?>">
                                <?php if ($edit_mode): ?>
                                    <div class="form-text">Leer lassen, um Passwort nicht zu ändern.</div>
                                <?php endif; ?>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Rolle</label>
                                <select class="form-select" name="role">
                                    <option value="member" <?= (($edit_user['role'] ?? 'member') === 'member') ? 'selected' : ''; ?>>Mitglied</option>
                                    <option value="admin" <?= (($edit_user['role'] ?? 'member') === 'admin') ? 'selected' : ''; ?>>Admin</option>
                                </select>
                            </div>
                            <div class="col-12 d-flex justify-content-start">
                                <button type="submit" class="btn btn-sm btn-outline-<?= $edit_mode ? 'success' : 'primary'; ?> me-2">
                                    <?= $edit_mode ? 'Speichern' : 'Hinzufügen'; ?>
                                </button>
                                <a href="users.php" class="btn btn-sm btn-outline-secondary">Abbrechen</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <div class="card shadow">
        <div class="card-header bg-primary-subtle text-secondary d-flex justify-content-between align-items-center">
            <h4 class="mb-0">Mitglieder</h4>
            <?php if ($is_admin): ?>
                <a class="btn btn-sm d-flex align-items-center justify-content-center" data-bs-toggle="collapse" href="#userFormCollapse" role="button" aria-expanded="false" aria-controls="userFormCollapse">Add
                    <span class="material-symbols-outlined">add</span>
                </a>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>User</th>
                            <th class="text-center" style="width: 56px;">Daten</th>
                            <th>Rolle</th>
                            <?php if ($is_admin): ?>
                                <th class="text-center" style="width: 1px;"></th>
                                <th class="text-end"></th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                            <tr>
                                <td><?= htmlspecialchars($user['id']) ?></td>
                                <td><?= htmlspecialchars($user['username']) ?></td>
                                <td class="text-center align-middle">
                                    <div class="d-flex" style="justify-content: center; height: 1.4rem; gap: 0.25rem;">
                                        <div class="d-flex align-items-center justify-content-center" style="width: 1.3em;">
                                            <?php if (!empty($user['email'])): ?>
                                                <span class="material-symbols-outlined text-success" style="font-size:0.8em; line-height:1;" title="E-Mail vorhanden">mail</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="d-flex align-items-center justify-content-center" style="width: 1.3em;">
                                            <?php if (!empty($user['birthday']) && $user['birthday'] !== '0000-00-00'): ?>
                                                <span class="material-symbols-outlined text-info" style="font-size:0.8em; line-height:1;" title="Geburtstag vorhanden">cake</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge rounded-pill bg-<?= $user['role'] === 'admin' ? 'info' : 'secondary' ?>">
                                        <?= htmlspecialchars($user['role']) ?>
                                    </span>
                                </td>
                                <?php if ($is_admin): ?>
                                    <!-- 🔹 Neue Status-Spalte -->
                                    <td class="text-center align-middle">
                                        <?php
                                        $is_online = !empty($user['last_activity']) && strtotime($user['last_activity']) >= strtotime('-10 minutes');
                                        $tooltip = $is_online
                                            ? 'Online'
                                            : (!empty($user['last_activity'])
                                                ? 'Zuletzt online: ' . date('d.m.Y H:i', strtotime($user['last_activity']))
                                                : 'Noch nie gesehen');
                                        $color = $is_online ? 'success' : 'secondary';
                                        ?>
                                        <span
                                            class="badge rounded-pill bg-<?= $color ?> d-inline-block"
                                            title="<?= htmlspecialchars($tooltip) ?>"
                                            style="width: 12px; height: 12px; padding: 0; border: 1px solid #555;"></span>
                                    </td>
                                    <td class="text-end align-middle">
                                        <div class="dropdown">
                                            <a href="#" class="text-secondary" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                <span class="material-icons">more_vert</span>
                                            </a>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <li>
                                                    <a class="dropdown-item d-flex align-items-center" href="users.php?action=edit&id=<?= htmlspecialchars($user['id']) ?>">
                                                        <span class="material-icons me-2">mode_edit_outline</span> Bearbeiten
                                                    </a>
                                                </li>
                                                <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                                    <li>
                                                        <a class="dropdown-item d-flex align-items-center text-danger" href="users.php?action=delete&id=<?= htmlspecialchars($user['id']) ?>" onclick="return confirm('Wirklich löschen?')">
                                                            <span class="material-icons me-2">delete_outline</span> Löschen
                                                        </a>
                                                    </li>
                                                <?php endif; ?>
                                            </ul>
                                        </div>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include('inc/footer.php'); ?>