<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, ['<html lang="de">' => '<html lang="en">', 'Einladung · TripTale' => t('invite.title') . ' · TripTale', '>Einladung nicht möglich<' => '>' . t('invite_login.title') . '<', '>Anmeldelink anfordern<' => '>' . t('invite_login.request') . '<']);
});
$id=filter_input(INPUT_GET,'id',FILTER_VALIDATE_INT,['options'=>['min_range'=>1]]);$token=(string)($_GET['token']??'');$error=null;
if(!$id||!preg_match('/^[a-f0-9]{64}$/',$token)){$error=t('invite_login.error_invalid');}
else{try{$pdo=db();$pdo->beginTransaction();$q=$pdo->prepare('SELECT i.id,i.token_hash,i.user_id,i.trip_id FROM '.table('trip_invitations').' i JOIN '.table('users').' u ON u.id=i.user_id WHERE i.id=:id AND i.accepted_at IS NULL AND i.revoked_at IS NULL AND i.expires_at>NOW() AND u.status=\'active\' AND u.deleted_at IS NULL FOR UPDATE');$q->execute([':id'=>$id]);$invite=$q->fetch();if(!$invite||!hash_equals($invite['token_hash'],hash('sha256',$token))){$pdo->rollBack();$error=t('invite_login.error_invalid');}else{$pdo->prepare('UPDATE '.table('trip_invitations').' SET accepted_at=NOW() WHERE id=:id')->execute([':id'=>$id]);$pdo->commit();start_session();session_regenerate_id(true);$_SESSION['user_id']=(int)$invite['user_id'];$_SESSION['login_expires_at']=time()+(14*24*60*60);header('Location: /trip.php?id='.(int)$invite['trip_id']);exit;}}catch(Throwable $exception){if(isset($pdo)&&$pdo->inTransaction()){$pdo->rollBack();}$error=t('invite_login.error_check');}}
?><!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Einladung · TripTale</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:520px;margin:auto;background:#fff;padding:28px;border-radius:14px}.error{background:#ffe6e3;padding:12px;border-radius:7px}.button{display:inline-block;background:#126e82;color:#fff;padding:10px 14px;border-radius:7px;text-decoration:none;font-weight:700}</style></head><body><main><h1>Einladung nicht möglich</h1><p class="error"><?=htmlspecialchars((string)$error,ENT_QUOTES,'UTF-8')?></p><a class="button" href="/login.php">Anmeldelink anfordern</a></main></body></html>
