<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';

$user = require_login();
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, ['<html lang="de">' => '<html lang="en">', 'Nutzer · TripTale' => t('users.title') . ' · TripTale', '>← Zurück<' => '>' . t('users.back') . '<', '>Nutzer<' => '>' . t('users.title') . '<', '>Nutzer anlegen, Rollen verwalten und Zugänge deaktivieren.<' => '>' . t('users.intro') . '<', '>+ Neuer Nutzer<' => '>' . t('users.new') . '<', '>Der Nutzer wurde gespeichert.<' => '>' . t('users.saved') . '<', '>Der Nutzer sowie seine privaten Notizen, Kommentare und Bilder wurden gelöscht.<' => '>' . t('users.deleted') . '<', 'placeholder="Name oder E-Mail-Adresse suchen …"' => 'placeholder="' . htmlspecialchars(t('users.search'), ENT_QUOTES, 'UTF-8') . '"', 'Mobil: ' => t('users.mobile') . ' ', '>Hauptadministrator<' => '>' . t('users.role_main_admin') . '<', '>Administrator<' => '>' . t('users.role_admin') . '<', '>Teilnehmer<' => '>' . t('users.role_participant') . '<', '>Aktiv<' => '>' . t('users.active') . '<', '>Deaktiviert<' => '>' . t('users.inactive') . '<', '>Bearbeiten<' => '>' . t('common.edit') . '<', '>Nutzer endgültig löschen<' => '>' . t('users.delete') . '<', '>Noch keine Nutzer vorhanden.<' => '>' . t('users.none') . '<', "confirm('Diesen Nutzer wirklich endgültig löschen? Seine privaten Notizen, Kommentare und zugehörigen Bilder werden entfernt.')" => 'confirm(' . tjs('users.confirm_delete') . ')']);
});
if ($user['role'] !== 'main_admin') { http_response_code(403); exit('Kein Zugriff.'); }

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $deleteId = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
    try {
        if (!$deleteId) { throw new RuntimeException(t('users.error_missing')); }
        $targetQuery = db()->prepare('SELECT id, first_name, last_name, role, profile_image FROM ' . table('users') . ' WHERE id = :id AND deleted_at IS NULL');
        $targetQuery->execute([':id' => $deleteId]);
        $target = $targetQuery->fetch();
        if (!$target) { throw new RuntimeException(t('users.error_missing')); }
        if ($target['role'] === 'main_admin') { throw new RuntimeException(t('users.error_main_admin')); }
        $tripCount = db()->prepare('SELECT COUNT(*) FROM ' . table('trips') . ' WHERE created_by = :user_id');
        $tripCount->execute([':user_id' => $deleteId]);
        if ((int)$tripCount->fetchColumn() > 0) { throw new RuntimeException(t('users.error_has_trips')); }

        $noteImages = db()->prepare('SELECT ni.file_path FROM ' . table('trip_private_note_images') . ' ni JOIN ' . table('trip_private_notes') . ' n ON n.id = ni.note_id WHERE n.user_id = :user_id');
        $noteImages->execute([':user_id' => $deleteId]);
        $commentImages = db()->prepare('SELECT ci.file_path FROM ' . table('trip_comment_images') . ' ci JOIN ' . table('trip_comments') . ' c ON c.id = ci.comment_id WHERE c.user_id = :user_id');
        $commentImages->execute([':user_id' => $deleteId]);
        $imagePaths = array_merge(array_column($noteImages->fetchAll(), 'file_path'), array_column($commentImages->fetchAll(), 'file_path'));

        $pdo = db();
        $pdo->beginTransaction();
        $pdo->prepare('DELETE FROM ' . table('users') . ' WHERE id = :id')->execute([':id' => $deleteId]);
        $pdo->commit();
        foreach (array_unique($imagePaths) as $path) {
            $path = (string)$path;
            if (str_starts_with($path, 'uploads/note-images/') || str_starts_with($path, 'uploads/comment-images/')) {
                @unlink(__DIR__ . '/' . $path);
            }
        }
        if (str_starts_with((string)($target['profile_image'] ?? ''), 'uploads/profile-images/')) {
            @unlink(__DIR__ . '/' . $target['profile_image']);
        }
        header('Location: /users.php?deleted=1'); exit;
    } catch (Throwable $exception) {
        if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
        $error = $exception instanceof RuntimeException ? $exception->getMessage() : t('users.error_delete');
    }
}

$users = db()->query('SELECT id, first_name, last_name, email, phone, profile_image, role, status, created_at FROM ' . table('users') . ' WHERE deleted_at IS NULL ORDER BY role, last_name, first_name')->fetchAll();
$roleLabels = ['main_admin' => t('users.role_main_admin'), 'admin' => t('users.role_admin'), 'participant' => t('users.role_participant')];
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Nutzer · TripTale</title>
<style>
body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:900px;margin:auto}.top{display:flex;justify-content:space-between;align-items:center;gap:14px}.button,button{display:inline-block;padding:9px 12px;background:#126e82;color:#fff;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700;cursor:pointer}.back{background:#e3ebee;color:#126e82}.muted{color:#59636d}.search{box-sizing:border-box;width:100%;margin:14px 0;padding:11px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.user{background:#fff;margin:10px 0;border-radius:12px;border:1px solid #d6e0e4;border-left:4px solid #75aeb9;box-shadow:0 3px 12px #0001;overflow:hidden}.user summary{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:18px;cursor:pointer;list-style:none}.user summary::-webkit-details-marker{display:none}.user summary:hover{background:#f8fafb}.user-person{display:flex;align-items:center;gap:12px;min-width:0}.user-avatar{width:44px;height:44px;flex:0 0 44px;object-fit:cover;border-radius:50%;background:#eaf2f3;border:1px solid #c9dadd}.user-name{font-weight:750}.user-email{color:#59636d;overflow-wrap:anywhere}.chevron{font-size:1.25rem;color:#126e82}.user[open] .chevron{transform:rotate(180deg)}.user-details{padding:0 18px 18px;border-top:1px solid #e1e7e9}.user-details p{margin:12px 0}.role{font-weight:700;color:#126e82}.status{display:inline-block;padding:3px 8px;border-radius:99px;font-size:.85rem;font-weight:700;background:#e6f5e9;color:#1d6831}.status.inactive{background:#edf0f2;color:#59636d}.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:16px}.delete{background:#9d2d2d}.success,.error{padding:12px;border-radius:8px}.success{background:#e6f5e9;color:#1d6831}.error{background:#ffe6e3;color:#8b2424}@media(max-width:600px){body{padding:12px}main{margin:18px auto}.top{display:block}.top>*{width:100%}h1{font-size:1.6rem}.top>.button{display:block;width:100%;text-align:center;margin:8px 0}.user summary{padding:15px}.user-email{display:block;margin-top:4px}.chevron{margin-left:auto}.user-details{padding:0 15px 15px}.actions{display:block}.actions .button,.actions button{display:block;width:100%;text-align:center;margin:8px 0}.actions form{margin:0}.back{display:inline-block!important;width:auto!important;max-width:100%!important;text-align:left!important}}
</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main>
<a class="button back" href="/dashboard.php">← Zurück</a><div class="top"><div><h1>Nutzer</h1><p class="muted">Nutzer anlegen, Rollen verwalten und Zugänge deaktivieren.</p></div><a class="button" href="/user-edit.php">+ Neuer Nutzer</a></div>
<?php if (isset($_GET['saved'])): ?><p class="success">Der Nutzer wurde gespeichert.</p><?php endif; ?>
<?php if (isset($_GET['deleted'])): ?><p class="success">Der Nutzer sowie seine privaten Notizen, Kommentare und Bilder wurden gelöscht.</p><?php endif; ?>
<?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
<input class="search" id="user-search" type="search" placeholder="Name oder E-Mail-Adresse suchen …">
<?php foreach ($users as $entry): ?><details class="user" data-search="<?= htmlspecialchars(strtolower($entry['first_name'] . ' ' . $entry['last_name'] . ' ' . $entry['email']), ENT_QUOTES, 'UTF-8') ?>"><summary><span class="user-person"><img class="user-avatar" src="/<?= htmlspecialchars((string)($entry['profile_image'] ?: 'assets/images/triptale-profile-placeholder.png'), ENT_QUOTES, 'UTF-8') ?>" alt=""><span><span class="user-name"><?= htmlspecialchars($entry['first_name'] . ' ' . $entry['last_name'], ENT_QUOTES, 'UTF-8') ?></span><span class="user-email"> · <?= htmlspecialchars($entry['email'], ENT_QUOTES, 'UTF-8') ?></span></span></span><span class="chevron">⌄</span></summary><div class="user-details"><p><span class="role"><?= htmlspecialchars($roleLabels[$entry['role']] ?? $entry['role'], ENT_QUOTES, 'UTF-8') ?></span> · <span class="status<?= $entry['status'] === 'inactive' ? ' inactive' : '' ?>"><?= $entry['status'] === 'active' ? 'Aktiv' : 'Deaktiviert' ?></span></p><?php if ($entry['phone']): ?><p class="muted">Mobil: <?= htmlspecialchars($entry['phone'], ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><div class="actions"><a class="button" href="/user-edit.php?id=<?= (int)$entry['id'] ?>">Bearbeiten</a><?php if ($entry['role'] !== 'main_admin'): ?><form method="post" onsubmit="return confirm('Diesen Nutzer wirklich endgültig löschen? Seine privaten Notizen, Kommentare und zugehörigen Bilder werden entfernt.');"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="user_id" value="<?= (int)$entry['id'] ?>"><button class="delete" type="submit">Nutzer endgültig löschen</button></form><?php endif; ?></div></div></details><?php endforeach; ?>
<?php if (!$users): ?><section class="user"><p class="muted" style="padding:18px">Noch keine Nutzer vorhanden.</p></section><?php endif; ?>
</main><script>const search=document.getElementById('user-search');search.addEventListener('input',()=>{const term=search.value.toLowerCase();document.querySelectorAll('[data-search]').forEach(card=>card.hidden=!card.dataset.search.includes(term));});</script></body></html>
