<?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">', 'Einladungen · TripTale' => t('invite.title') . ' · TripTale', '>← Zurück zur Reise<' => '>' . t('team.back') . '<', '>Einladungen<' => '>' . t('invite.title') . '<', '>Für <' => '>' . t('invite.for') . ' <', 'Für ' => t('invite.for') . ' ', '>Einladung an <' => '>' . t('invite.to') . '<', '>Einladungslink<' => '>' . t('invite.link') . '<', '>Du kannst den Link zusätzlich direkt weitergeben. Er ist 24 Stunden gültig.<' => '>' . t('invite.link_hint') . '<', '>Link kopieren<' => '>' . t('invite.copy') . '<', '>Neue Einladung senden<' => '>' . t('invite.new') . '<', '>Bitte auswählen …<' => '>' . t('team.select') . '<', '>Einladung per E-Mail senden<' => '>' . t('invite.send_email') . '<', '>Einladungsstatus<' => '>' . t('invite.status') . '<', '>Alle aktiven Nutzer sind bereits dieser Reise zugeordnet.<' => '>' . t('invite.all_assigned') . '<', '>Einladung senden<' => '>' . t('invite.send') . '<', '>Einladung erneut senden<' => '>' . t('invite.resend') . '<', '>Noch nicht eingeladen<' => '>' . t('invite.not_yet') . '<', '>Abgelaufen<' => '>' . t('invite.expired') . '<', '>Durch neuere Einladung ersetzt<' => '>' . t('invite.replaced') . '<', 'Angenommen am ' => t('invite.accepted') . ' ', 'Offen bis ' => t('invite.open_until') . ' ', "copy.textContent='Link kopiert'" => "copy.textContent=" . json_encode(t('invite.copied'), JSON_UNESCAPED_UNICODE)]);
});
ob_start(static function (string $html): string {
    return language() !== 'de' ? str_replace('>← Zur Reisegruppe<', '>' . t('team.back_to_group') . '<', $html) : $html;
});
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return preg_replace_callback('#<p class="success">Einladung an ([^<]+) wurde per E-Mail versendet\.</p>#', static function (array $match): string {
        return '<p class="success">' . htmlspecialchars(str_replace('{name}', $match[1], t('invite.sent_to')), ENT_QUOTES, 'UTF-8') . '</p>';
    }, $html) ?? $html;
});
$user=require_login();$tripId=filter_input(INPUT_GET,'id',FILTER_VALIDATE_INT,['options'=>['min_range'=>1]]);if(!$tripId){exit('Reise nicht gefunden.');}
$q=db()->prepare('SELECT id,title,created_by FROM '.table('trips').' WHERE id=:id');$q->execute([':id'=>$tripId]);$trip=$q->fetch();if(!$trip){exit('Reise nicht gefunden.');}
$canManage=$user['role']==='main_admin'||(int)$trip['created_by']===(int)$user['id'];if(!$canManage){$q=db()->prepare('SELECT 1 FROM '.table('trip_admins').' WHERE trip_id=:trip AND user_id=:user');$q->execute([':trip'=>$tripId,':user'=>$user['id']]);$canManage=(bool)$q->fetchColumn();}if(!$canManage){http_response_code(403);exit('Du darfst keine Einladungen für diese Reise senden.');}
$membersSql='SELECT u.id,u.first_name,u.last_name,u.email,u.preferred_language FROM '.table('users').' u WHERE u.status=\'active\' AND u.deleted_at IS NULL AND (EXISTS(SELECT 1 FROM '.table('trip_admins').' a WHERE a.trip_id=:trip_a AND a.user_id=u.id) OR EXISTS(SELECT 1 FROM '.table('trip_participants').' p WHERE p.trip_id=:trip_p AND p.user_id=u.id)) ORDER BY u.last_name,u.first_name';$q=db()->prepare($membersSql);$q->execute([':trip_a'=>$tripId,':trip_p'=>$tripId]);$members=$q->fetchAll();
$q=db()->prepare('SELECT u.id,u.first_name,u.last_name,u.email,u.preferred_language FROM '.table('users').' u WHERE u.role<>\'main_admin\' AND u.status=\'active\' AND u.deleted_at IS NULL AND NOT EXISTS(SELECT 1 FROM '.table('trip_admins').' a WHERE a.trip_id=:trip_a AND a.user_id=u.id) AND NOT EXISTS(SELECT 1 FROM '.table('trip_participants').' p WHERE p.trip_id=:trip_p AND p.user_id=u.id) ORDER BY u.last_name,u.first_name');$q->execute([':trip_a'=>$tripId,':trip_p'=>$tripId]);$available=$q->fetchAll();
$error=null;$sentTo=null;$inviteUrl=null;
if($_SERVER['REQUEST_METHOD']==='POST'){
    verify_csrf();
    $memberId=filter_input(INPUT_POST,'user_id',FILTER_VALIDATE_INT,['options'=>['min_range'=>1]]);
    $member=null;$isNew=false;
    foreach($available as $candidate){if((int)$candidate['id']===$memberId){$member=$candidate;$isNew=true;break;}}
    if(!$member){foreach($members as $candidate){if((int)$candidate['id']===$memberId){$member=$candidate;break;}}}
    if(!$member){$error=t('invite.error_select_user');}
    else{try{
        $token=bin2hex(random_bytes(32));$pdo=db();$pdo->beginTransaction();
        if($isNew){$pdo->prepare('INSERT INTO '.table('trip_participants').' (trip_id,user_id) VALUES (:trip,:user)')->execute([':trip'=>$tripId,':user'=>$memberId]);}
        $pdo->prepare('UPDATE '.table('trip_invitations').' SET revoked_at=NOW() WHERE trip_id=:trip AND user_id=:user AND accepted_at IS NULL AND revoked_at IS NULL')->execute([':trip'=>$tripId,':user'=>$memberId]);
        $q=$pdo->prepare('INSERT INTO '.table('trip_invitations').' (trip_id,user_id,sent_by,token_hash,expires_at) VALUES (:trip,:user,:sender,:token,DATE_ADD(NOW(),INTERVAL 24 HOUR))');
        $q->execute([':trip'=>$tripId,':user'=>$memberId,':sender'=>$user['id'],':token'=>hash('sha256',$token)]);
        $inviteId=(int)$pdo->lastInsertId();$pdo->commit();
        $inviteUrl='https://triptale.willhoff.de/trip-invite-login.php?id='.$inviteId.'&token='.$token;
        $mailLanguage=(string)($member['preferred_language']??'de');
        $mail=str_replace(['{name}','{trip}','{url}','\\n'],[(string)$member['first_name'],(string)$trip['title'],$inviteUrl,PHP_EOL],t_in_language('invite.mail_body',$mailLanguage));
        $subject=str_replace('{trip}',(string)$trip['title'],t_in_language('invite.mail_subject',$mailLanguage));
        if(!triptale_send_mail($member['email'],$subject,$mail)){throw new RuntimeException(triptale_mail_failure_message('invite.error_mail'));}
        triptale_log_trip_change($tripId,(int)$user['id'],'invite_sent','Eine Einladung wurde an '.$member['first_name'].' '.$member['last_name'].' gesendet.');
        $sentTo=$member['first_name'].' '.$member['last_name'];
    }catch(Throwable $exception){if(isset($pdo)&&$pdo->inTransaction())$pdo->rollBack();$error=$exception instanceof RuntimeException?$exception->getMessage():t('invite.error_create');}}
}
$status=db()->prepare('SELECT * FROM '.table('trip_invitations').' WHERE trip_id=:trip AND user_id=:user ORDER BY sent_at DESC LIMIT 1');foreach($members as &$member){$status->execute([':trip'=>$tripId,':user'=>$member['id']]);$member['invite']=$status->fetch()?:null;}unset($member);
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Einladungen · 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}.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}.back+h1{margin-top:26px}label{display:block;margin-top:22px;font-weight:700}select,input{box-sizing:border-box;width:100%;padding:11px;margin-top:12px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}.success,.error{padding:12px;border-radius:8px}.success{background:#e6f5e9;color:#1d6831}.error{background:#ffe6e3;color:#8b2424}.muted{color:#59636d}.invite{margin:14px 0;padding:15px;border:1px solid #d6e0e4;border-left:4px solid #75aeb9;border-radius:10px;background:#f8fafb}.invite h2{font-size:1.05rem;margin:0 0 4px}.status{display:inline-block;margin-top:7px;padding:3px 8px;border-radius:99px;font-size:.86rem;font-weight:700;background:#edf0f2;color:#59636d}.status.open{background:#fff3d9;color:#805c14}.status.accepted{background:#e6f5e9;color:#1d6831}.invite-actions{margin-top:12px}.link-box{margin:14px 0;padding:14px;background:#edf5f6;border-left:4px solid #75aeb9;border-radius:9px}.link-row{display:flex;gap:8px;align-items:center}.link-row input{margin:0;min-width:0}.link-row button{flex:0 0 auto}@media(max-width:600px){body{padding:12px}main{padding:16px}.button:not(.back),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}.link-row{display:block}.link-row button{width:100%;margin-top:8px}}</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main><a class="button back" href="/trip-users.php?id=<?= (int)$tripId ?>">← Zur Reisegruppe</a><h1>Einladungen</h1><p class="muted">Für <?=htmlspecialchars($trip['title'],ENT_QUOTES,'UTF-8')?></p><?php if($sentTo):?><p class="success">Einladung an <?=htmlspecialchars($sentTo,ENT_QUOTES,'UTF-8')?> wurde per E-Mail versendet.</p><?php endif;?><?php if($error):?><p class="error"><?=htmlspecialchars($error,ENT_QUOTES,'UTF-8')?></p><?php endif;?><?php if($inviteUrl):?><section class="link-box"><strong>Einladungslink</strong><p class="muted">Du kannst den Link zusätzlich direkt weitergeben. Er ist 24 Stunden gültig.</p><div class="link-row"><input id="invite-link" readonly value="<?=htmlspecialchars($inviteUrl,ENT_QUOTES,'UTF-8')?>"><button type="button" id="copy-link">Link kopieren</button></div></section><?php endif;?><?php if($available):?><form method="post"><input type="hidden" name="csrf_token" value="<?=htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8')?>"><label>Neue Einladung senden<select name="user_id" required><option value="">Bitte auswählen …</option><?php foreach($available 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><button>Einladung per E-Mail senden</button></form><?php else:?><p class="muted">Alle aktiven Nutzer sind bereits dieser Reise zugeordnet.</p><?php endif;?><h2>Einladungsstatus</h2><?php foreach($members as $member):$invite=$member['invite'];$statusText='Noch nicht eingeladen';$class='';if($invite){if($invite['accepted_at']){$statusText='Angenommen am '.date('d.m.Y H:i',strtotime($invite['accepted_at']));$class='accepted';}elseif($invite['revoked_at']){$statusText='Durch neuere Einladung ersetzt';}elseif(strtotime($invite['expires_at'])<time()){$statusText='Abgelaufen';}else{$statusText='Offen bis '.date('d.m.Y H:i',strtotime($invite['expires_at']));$class='open';}}?><section class="invite"><h2><?=htmlspecialchars($member['first_name'].' '.$member['last_name'],ENT_QUOTES,'UTF-8')?></h2><div class="muted"><?=htmlspecialchars($member['email'],ENT_QUOTES,'UTF-8')?></div><span class="status <?= $class ?>"><?=htmlspecialchars($statusText,ENT_QUOTES,'UTF-8')?></span><form class="invite-actions" method="post"><input type="hidden" name="csrf_token" value="<?=htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8')?>"><input type="hidden" name="user_id" value="<?= (int)$member['id'] ?>"><button><?= $invite?'Einladung erneut senden':'Einladung senden' ?></button></form></section><?php endforeach;?></main><script>var copy=document.getElementById('copy-link');if(copy)copy.addEventListener('click',function(){var link=document.getElementById('invite-link');link.select();navigator.clipboard&&navigator.clipboard.writeText(link.value);copy.textContent='Link kopiert';});</script></body></html>
