<?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 bearbeiten · TripTale' => t('user_form.edit_title') . ' · TripTale', '>← Zurück<' => '>' . t('users.back') . '<', '>Nutzer bearbeiten<' => '>' . t('user_form.edit_title') . '<', '>Neuen Nutzer anlegen<' => '>' . t('user_form.new_title') . '<', '>Der Nutzer meldet sich später ausschließlich über einen Anmeldelink an, den er per E-Mail anfordert.<' => '>' . t('user_form.hint') . '<', '>Vorname<input' => '>' . t('user_form.first_name') . '<input', '>Nachname<input' => '>' . t('user_form.last_name') . '<input', '>E-Mail-Adresse<input' => '>' . t('user_form.email') . '<input', '>Mobil <span' => '>' . t('user_form.mobile') . ' <span', '>(optional)<' => '>' . t('common.optional') . '<', '>Rolle<select' => '>' . t('user_form.role') . '<select', '>Status<select' => '>' . t('user_form.status') . '<select', '>Der Hauptadministrator bleibt aktiv und kann seine Rolle nicht ändern.<' => '>' . t('user_form.main_admin_locked') . '<', '>Teilnehmer<' => '>' . t('users.role_participant') . '<', '>Administrator<' => '>' . t('users.role_admin') . '<', '>Aktiv<' => '>' . t('users.active') . '<', '>Deaktiviert<' => '>' . t('users.inactive') . '<', '>Speichern<' => '>' . t('common.save') . '<']);
});
if ($user['role'] !== 'main_admin') { http_response_code(403); exit('Kein Zugriff.'); }
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$entry = ['first_name'=>'','last_name'=>'','email'=>'','phone'=>'','role'=>'participant','status'=>'active'];
if ($id) {
    $query = db()->prepare('SELECT id,first_name,last_name,email,phone,role,status FROM '.table('users').' WHERE id=:id AND deleted_at IS NULL');
    $query->execute([':id'=>$id]); $entry=$query->fetch();
    if (!$entry) { http_response_code(404); exit(t('users.error_missing')); }
}
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $firstName=trim((string)($_POST['first_name']??''));
    $lastName=trim((string)($_POST['last_name']??''));
    $email=strtolower(trim((string)($_POST['email']??'')));
    $phone=trim((string)($_POST['phone']??''));
    $role=(string)($_POST['role']??'participant');
    $status=(string)($_POST['status']??'active');
    if ($id && $entry['role']==='main_admin') { $role='main_admin'; $status='active'; }
    if ($firstName==='' || $lastName==='') { $error=t('user_form.error_name'); }
    elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $error=t('user_form.error_email'); }
    elseif (!in_array($role, ['admin','participant','main_admin'], true) || !in_array($status, ['active','inactive'], true)) { $error=t('user_form.error_choice'); }
    else {
        $duplicate=db()->prepare('SELECT id FROM '.table('users').' WHERE email=:email AND id<>:id AND deleted_at IS NULL');
        $duplicate->execute([':email'=>$email,':id'=>$id?:0]);
        if ($duplicate->fetch()) { $error=t('user_form.error_duplicate'); }
        else {
            try {
                if ($id) {
                    $sql='UPDATE '.table('users').' SET first_name=:first_name,last_name=:last_name,email=:email,phone=:phone,role=:role,status=:status';
                    $parameters=[':first_name'=>$firstName,':last_name'=>$lastName,':email'=>$email,':phone'=>$phone?:null,':role'=>$role,':status'=>$status,':id'=>$id];
                    $sql.=' WHERE id=:id'; db()->prepare($sql)->execute($parameters);
                } else {
                    db()->prepare('INSERT INTO '.table('users').' (first_name,last_name,email,phone,role,status,created_by) VALUES (:first_name,:last_name,:email,:phone,:role,:status,:created_by)')->execute([':first_name'=>$firstName,':last_name'=>$lastName,':email'=>$email,':phone'=>$phone?:null,':role'=>$role==='main_admin'?'participant':$role,':status'=>$status,':created_by'=>$user['id']]);
                }
                header('Location: /users.php?saved=1'); exit;
            } catch (Throwable $exception) { $error=t('user_form.error_save'); }
        }
    }
}
$value=static fn(string $key): string => (string)($_POST[$key] ?? $entry[$key] ?? '');
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Nutzer bearbeiten · TripTale</title>
<style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:720px;margin:auto;background:#fff;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}label{display:block;margin-top:16px;font-weight:700}input,select{box-sizing:border-box;width:100%;padding:11px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.button,.save{display:inline-block;padding:9px 12px;background:#126e82;color:#fff;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700}.back{background:#e3ebee;color:#126e82}.save{margin-top:22px}.hint{color:#59636d;font-size:.92rem}.locked{padding:11px;background:#edf2f3;border-radius:7px}.error{background:#ffe6e3;padding:12px;border-radius:7px}@media(max-width:600px){body{padding:12px}main{padding:16px}h1{font-size:1.6rem}}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main>
<a class="button back" href="/users.php">← Zurück</a><h1><?= $id ? 'Nutzer bearbeiten' : 'Neuen Nutzer anlegen' ?></h1><p class="hint">Der Nutzer meldet sich später ausschließlich über einen Anmeldelink an, den er per E-Mail anfordert.</p><?php if($error): ?><p class="error"><?= htmlspecialchars($error,ENT_QUOTES,'UTF-8') ?></p><?php endif; ?>
<form method="post"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8') ?>"><label>Vorname<input name="first_name" required value="<?= htmlspecialchars($value('first_name'),ENT_QUOTES,'UTF-8') ?>"></label><label>Nachname<input name="last_name" required value="<?= htmlspecialchars($value('last_name'),ENT_QUOTES,'UTF-8') ?>"></label><label>E-Mail-Adresse<input type="email" name="email" required value="<?= htmlspecialchars($value('email'),ENT_QUOTES,'UTF-8') ?>"></label><label>Mobil <span class="hint">(optional)</span><input name="phone" value="<?= htmlspecialchars($value('phone'),ENT_QUOTES,'UTF-8') ?>"></label><?php if($id && $entry['role']==='main_admin'): ?><p class="locked">Der Hauptadministrator bleibt aktiv und kann seine Rolle nicht ändern.</p><?php else: ?><label>Rolle<select name="role"><option value="participant"<?= $value('role')==='participant'?' selected':'' ?>>Teilnehmer</option><option value="admin"<?= $value('role')==='admin'?' selected':'' ?>>Administrator</option></select></label><label>Status<select name="status"><option value="active"<?= $value('status')==='active'?' selected':'' ?>>Aktiv</option><option value="inactive"<?= $value('status')==='inactive'?' selected':'' ?>>Deaktiviert</option></select></label><?php endif; ?><button class="save" type="submit">Speichern</button></form>
</main></body></html>
