<?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 {
    $script = '<script>(function(){var toolbar=document.querySelector(".toolbar");if(!toolbar)return;var buttons=[].slice.call(toolbar.querySelectorAll(":scope > button.button"));if(!buttons.length)return;var actions=document.createElement("div");actions.style.cssText="display:flex;flex-wrap:wrap;gap:12px;margin-top:12px";buttons[0].before(actions);buttons.forEach(function(button){button.style.setProperty("margin","0","important");actions.appendChild(button);});})();</script>';
    return str_replace('</body>', $script . '</body>', $html);
});
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, ['<html lang="de">' => '<html lang="en">', 'Änderungen · TripTale' => t('changes.title') . ' · TripTale', '>← Zur Reise<' => '>' . t('changes.back') . '<', '>Änderungen<' => '>' . t('changes.title') . '<', '>Änderungen sammeln, gemeinsam informieren und anschließend archivieren.<' => '>' . t('changes.intro') . '<', '>Offen<' => '>' . t('changes.open') . '<', '>Archiv<' => '>' . t('changes.archive') . '<', '>Ausgewählte Änderungen<' => '>' . t('changes.selected') . '<', '>Ausgewählte archivierte Änderungen<' => '>' . t('changes.selected_archived') . '<', '>Eine gemeinsame E-Mail enthält alle ausgewählten Einträge. Nach dem Versand werden sie automatisch archiviert.<' => '>' . t('changes.open_hint') . '<', '>Archivierte Einträge können wieder geöffnet oder endgültig gelöscht werden.<' => '>' . t('changes.archive_hint') . '<', '>Gemeinsam per E-Mail senden<' => '>' . t('changes.send') . '<', '>Ohne Mail archivieren<' => '>' . t('changes.archive_without_mail') . '<', '>Wieder öffnen<' => '>' . t('changes.restore') . '<', '>Endgültig löschen<' => '>' . t('changes.delete') . '<', '>Per E-Mail versendet.<' => '>' . t('changes.sent') . '<', '>Keine offenen Änderungen.<' => '>' . t('changes.none_open') . '<', '>Das Archiv ist noch leer.<' => '>' . t('changes.none_archive') . '<', "confirm('Ausgewählte Änderungen wirklich endgültig löschen?')" => 'confirm(' . json_encode(t('changes.confirm_delete'), JSON_UNESCAPED_UNICODE) . ')']);
});
$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.');}
$q=db()->prepare('SELECT 1 FROM '.table('trip_admins').' WHERE trip_id=:a AND user_id=:b UNION SELECT 1 FROM '.table('trip_participants').' WHERE trip_id=:c AND user_id=:d LIMIT 1');$q->execute([':a'=>$tripId,':b'=>$user['id'],':c'=>$tripId,':d'=>$user['id']]);if($user['role']!=='main_admin'&&(int)$trip['created_by']!==(int)$user['id']&&!$q->fetchColumn()){http_response_code(403);exit('Kein Zugriff.');}
$canManage=triptale_can_manage_trip($tripId,$user,(int)$trip['created_by']);$view=($_GET['view']??'')==='archive'?'archive':'open';$notice=isset($_GET['sent']) ? t('changes.sent') : null;$error=isset($_GET['mailerror']) ? (($_GET['mailerror']??'')==='config' ? t('mail.error_not_configured') : t('changes.error_mail')) : null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') === 'send') {
    verify_csrf();
    $ids = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['change_ids'] ?? [])))));
    $customMessage = trim((string)($_POST['custom_message'] ?? ''));
    if (!$canManage) { $error = t('changes.error_select'); }
    else {
        $chosen = [];
        if ($ids) {
            $marks = implode(',', array_fill(0, count($ids), '?'));
            $query = db()->prepare('SELECT id,message FROM ' . table('trip_changes') . ' WHERE trip_id=? AND id IN (' . $marks . ') AND archived_at IS NULL ORDER BY created_at,id');
            $query->execute(array_merge([$tripId], $ids));
            $chosen = $query->fetchAll();
        }
        if ($ids && !$chosen) { $error = t('changes.error_unavailable'); }
        else {
            $recipients = triptale_trip_change_recipients($tripId, (int)$user['id']);
            $changesText = implode(PHP_EOL, array_map(static fn(array $change): string => '• ' . $change['message'], $chosen));
            $sent = 0; $failed = 0;
            foreach ($recipients as $recipient) {
                $locale = (string)($recipient['preferred_language'] ?? 'de');
                $name = trim((string)$recipient['first_name'] . ' ' . (string)$recipient['last_name']);
                $template = $chosen ? ($customMessage !== '' ? t_in_language('changes.mail_body_with_message', $locale) : t_in_language('changes.mail_body', $locale)) : ($customMessage !== '' ? t_in_language('changes.mail_message_body', $locale) : t_in_language('changes.mail_general_body', $locale));
                $body = str_replace(['{name}','{trip}','{changes}','{message}','{url}','\\n'], [$name, (string)$trip['title'], $changesText, $customMessage, triptale_public_url('/trip.php?id='.$tripId), PHP_EOL], $template);
                $subject = str_replace('{trip}', (string)$trip['title'], t_in_language('changes.mail_subject', $locale));
                if (triptale_send_mail((string)$recipient['email'], $subject, $body)) { $sent++; } else { $failed++; }
            }
            if ($failed) { header('Location: /trip-changes.php?id=' . $tripId . '&mailerror=' . (triptale_mail_is_configured(triptale_mail_settings()) ? '1' : 'config')); exit; }
            else {
                if ($chosen) {
                    $marks = implode(',', array_fill(0, count($chosen), '?'));
                    $query = db()->prepare('UPDATE ' . table('trip_changes') . ' SET notification_decided_at=NOW(),notified_at=NOW(),notified_by=?,archived_at=NOW(),archived_by=? WHERE trip_id=? AND id IN (' . $marks . ')');
                    $query->execute(array_merge([(int)$user['id'], (int)$user['id'], $tripId], array_column($chosen, 'id')));
                }
                header('Location: /trip-changes.php?id=' . $tripId . '&sent=' . ($sent ? '1' : '0')); exit;
            }
        }
    }
}
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();$action=(string)($_POST['action']??'');$source=($_POST['source_view']??'')==='archive'?'archive':'open';$ids=array_values(array_unique(array_filter(array_map('intval',(array)($_POST['change_ids']??[])))));if(!$canManage||!$ids||!in_array($action,['send','archive','delete','restore'],true)){$error='Bitte wähle mindestens einen Eintrag aus.';}else{$marks=implode(',',array_fill(0,count($ids),'?'));$archived=($action==='restore'||$source==='archive')?'archived_at IS NOT NULL':'archived_at IS NULL';$q=db()->prepare('SELECT id,message FROM '.table('trip_changes').' WHERE trip_id=? AND id IN ('.$marks.') AND '.$archived.' ORDER BY created_at,id');$q->execute(array_merge([$tripId],$ids));$chosen=$q->fetchAll();if(!$chosen){$error='Die ausgewählten Einträge sind nicht verfügbar.';}elseif($action==='delete'){$q=db()->prepare('DELETE FROM '.table('trip_changes').' WHERE trip_id=? AND id IN ('.$marks.')');$q->execute(array_merge([$tripId],array_column($chosen,'id')));$notice=str_replace('{count}',(string)count($chosen),t('changes.notice_deleted'));}elseif($action==='archive'){$q=db()->prepare('UPDATE '.table('trip_changes').' SET archived_at=NOW(),archived_by=? WHERE trip_id=? AND id IN ('.$marks.')');$q->execute(array_merge([(int)$user['id'],$tripId],array_column($chosen,'id')));$notice=str_replace('{count}',(string)count($chosen),t('changes.notice_archived'));}elseif($action==='restore'){$q=db()->prepare('UPDATE '.table('trip_changes').' SET archived_at=NULL,archived_by=NULL WHERE trip_id=? AND id IN ('.$marks.')');$q->execute(array_merge([$tripId],array_column($chosen,'id')));$notice=count($chosen).' Änderung(en) sind wieder offen.';$view='archive';}else{$recipients=triptale_trip_change_recipients($tripId,(int)$user['id']);$lines=array_map(static fn(array $c):string=>'• '.$c['message'],$chosen);$sent=0;$failed=0;foreach($recipients as$r){$name=trim((string)$r['first_name'].' '.(string)$r['last_name']);$body='Hallo'.($name!==''?' '.$name:'').",\n\nbei der Reise „".$trip['title']."“ gibt es folgende Änderungen:\n\n".implode("\n",$lines)."\n\nZur Reise: ".triptale_public_url('/trip.php?id='.$tripId)."\n\nTripTale";if(@mail((string)$r['email'],'TripTale: Änderungen bei „'.$trip['title'].'“',$body,triptale_mail_headers())){$sent++;}else{$failed++;}}if($failed){$error='Mindestens eine E-Mail konnte nicht versendet werden. Die Einträge bleiben offen.';}else{$q=db()->prepare('UPDATE '.table('trip_changes').' SET notification_decided_at=NOW(),notified_at=NOW(),notified_by=?,archived_at=NOW(),archived_by=? WHERE trip_id=? AND id IN ('.$marks.')');$q->execute(array_merge([(int)$user['id'],(int)$user['id'],$tripId],array_column($chosen,'id')));$notice=$sent?str_replace('{count}',(string)count($chosen),t('changes.notice_sent')):'Es gibt keine weiteren aktiven Personen in der Reisegruppe. Die Änderungen wurden archiviert.';}}}}
$q=db()->prepare('SELECT c.*,u.first_name,u.last_name FROM '.table('trip_changes').' c LEFT JOIN '.table('users').' u ON u.id=c.user_id WHERE c.trip_id=:id AND '.($view==='archive'?'c.archived_at IS NOT NULL':'c.archived_at IS NULL').' ORDER BY c.created_at DESC,c.id DESC');$q->execute([':id'=>$tripId]);$changes=$q->fetchAll();$newId=filter_input(INPUT_GET,'new',FILTER_VALIDATE_INT)?:0;
?><!doctype html><html lang="de"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Änderungen · TripTale</title><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;color:#17202a}main{max-width:800px;margin:34px auto;padding:0 20px}.card,.toolbar{background:#fff;border:1px solid #d6e0e4;border-radius:12px;padding:16px;margin:12px 0;box-shadow:0 3px 12px #00000012}.card{border-left:4px solid #75aeb9}.new{border-left-color:#126e82;background:#f2f8f9}.button{display:inline-block;background:#126e82;color:#fff;border:0;border-radius:7px;padding:10px 13px;text-decoration:none;font:inherit;font-weight:700;cursor:pointer;margin:4px 8px 0 0}.back,.secondary{background:#e3ebee;color:#126e82}.danger{background:#9d2d2d}.hint,.meta{color:#59636d;font-size:.93rem}.check{float:right;width:22px;height:22px;accent-color:#126e82}.success,.error{padding:12px;border-radius:8px}.success{background:#e6f5e9}.error{background:#ffe6e3}.tabs .button{background:#e3ebee;color:#126e82}.tabs .active{background:#126e82;color:#fff}@media(max-width:600px){main{margin:18px auto;padding:0 12px}.check{width:24px;height:24px}}</style><body><main><a class="button back" href="/trip.php?id=<?= (int)$tripId ?>">← Zur Reise</a><h1>Änderungen</h1><p>Änderungen sammeln, gemeinsam informieren und anschließend archivieren.</p><nav class="tabs"><a class="button<?= $view==='open'?' active':'' ?>" href="/trip-changes.php?id=<?= (int)$tripId ?>">Offen</a><a class="button<?= $view==='archive'?' active':'' ?>" href="/trip-changes.php?id=<?= (int)$tripId ?>&view=archive">Archiv</a></nav><?php if($notice):?><p class="success"><?=htmlspecialchars($notice,ENT_QUOTES,'UTF-8')?></p><?php endif;?><?php if($error):?><p class="error"><?=htmlspecialchars($error,ENT_QUOTES,'UTF-8')?></p><?php endif;?><?php if($canManage&&$changes):?><form method="post"><input type="hidden" name="csrf_token" value="<?=htmlspecialchars(csrf_token(),ENT_QUOTES,'UTF-8')?>"><input type="hidden" name="source_view" value="<?=$view?>"><section class="toolbar"><strong><?= $view==='open'?'Ausgewählte Änderungen':'Ausgewählte archivierte Änderungen' ?></strong><p class="hint"><?= $view==='open'?'Eine gemeinsame E-Mail enthält alle ausgewählten Einträge. Nach dem Versand werden sie automatisch archiviert.':'Archivierte Einträge können wieder geöffnet oder endgültig gelöscht werden.' ?></p><?php if($view==='open'):?><button class="button" name="action" value="send">Gemeinsam per E-Mail senden</button><button class="button secondary" name="action" value="archive">Ohne Mail archivieren</button><?php else:?><button class="button secondary" name="action" value="restore">Wieder öffnen</button><?php endif;?><button class="button danger" name="action" value="delete" onclick="return confirm('Ausgewählte Änderungen wirklich endgültig löschen?');">Endgültig löschen</button></section><?php foreach($changes as$c):$author=trim((string)$c['first_name'].' '.(string)$c['last_name']);?><section class="card<?= (int)$c['id']===$newId?' new':''?>"><label><input class="check" type="checkbox" name="change_ids[]" value="<?= (int)$c['id']?>"<?= (int)$c['id']===$newId?' checked':''?>></label><strong><?=htmlspecialchars($c['message'],ENT_QUOTES,'UTF-8')?></strong><p class="meta"><?=htmlspecialchars($author?:'Unbekannt',ENT_QUOTES,'UTF-8')?> · <?=htmlspecialchars(date('d.m.Y · H:i',strtotime($c['created_at'])),ENT_QUOTES,'UTF-8')?></p><?php if($c['notified_at']):?><p class="hint"><b>Per E-Mail versendet.</b></p><?php endif;?></section><?php endforeach;?></form><?php elseif(!$changes):?><section class="card"><p><?= $view==='open'?'Keine offenen Änderungen.':'Das Archiv ist noch leer.'?></p></section><?php endif;?></main></body></html>
