<?php
require_once __DIR__.'/../app/bootstrap.php';
require_once __DIR__.'/_layout.php';
$user = require_superadmin($pdo);
csrf_check();
$message = '';
$ok = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $targetId = (int)($_POST['user_id'] ?? 0);
    if ($action === 'create') {
        [$ok, $message] = register_user($pdo, $_POST['email'] ?? '', $_POST['password'] ?? '', $_POST['role'] ?? 'user', true, $_POST['name'] ?? '');
    } elseif ($action === 'role') {
        [$ok, $message] = set_user_role($pdo, $targetId, $_POST['role'] ?? 'user', (int)$user['id']);
        if ($targetId === (int)$user['id']) $user = current_user($pdo);
    } elseif ($action === 'delete') {
        $stmt = $pdo->prepare('SELECT id, role FROM '.qtbl('users').' WHERE id = ?');
        $stmt->execute([$targetId]);
        $target = $stmt->fetch();
        if (!$target) {
            $message = 'Benutzer nicht gefunden.';
        } elseif ((int)$target['id'] === (int)$user['id']) {
            $message = 'Das eigene Konto bitte unter Konto löschen entfernen.';
        } elseif (($target['role'] ?? 'user') === 'superadmin' && superadmin_count($pdo) <= 1) {
            $message = 'Der letzte Superadmin kann nicht gelöscht werden.';
        } elseif (($_POST['confirm_delete'] ?? '') !== 'LÖSCHEN') {
            $message = 'Bitte LÖSCHEN ins Bestätigungsfeld schreiben.';
        } else {
            delete_user_completely($pdo, $targetId);
            $ok = true;
            $message = 'Benutzer, QR-Codes und Statistikdaten wurden gelöscht.';
        }
    }
}

$stmt = $pdo->query('SELECT u.id, u.name, u.email, u.role, u.email_verified_at, u.created_at, COUNT(q.id) AS qr_count, COALESCE(SUM(q.scan_count),0) AS scan_count FROM '.qtbl('users').' u LEFT JOIN '.qtbl('qr_codes').' q ON q.user_id = u.id GROUP BY u.id ORDER BY u.created_at DESC');
$users = $stmt->fetchAll();
page_header('Benutzerverwaltung');
if ($message) echo '<p class="notice '.($ok?'ok':'').'">'.e($message).'</p>';
?>
<section class="card formgrid">
<h2>Benutzer erstellen</h2>
<form method="post" class="formgrid">
<input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
<input type="hidden" name="action" value="create">
<label>Name <span class="muted">optional</span><input name="name" maxlength="100" value="<?= e((($_POST['action'] ?? '')==='create') ? ($_POST['name'] ?? '') : '') ?>"></label><label>E-Mail<input name="email" type="email" required value="<?= e((($_POST['action'] ?? '')==='create') ? ($_POST['email'] ?? '') : '') ?>"></label>
<label>Passwort<span class="password-field"><input name="password" type="password" minlength="12" required data-password-toggle><button type="button" class="password-toggle" data-password-toggle-button aria-label="Passwort anzeigen" aria-pressed="false"><span class="eye-open" aria-hidden="true">&#128065;</span><span class="eye-closed" aria-hidden="true">&#128584;</span></button></span></label>
<label>Rolle<select name="role"><option value="user" <?= ((($_POST['role'] ?? 'user')==='user') ? 'selected' : '') ?>>Benutzer</option><option value="superadmin" <?= ((($_POST['role'] ?? '')==='superadmin') ? 'selected' : '') ?>>Superadmin</option></select></label>
<button class="btn">Benutzer erstellen</button>
</form>
</section>

<table class="table"><thead><tr><th>Benutzer</th><th>Rolle</th><th>QR-Codes</th><th>Scans</th><th>Aktionen</th></tr></thead><tbody>
<?php foreach($users as $u): ?>
<tr>
<td><strong><?= e($u['name'] ?: $u['email']) ?></strong><div class="muted"><?= e($u['email']) ?> · Erstellt: <?= e($u['created_at']) ?><?= (int)$u['id']===(int)$user['id'] ? ' · du' : '' ?></div></td>
<td><?= e($u['role']) ?><div class="muted"><?= !empty($u['email_verified_at']) ? 'bestätigt' : 'unbestätigt' ?></div></td>
<td><?= (int)$u['qr_count'] ?></td>
<td><?= (int)$u['scan_count'] ?></td>
<td class="actions">
<form method="post" class="inlineform">
<input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
<input type="hidden" name="action" value="role">
<input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
<select name="role"><option value="user" <?= $u['role']==='user'?'selected':'' ?>>Benutzer</option><option value="superadmin" <?= $u['role']==='superadmin'?'selected':'' ?>>Superadmin</option></select>
<button class="btn small">Rolle speichern</button>
</form>
<?php if((int)$u['id'] !== (int)$user['id']): ?>
<form method="post" class="inlineform" data-confirm="Benutzer und alle zugehörigen QR-Codes endgültig löschen?">
<input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
<input name="confirm_delete" placeholder="LÖSCHEN" required>
<button class="btn danger small">Löschen</button>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody></table>
<?php page_footer(); ?>
