<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/trip-changes.php';
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, ['<html lang="de">' => '<html lang="en">', 'Reisegruppe · TripTale' => t('team.title') . ' · TripTale', '>← Zurück zur Reise<' => '>' . t('team.back') . '<', '>Reisegruppe<' => '>' . t('team.title') . '<', '>Teilnehmer<' => '>' . t('team.participant') . '<', '>Reise-Admin<' => '>' . t('team.admin') . '<', '>Kann die Reise ansehen, Kommentare schreiben und eigene private Notizen führen.<' => '>' . t('team.participant_hint') . '<', '>Kann zusätzlich Reise, Tage und Programm bearbeiten sowie das Reiseteam verwalten.<' => '>' . t('team.admin_hint') . '<', '>Nutzer hinzufügen oder Rolle ändern<' => '>' . t('team.add_or_change') . '<', '>Nutzer<' => '>' . t('team.user') . '<', '>Bitte auswählen …<' => '>' . t('team.select') . '<', '>Zugriff<' => '>' . t('team.access') . '<', '>Teilnehmer<' => '>' . t('team.participant') . '<', '>Reise-Admin<' => '>' . t('team.admin') . '<', '>Speichern<' => '>' . t('team.save') . '<', '>Zugeordnete Nutzer<' => '>' . t('team.assigned') . '<', '>Einladung senden<' => '>' . t('team.invite') . '<', '>Die Rolle in dieser Reise wurde gespeichert.<' => '>' . t('team.saved') . '<', '>Der Nutzer wurde aus der Reise entfernt.<' => '>' . t('team.removed') . '<', '>Aus Reisegruppe entfernen<' => '>' . t('team.remove') . '<', '>Zum Reise-Admin machen<' => '>' . t('team.make_admin') . '<', '>Zum Teilnehmer machen<' => '>' . t('team.make_participant') . '<', '>Aus Reise entfernen<' => '>' . t('team.remove_short') . '<']);
});

ob_start(static function (string $html): string {
    return language() !== 'de' ? str_replace('>← Zurück<', '>' . t('team.back') . '<', $html) : $html;
});
$user = require_login();
$tripId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if (!$tripId) { http_response_code(404); exit('Reise nicht gefunden.'); }

$query = db()->prepare('SELECT * FROM ' . table('trips') . ' WHERE id = :id');
$query->execute([':id' => $tripId]);
$trip = $query->fetch();
if (!$trip) { http_response_code(404); exit('Reise nicht gefunden.'); }

$canManage = $user['role'] === 'main_admin' || (int)$trip['created_by'] === (int)$user['id'];
if (!$canManage) {
    $check = db()->prepare('SELECT 1 FROM ' . table('trip_admins') . ' WHERE trip_id = :trip_id AND user_id = :user_id');
    $check->execute([':trip_id' => $tripId, ':user_id' => $user['id']]);
    $canManage = (bool)$check->fetchColumn();
}
if (!$canManage) { http_response_code(403); exit('Du darfst die Reisegruppe nicht verwalten.'); }

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = (string)($_POST['action'] ?? '');
    $memberId = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
    try {
        if (!$memberId) { throw new RuntimeException('Bitte einen Nutzer auswählen.'); }
        $memberQuery = db()->prepare('SELECT first_name,last_name FROM ' . table('users') . ' WHERE id=:id');
        $memberQuery->execute([':id'=>$memberId]);
        $member = $memberQuery->fetch();
        if (!$member) { throw new RuntimeException('Dieser Nutzer wurde nicht gefunden.'); }
        $memberName = trim($member['first_name'] . ' ' . $member['last_name']);
        if ($action === 'assign') {
            $assignment = (string)($_POST['assignment'] ?? 'participant');
            if (!in_array($assignment, ['participant', 'admin'], true)) { throw new RuntimeException('Bitte eine gültige Rolle auswählen.'); }
            $active = db()->prepare('SELECT id FROM ' . table('users') . " WHERE id = :id AND role <> 'main_admin' AND status = 'active' AND deleted_at IS NULL");
            $active->execute([':id' => $memberId]);
            if (!$active->fetchColumn()) { throw new RuntimeException('Dieser Nutzer ist nicht aktiv oder kann nicht zugeordnet werden.'); }
            $pdo = db();
            $pdo->beginTransaction();
            $pdo->prepare('DELETE FROM ' . table('trip_admins') . ' WHERE trip_id = :trip_id AND user_id = :user_id')->execute([':trip_id' => $tripId, ':user_id' => $memberId]);
            $pdo->prepare('DELETE FROM ' . table('trip_participants') . ' WHERE trip_id = :trip_id AND user_id = :user_id')->execute([':trip_id' => $tripId, ':user_id' => $memberId]);
            $target = $assignment === 'admin' ? 'trip_admins' : 'trip_participants';
            $pdo->prepare('INSERT INTO ' . table($target) . ' (trip_id, user_id) VALUES (:trip_id, :user_id)')->execute([':trip_id' => $tripId, ':user_id' => $memberId]);
            $pdo->commit();
            triptale_log_trip_change($tripId, (int)$user['id'], 'member_assigned', $memberName . ' wurde als ' . ($assignment === 'admin' ? 'Reise-Admin' : 'Teilnehmer') . ' der Reisegruppe zugeordnet.');
            header('Location: /trip-users.php?id=' . $tripId . '&saved=1'); exit;
        }
        if ($action === 'remove') {
            if ((int)$trip['created_by'] === $memberId) { throw new RuntimeException('Der Ersteller der Reise behält den Zugriff.'); }
            $pdo = db();
            $pdo->beginTransaction();
            $pdo->prepare('DELETE FROM ' . table('trip_admins') . ' WHERE trip_id = :trip_id AND user_id = :user_id')->execute([':trip_id' => $tripId, ':user_id' => $memberId]);
            $pdo->prepare('DELETE FROM ' . table('trip_participants') . ' WHERE trip_id = :trip_id AND user_id = :user_id')->execute([':trip_id' => $tripId, ':user_id' => $memberId]);
            $pdo->commit();
            triptale_log_trip_change($tripId, (int)$user['id'], 'member_removed', $memberName . ' wurde aus der Reisegruppe entfernt.');
            header('Location: /trip-users.php?id=' . $tripId . '&removed=1'); exit;
        }
        throw new RuntimeException('Ungültige Anfrage.');
    } catch (Throwable $exception) {
        if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
        $error = $exception instanceof RuntimeException ? $exception->getMessage() : 'Die Zuordnung konnte nicht gespeichert werden.';
    }
}

$people = db()->query("SELECT id, first_name, last_name, email FROM " . table('users') . " WHERE role <> 'main_admin' AND status = 'active' AND deleted_at IS NULL ORDER BY last_name, first_name")->fetchAll();
$members = db()->prepare('SELECT u.id, u.first_name, u.last_name, u.email, u.profile_image, \'admin\' AS assignment FROM ' . table('trip_admins') . ' m JOIN ' . table('users') . ' u ON u.id = m.user_id WHERE m.trip_id = :admin_trip_id UNION ALL SELECT u.id, u.first_name, u.last_name, u.email, u.profile_image, \'participant\' AS assignment FROM ' . table('trip_participants') . ' m JOIN ' . table('users') . ' u ON u.id = m.user_id WHERE m.trip_id = :participant_trip_id ORDER BY last_name, first_name');
$members->execute([':admin_trip_id' => $tripId, ':participant_trip_id' => $tripId]);
$members = $members->fetchAll();
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Reisegruppe · TripTale</title>
<style>
body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:820px;margin:auto;background:#fff;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}.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}.card{padding:16px;margin:12px 0;border:1px solid #d6e0e4;border-left:4px solid #75aeb9;border-radius:10px;background:#f8fafb}.roles{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin:18px 0}.roles .card{margin:0}.actions{display:flex;gap:10px;align-items:end;flex-wrap:wrap}.actions label{flex:1;min-width:190px}.actions select{box-sizing:border-box;width:100%;padding:10px;margin-top:5px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.muted{color:#59636d}.role{font-weight:700;color:#126e82}.delete{background:#9d2d2d}.success{background:#e6f5e9;color:#1d6831;padding:12px;border-radius:8px}.error{background:#ffe6e3;color:#8b2424;padding:12px;border-radius:8px}.member-actions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.member-actions form{margin:0}.member-name{display:flex;align-items:center;gap:10px;font-size:1.05rem}.member-avatar{width:42px;height:42px;flex:0 0 42px;object-fit:cover;border-radius:50%;background:#eaf2f3;border:1px solid #c9dadd}@media(max-width:600px){body{padding:12px}main{padding:16px}.roles{grid-template-columns:1fr}.actions>*{width:100%}.button,button{width:100%;text-align:center;margin-top:8px}.back{display:inline-block!important;width:auto!important;max-width:100%!important;text-align:left!important}.member-actions{display:block}.member-actions form{margin-top:8px}h1{font-size:1.6rem}}
</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main>
<a class="button back" href="/trip.php?id=<?= (int)$tripId ?>">← Zurück</a>
<h1>Reisegruppe</h1><p class="muted"><?= htmlspecialchars($trip['title'], ENT_QUOTES, 'UTF-8') ?></p>
<?php if (isset($_GET['saved'])): ?><p class="success">Die Rolle in dieser Reise wurde gespeichert.</p><?php endif; ?>
<?php if (isset($_GET['removed'])): ?><p class="success">Der Nutzer wurde aus der Reise entfernt.</p><?php endif; ?>
<?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
<div class="roles"><section class="card"><strong>Teilnehmer</strong><p class="muted">Kann die Reise ansehen, Kommentare schreiben und eigene private Notizen führen.</p></section><section class="card"><strong>Reise-Admin</strong><p class="muted">Kann zusätzlich Reise, Tage und Programm bearbeiten sowie das Reiseteam verwalten.</p></section></div>
<section class="card"><h2>Nutzer hinzufügen oder Rolle ändern</h2><form method="post" class="actions"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="action" value="assign"><label>Nutzer<select name="user_id" required><option value="">Bitte auswählen …</option><?php foreach ($people as $person): ?><option value="<?= (int)$person['id'] ?>"><?= htmlspecialchars($person['first_name'] . ' ' . $person['last_name'] . ' · ' . $person['email'], ENT_QUOTES, 'UTF-8') ?></option><?php endforeach; ?></select></label><label>Zugriff<select name="assignment"><option value="participant">Teilnehmer</option><option value="admin">Reise-Admin</option></select></label><button type="submit">Speichern</button></form></section>
<h2>Zugeordnete Nutzer</h2><p><a class="button" href="/trip-invite.php?id=<?= (int)$tripId ?>">Einladung senden</a></p>
<?php foreach ($members as $member): ?><section class="card"><strong class="member-name"><img class="member-avatar" src="/<?= htmlspecialchars((string)($member['profile_image'] ?: 'assets/images/triptale-profile-placeholder.png'), ENT_QUOTES, 'UTF-8') ?>" alt=""><?= htmlspecialchars($member['first_name'] . ' ' . $member['last_name'], ENT_QUOTES, 'UTF-8') ?></strong><p class="muted"><?= htmlspecialchars($member['email'], ENT_QUOTES, 'UTF-8') ?></p><p class="role"><?= $member['assignment'] === 'admin' ? t('team.admin') : t('team.participant') ?><?= (int)$trip['created_by'] === (int)$member['id'] ? ' · ' . t('team.creator') : '' ?></p><?php if ((int)$trip['created_by'] !== (int)$member['id']): ?><div class="member-actions"><form method="post"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="action" value="assign"><input type="hidden" name="user_id" value="<?= (int)$member['id'] ?>"><input type="hidden" name="assignment" value="<?= $member['assignment'] === 'admin' ? 'participant' : 'admin' ?>"><button type="submit"><?= $member['assignment'] === 'admin' ? t('team.make_participant') : t('team.make_admin') ?></button></form><form method="post" onsubmit="return confirm('Diesen Nutzer wirklich aus der Reise entfernen?');"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="action" value="remove"><input type="hidden" name="user_id" value="<?= (int)$member['id'] ?>"><button class="delete" type="submit"><?= t('team.remove_short') ?></button></form></div><?php endif; ?></section><?php endforeach; ?>
<?php if (!$members): ?><p class="muted">Noch niemand außer dem Ersteller ist dieser Reise zugeordnet.</p><?php endif; ?>
</main></body></html>
