<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
$user=require_login();
$transferNotice = isset($_GET['main_admin_transferred']) ? t('main_admin_transfer.success') : null;
ob_start(static function (string $html) use ($transferNotice): string {
    if ($transferNotice === null) { return $html; }
    return preg_replace('#</h1>#', '</h1><p class="success">' . htmlspecialchars($transferNotice, ENT_QUOTES, 'UTF-8') . '</p>', $html, 1) ?? $html;
});
ob_start(static function (string $html): string {
    $labels = ['de'=>'Konto löschen', 'en'=>'Delete account', 'fr'=>'Supprimer le compte', 'es'=>'Eliminar cuenta', 'it'=>'Elimina account', 'nl'=>'Account verwijderen'];
    $label = $labels[language()] ?? $labels['de'];
    return str_replace('</form></main>', '</form><p><a class="button" style="background:#9d2d2d;color:#fff" href="/account-delete.php">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</a></p></main>', $html);
});
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, ['<html lang="de">' => '<html lang="en">', 'Mein Profil · TripTale' => t('profile.title') . ' · TripTale', '>← Zurück<' => '>' . t('profile.back') . '<', '>Profilbild bearbeiten<' => '>' . t('profile.image_edit') . '<', '>Einstellungen<' => '>' . t('profile.settings') . '<', '>Mein Profil<' => '>' . t('profile.title') . '<', '>Deine Mobilnummer wurde gespeichert.<' => '>' . t('profile.mobile_saved') . '<', '>Die Bestätigungs-E-Mail wurde versendet. Bitte bestätige die neue Adresse innerhalb von 24 Stunden. Bis dahin bleibt die bisherige Adresse aktiv.<' => '>' . t('profile.email_sent') . '<', 'Für <strong>' => t('profile.pending') . '<strong>', '> wartet noch eine Bestätigung per E-Mail.<' => '>', '>E-Mail-Adresse<input' => '>' . t('profile.email') . '<input', '>Bei einer Änderung erhältst du an die neue Adresse einen Bestätigungslink. Erst nach der Bestätigung wird die Adresse übernommen.<' => '>' . t('profile.email_hint') . '<', '>Mobilnummer <span' => '>' . t('profile.mobile') . ' <span', '>(optional)<' => '>' . t('common.optional') . '<', '>Änderungen speichern<' => '>' . t('profile.save') . '<']);
});
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return preg_replace_callback('#<p class="notice">Für <strong>([^<]+)</strong> wartet noch eine Bestätigung per E-Mail\.</p>#', static function (array $match): string {
        return '<p class="notice">' . htmlspecialchars(str_replace('{email}', $match[1], t('profile.pending')), ENT_QUOTES, 'UTF-8') . '</p>';
    }, $html) ?? $html;
});
$query=db()->prepare('SELECT first_name,last_name,email,phone,preferred_language FROM '.table('users').' WHERE id=:id');$query->execute([':id'=>$user['id']]);$current=$query->fetch();if(!$current){http_response_code(404);exit('Nutzer nicht gefunden.');}
$error=null;
if($_SERVER['REQUEST_METHOD']==='POST'){
    verify_csrf();$email=strtolower(trim((string)($_POST['email']??'')));$phone=trim((string)($_POST['phone']??''));
    if(!filter_var($email,FILTER_VALIDATE_EMAIL)){$error=t('profile.error_email');}
    elseif(mb_strlen($phone)>50){$error=t('profile.error_mobile');}
    elseif($email===strtolower((string)$current['email'])){db()->prepare('UPDATE '.table('users').' SET phone=:phone WHERE id=:id')->execute([':phone'=>$phone?:null,':id'=>$user['id']]);header('Location: /profile.php?saved=1');exit;}
    else{try{
        $exists=db()->prepare('SELECT id FROM '.table('users').' WHERE email=:email AND id<>:id LIMIT 1');$exists->execute([':email'=>$email,':id'=>$user['id']]);
        if($exists->fetchColumn()){$error=t('profile.error_used');}else{
            $token=bin2hex(random_bytes(32));$pdo=db();$pdo->beginTransaction();
            $pdo->prepare('DELETE FROM '.table('email_change_tokens').' WHERE expires_at<NOW() OR used_at IS NOT NULL OR user_id=:user_id')->execute([':user_id'=>$user['id']]);
            $insert=$pdo->prepare('INSERT INTO '.table('email_change_tokens').' (user_id,new_email,token_hash,expires_at) VALUES (:user_id,:new_email,:token_hash,DATE_ADD(NOW(),INTERVAL 24 HOUR))');$insert->execute([':user_id'=>$user['id'],':new_email'=>$email,':token_hash'=>hash('sha256',$token)]);$tokenId=(int)$pdo->lastInsertId();$pdo->commit();
            $url='https://triptale.willhoff.de/confirm-email.php?id='.$tokenId.'&token='.$token;$mailLanguage=(string)($current['preferred_language']??'de');$message=str_replace(['{name}','{url}','\\n'],[(string)$current['first_name'],$url,PHP_EOL],t_in_language('profile.mail_body',$mailLanguage));
            if(!triptale_send_mail($email,t_in_language('profile.mail_subject',$mailLanguage),$message)){throw new RuntimeException(triptale_mail_failure_message('profile.error_mail'));}
            db()->prepare('UPDATE '.table('users').' SET phone=:phone WHERE id=:id')->execute([':phone'=>$phone?:null,':id'=>$user['id']]);header('Location: /profile.php?mail_sent=1');exit;
        }
    }catch(Throwable $exception){if(isset($pdo)&&$pdo->inTransaction()){$pdo->rollBack();}$error=$exception instanceof RuntimeException?$exception->getMessage():t('profile.error_prepare');}}
}
$pending=null;try{$pendingQuery=db()->prepare('SELECT new_email,expires_at FROM '.table('email_change_tokens').' WHERE user_id=:user_id AND used_at IS NULL AND expires_at>NOW() ORDER BY id DESC LIMIT 1');$pendingQuery->execute([':user_id'=>$user['id']]);$pending=$pendingQuery->fetch()?:null;}catch(Throwable $exception){}
$roleLabel = t(($user['role'] ?? '') === 'main_admin' ? 'users.role_main_admin' : (($user['role'] ?? '') === 'admin' ? 'users.role_admin' : 'users.role_participant'));
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Mein Profil · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:620px;margin:auto;background:#fff;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}.button,button{display:inline-block;padding:10px 13px;background:#126e82;color:#fff;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700;cursor:pointer}.back{background:#e3ebee;color:#126e82}.settings{margin-left:8px}.back+h1{margin-top:26px}label{display:block;margin-top:18px;font-weight:700}input{box-sizing:border-box;width:100%;padding:11px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.muted,.hint{color:#59636d}.role-badge{display:inline-block;margin-left:8px;padding:4px 9px;border:1px solid #126e82;border-radius:999px;background:#e3ebee;color:#126e82;font-size:.82rem;font-weight:700;vertical-align:middle}.hint{font-size:.92rem;margin:6px 0 0}.save{margin-top:22px}.success,.notice,.error{padding:12px;border-radius:8px}.success{background:#e6f5e9;color:#1d6831}.notice{background:#eef5f8;color:#28556d}.error{background:#ffe6e3;color:#8b2424}@media(max-width:600px){body{padding:12px}main{padding:16px}.back,.settings{display:inline-block!important;width:auto!important;max-width:100%!important;margin:0 6px 0 0}.back+h1{margin-top:22px}.role-badge{margin:6px 0 0;display:table}.save{width:100%}}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/dashboard.php">← Zurück</a><?php if($user['role']==='main_admin'):?><a class="button settings" href="/settings.php">Einstellungen</a><?php endif;?><h1>Mein Profil</h1><p class="muted"><?=htmlspecialchars($current['first_name'].' '.$current['last_name'],ENT_QUOTES,'UTF-8')?> <span class="role-badge"><?=htmlspecialchars($roleLabel,ENT_QUOTES,'UTF-8')?></span></p><?php if(isset($_GET['saved'])):?><p class="success">Deine Mobilnummer wurde gespeichert.</p><?php endif;?><?php if(isset($_GET['mail_sent'])):?><p class="success">Die Bestätigungs-E-Mail wurde versendet. Bitte bestätige die neue Adresse innerhalb von 24 Stunden. Bis dahin bleibt die bisherige Adresse aktiv.</p><?php endif;?><?php if($pending):?><p class="notice">Für <strong><?=htmlspecialchars($pending['new_email'],ENT_QUOTES,'UTF-8')?></strong> wartet noch eine Bestätigung per E-Mail.</p><?php endif;?><?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>E-Mail-Adresse<input type="email" name="email" required value="<?=htmlspecialchars((string)($_POST['email']??$current['email']),ENT_QUOTES,'UTF-8')?>"></label><p class="hint">Bei einer Änderung erhältst du an die neue Adresse einen Bestätigungslink. Erst nach der Bestätigung wird die Adresse übernommen.</p><label>Mobilnummer <span class="muted">(optional)</span><input name="phone" value="<?=htmlspecialchars((string)($_POST['phone']??$current['phone']??''),ENT_QUOTES,'UTF-8')?>"></label><button class="save" type="submit">Änderungen speichern</button></form></main></body></html>
