<?php
/** @var array $updateInfo */
/** @var string $currentVersion */
/** @var array $lastInstall */
/** @var bool $preBackupExists */
/** @var string $preBackupPath */
/** @var bool $checkEnabled */
/** @var string $registryUrl */
/** @var string $lastCheckedAt */
/** @var \App\Core\Auth $auth */
/** @var \App\Core\Csrf $csrf */

$latestVersion = $updateInfo['version'] ?? '';
$coreData      = $updateInfo['data'] ?? [];
$releaseNotes  = $coreData['release_notes'] ?? '';
$sizeMb        = !empty($coreData['size_bytes']) ? round($coreData['size_bytes'] / 1024 / 1024, 1) : null;
$isSecurity    = !empty($coreData['security_release']);
$isSigned      = !empty($coreData['signature_b64']);

// Humanize last check timestamp
$lastCheckedHuman = '';
if ($lastCheckedAt !== '') {
    $ts = strtotime($lastCheckedAt);
    if ($ts) {
        $lastCheckedHuman = date('d.m.Y – H:i', $ts) . ' Uhr';
    }
}
?>
<?php ob_start(); ?>

<?php admin_content_header(__('admin.system_updates.title'), 'refresh-cw'); ?>

<style>
/* ============================================================
   System-Updates – Premium-Look for end customers
   ============================================================ */
.su {
    --su-blue: #2563eb;
    --su-blue-dark: #1d4ed8;
    --su-blue-soft: #eff6ff;
    --su-green: #16a34a;
    --su-green-soft: #dcfce7;
    --su-red: #dc2626;
    --su-red-soft: #fee2e2;
    --su-ink: #0f172a;
    --su-text: #334155;
    --su-muted: #64748b;
    --su-border: #e2e8f0;
    --su-border-soft: #f1f5f9;
    --su-bg-card: #ffffff;
    --su-bg-soft: #f8fafc;
    max-width: 980px;
}

.su-alert {
    padding: .9rem 1.15rem;
    border-radius: 10px;
    font-size: .9rem;
    margin-bottom: 1rem;
    border: 1px solid transparent;
}
.su-alert--success { background: var(--su-green-soft); color: #14532d; border-color: #bbf7d0; }
.su-alert--error   { background: var(--su-red-soft);   color: #7f1d1d; border-color: #fecaca; }
.su-alert--info    { background: var(--su-blue-soft);  color: #1e3a8a; border-color: #bfdbfe; }

/* ── Hero-Card: Version comparison + status ────────────────── */
.su-hero {
    background: var(--su-bg-card);
    border: 1px solid var(--su-border);
    border-radius: 14px;
    padding: 1.75rem 2rem;
    margin-bottom: 1.25rem;
    box-shadow: 0 1px 2px rgba(15,23,42,.04), 0 1px 3px rgba(15,23,42,.05);
    display: grid;
    grid-template-columns: 1fr auto;
    gap: 1.5rem;
    align-items: center;
}
.su-hero__versions {
    display: flex; align-items: center; gap: 1.5rem; flex-wrap: wrap;
}
.su-hero__ver {
    display: flex; flex-direction: column;
}
.su-hero__ver-label {
    font-size: .75rem; text-transform: uppercase; letter-spacing: .05em;
    color: var(--su-muted); font-weight: 600;
    margin-bottom: .25rem;
}
.su-hero__ver-num {
    font-size: 2rem; font-weight: 700; color: var(--su-ink);
    font-variant-numeric: tabular-nums; line-height: 1;
}
.su-hero__ver-num--new { color: var(--su-blue); }
.su-hero__arrow { color: #cbd5e1; }
.su-hero__status {
    display: inline-flex; align-items: center; gap: .4rem;
    padding: .45rem .9rem;
    font-size: .85rem; font-weight: 600;
    border-radius: 999px;
}
.su-hero__status--available { background: var(--su-blue-soft); color: #1d4ed8; }
.su-hero__status--uptodate  { background: var(--su-green-soft); color: #14532d; }
.su-hero__status svg { flex-shrink: 0; }
.su-hero__meta {
    font-size: .8rem; color: var(--su-muted);
    margin-top: .75rem;
    display: flex; align-items: center; gap: .4rem;
}
.su-hero__check-form { display: inline-block; }
.su-hero__btn-check {
    display: inline-flex; align-items: center; gap: .4rem;
    padding: .55rem 1rem;
    background: var(--su-bg-card);
    color: var(--su-text) !important;
    border: 1px solid var(--su-border);
    border-radius: 8px;
    font-size: .85rem; font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    transition: background .15s, border-color .15s;
}
.su-hero__btn-check:hover { background: var(--su-bg-soft); border-color: #cbd5e1; }
.su-hero__btn-check svg { color: var(--su-muted); }

/* ── Release Notes Card ────────────────────────────────────── */
.su-card {
    background: var(--su-bg-card);
    border: 1px solid var(--su-border);
    border-radius: 12px;
    margin-bottom: 1.25rem;
    overflow: hidden;
}
.su-card__head {
    display: flex; align-items: center; gap: .5rem;
    padding: 1rem 1.25rem;
    border-bottom: 1px solid var(--su-border-soft);
}
.su-card__head svg { color: var(--su-blue); }
.su-card__title {
    margin: 0;
    font-size: 1rem; font-weight: 600; color: var(--su-ink);
}
.su-card__body { padding: 1.25rem 1.5rem; }

/* Release Notes content styling */
.su-rn { font-size: .9rem; line-height: 1.65; color: var(--su-text); max-height: 360px; overflow-y: auto; }
.su-rn h2, .su-rn h3 { font-size: 1rem; margin: 1rem 0 .5rem; color: var(--su-ink); font-weight: 600; }
.su-rn h2:first-child, .su-rn h3:first-child { margin-top: 0; }
.su-rn p { margin: .5rem 0; }
.su-rn ul, .su-rn ol { padding-left: 1.25rem; margin: .5rem 0; }
.su-rn li { margin: .35rem 0; }
.su-rn li strong { color: var(--su-ink); }
.su-rn a { color: var(--su-blue); }
.su-rn code {
    background: var(--su-bg-soft); border: 1px solid var(--su-border-soft);
    padding: .1rem .4rem; border-radius: 4px; font-size: .85em;
}

/* ── Trust badges row (security guarantees) ────────────────── */
.su-trust {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
    padding: 1.25rem 1.5rem;
    background: var(--su-bg-soft);
    border-top: 1px solid var(--su-border-soft);
}
@media (max-width: 640px) { .su-trust { grid-template-columns: 1fr; } }
.su-trust__item { display: flex; gap: .75rem; align-items: flex-start; }
.su-trust__icon {
    flex: 0 0 36px; height: 36px;
    background: var(--su-bg-card);
    color: var(--su-green);
    border: 1px solid #bbf7d0;
    border-radius: 8px;
    display: flex; align-items: center; justify-content: center;
}
.su-trust__label { font-size: .8rem; font-weight: 600; color: var(--su-ink); margin-bottom: .15rem; }
.su-trust__desc  { font-size: .75rem; color: var(--su-muted); line-height: 1.4; }

/* ── Install Panel ─────────────────────────────────────────── */
.su-install__meta {
    display: flex; flex-wrap: wrap; gap: .5rem;
    margin-bottom: 1rem;
}
.su-chip {
    display: inline-flex; align-items: center; gap: .35rem;
    padding: .3rem .65rem;
    background: var(--su-bg-soft);
    color: var(--su-text);
    border: 1px solid var(--su-border);
    border-radius: 6px;
    font-size: .75rem; font-weight: 600;
}
.su-chip--secure { background: var(--su-green-soft); color: #14532d; border-color: #bbf7d0; }
.su-chip--alert  { background: var(--su-red-soft); color: #7f1d1d; border-color: #fecaca; }
.su-scope {
    display: flex; flex-direction: column; gap: .75rem;
    padding: 1rem 1.25rem;
    background: var(--su-bg-soft);
    border: 1px solid var(--su-border-soft);
    border-radius: 10px;
    margin-bottom: 1.25rem;
}
.su-scope__item { display: flex; align-items: flex-start; gap: .65rem; cursor: pointer; }
.su-scope__item input[type=checkbox] { margin-top: .2rem; width: 16px; height: 16px; cursor: pointer; }
.su-scope__label { font-size: .88rem; font-weight: 600; color: var(--su-ink); }
.su-scope__hint { font-size: .78rem; color: var(--su-muted); display: block; margin-top: .1rem; }
.su-scope__pflicht {
    display: inline-block;
    margin-left: .35rem;
    padding: .1rem .45rem;
    background: var(--su-blue-soft); color: var(--su-blue);
    border-radius: 4px;
    font-size: .68rem; font-weight: 700;
    text-transform: uppercase; letter-spacing: .03em;
}

.su-cta-row { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
.su-btn {
    display: inline-flex; align-items: center; gap: .5rem;
    padding: .75rem 1.5rem;
    font-size: .95rem; font-weight: 600;
    border-radius: 10px;
    border: 1px solid transparent;
    text-decoration: none;
    cursor: pointer;
    transition: background .15s, transform .15s, box-shadow .15s;
}
.su-btn--primary { background: var(--su-blue); color: #fff !important; border-color: var(--su-blue); box-shadow: 0 1px 2px rgba(37,99,235,.25); }
.su-btn--primary:hover:not(:disabled) { background: var(--su-blue-dark); border-color: var(--su-blue-dark); transform: translateY(-1px); box-shadow: 0 4px 8px rgba(37,99,235,.25); }
.su-btn--primary:disabled { opacity: .6; cursor: not-allowed; }
.su-btn--primary svg { color: #fff !important; }
.su-btn--ghost { background: transparent; color: var(--su-text) !important; border-color: var(--su-border); }
.su-btn--ghost:hover { background: var(--su-bg-soft); border-color: #cbd5e1; }

.su-spinner { font-size: .85rem; color: var(--su-muted); }

/* Progress */
.su-progress { margin-top: 1.25rem; }
.su-progress__label {
    display: flex; align-items: center; gap: .5rem;
    font-size: .85rem; color: var(--su-text);
    margin-bottom: .5rem; font-weight: 500;
}
.su-progress__bar {
    height: 8px; background: var(--su-border-soft); border-radius: 4px; overflow: hidden;
}
.su-progress__fill {
    height: 100%;
    background: linear-gradient(90deg, var(--su-blue) 0%, #60a5fa 100%);
    border-radius: 4px;
    width: 0%;
    transition: width .4s ease;
}

/* Last install + rollback */
.su-history { display: flex; align-items: center; gap: .75rem; margin-bottom: .75rem; font-size: .9rem; }
.su-history__badge { padding: .2rem .6rem; font-size: .75rem; font-weight: 700; border-radius: 4px; }
.su-history__badge--ok { background: var(--su-green-soft); color: #14532d; }
.su-history__badge--err { background: var(--su-red-soft); color: #7f1d1d; }

/* Settings */
.su-settings { display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; }
@media (max-width: 640px) { .su-settings { grid-template-columns: 1fr; } }
.su-setting__label { font-size: .75rem; text-transform: uppercase; letter-spacing: .05em; color: var(--su-muted); font-weight: 600; margin-bottom: .35rem; }
.su-setting__value { font-size: .9rem; color: var(--su-ink); }

@media (max-width: 640px) {
    .su-hero { grid-template-columns: 1fr; text-align: center; }
    .su-hero__versions { justify-content: center; }
    .su-hero__ver { align-items: center; }
}
</style>

<div class="su">

    <?php if (isset($flash_error)): ?>
    <div class="su-alert su-alert--error"><?= e($flash_error) ?></div>
    <?php endif; ?>
    <?php if (isset($flash_success)): ?>
    <div class="su-alert su-alert--success"><?= e($flash_success) ?></div>
    <?php endif; ?>
    <?php if (isset($flash_info)): ?>
    <div class="su-alert su-alert--info"><?= e($flash_info) ?></div>
    <?php endif; ?>

    <!-- ── Hero / Versions ─────────────────────────────────────── -->
    <div class="su-hero">
        <div>
            <div class="su-hero__versions">
                <div class="su-hero__ver">
                    <span class="su-hero__ver-label">Aktuell installiert</span>
                    <span class="su-hero__ver-num">v<?= e($currentVersion) ?></span>
                </div>
                <?php if ($updateInfo['available']): ?>
                <div class="su-hero__arrow"><?= render_icon('arrow-right', 32) ?></div>
                <div class="su-hero__ver">
                    <span class="su-hero__ver-label">Neue Version</span>
                    <span class="su-hero__ver-num su-hero__ver-num--new">v<?= e($latestVersion) ?></span>
                </div>
                <span class="su-hero__status su-hero__status--available">
                    <?= render_icon('download-cloud', 16) ?>
                    Update verfügbar
                </span>
                <?php else: ?>
                <span class="su-hero__status su-hero__status--uptodate">
                    <?= render_icon('shield-check', 16) ?>
                    System aktuell
                </span>
                <?php endif; ?>
            </div>
            <?php if ($lastCheckedHuman !== ''): ?>
            <div class="su-hero__meta">
                <?= render_icon('clock', 13) ?>
                Zuletzt geprüft: <?= e($lastCheckedHuman) ?>
            </div>
            <?php endif; ?>
        </div>

        <form method="POST" action="<?= admin_url('system/updates/check') ?>" class="su-hero__check-form">
            <?= $csrf->field() ?>
            <button type="submit" class="su-hero__btn-check">
                <?= render_icon('refresh-cw', 14) ?>
                Jetzt prüfen
            </button>
        </form>
    </div>

    <?php if ($updateInfo['available']): ?>

    <!-- ── Release Notes ───────────────────────────────────────── -->
    <?php if ($releaseNotes !== '' && $releaseNotes !== null): ?>
    <div class="su-card">
        <div class="su-card__head">
            <?= render_icon('sparkles', 18) ?>
            <h3 class="su-card__title">Was ist neu in v<?= e($latestVersion) ?>?</h3>
        </div>
        <div class="su-card__body">
            <article class="iw-release-notes su-rn">
                <?= function_exists('sanitize_html') ? sanitize_html($releaseNotes) : htmlspecialchars($releaseNotes) ?>
            </article>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── Install Panel ───────────────────────────────────────── -->
    <div class="su-card" id="su-install-panel">
        <div class="su-card__head">
            <?= render_icon('download', 18) ?>
            <h3 class="su-card__title">Update installieren</h3>
        </div>
        <div class="su-card__body">

            <div class="su-install__meta">
                <?php if ($isSecurity): ?>
                <span class="su-chip su-chip--alert"><?= render_icon('shield-alert', 12) ?> Sicherheits-Update</span>
                <?php endif; ?>
                <?php if ($isSigned): ?>
                <span class="su-chip su-chip--secure"><?= render_icon('shield-check', 12) ?> Signatur verifiziert (Ed25519)</span>
                <?php endif; ?>
                <?php if ($sizeMb !== null): ?>
                <span class="su-chip"><?= render_icon('package', 12) ?> <?= e($sizeMb) ?> MB</span>
                <?php endif; ?>
            </div>

            <p style="font-size:.92rem; color:var(--su-text); margin:0 0 1rem;">
                Das Update wird automatisch heruntergeladen, auf Echtheit geprüft und installiert.
                Vor der Installation wird ein Backup angelegt &ndash; falls etwas schiefgeht, wird die Seite automatisch zurückgesetzt.
            </p>

            <div class="su-scope">
                <label class="su-scope__item">
                    <input type="checkbox" id="scope_app_db" checked disabled>
                    <span>
                        <span class="su-scope__label">App-Dateien &amp; Datenbank sichern<span class="su-scope__pflicht">Pflicht</span></span>
                        <span class="su-scope__hint">Ermöglicht automatisches Zurückrollen bei Problemen.</span>
                    </span>
                </label>
                <label class="su-scope__item">
                    <input type="checkbox" id="scope_uploads" name="backup_uploads" value="1">
                    <span>
                        <span class="su-scope__label">Uploads mitsichern</span>
                        <span class="su-scope__hint">Bilder und Dateien. Optional &ndash; macht das Backup größer, aber sicherer.</span>
                    </span>
                </label>
            </div>

            <div class="su-cta-row">
                <button id="su-install-btn" class="su-btn su-btn--primary" onclick="suStartInstall()">
                    <?= render_icon('download-cloud', 16) ?>
                    Jetzt installieren
                </button>
                <span id="su-install-spinner" class="su-spinner" style="display:none;">Bitte warten…</span>
            </div>

            <div id="su-progress-wrap" class="su-progress" style="display:none;">
                <div class="su-progress__label" id="su-progress-label">Vorbereitung…</div>
                <div class="su-progress__bar"><div class="su-progress__fill" id="su-progress-fill"></div></div>
            </div>

            <div id="su-install-result" style="margin-top:1rem;"></div>
        </div>

        <!-- Trust badges -->
        <div class="su-trust">
            <div class="su-trust__item">
                <div class="su-trust__icon"><?= render_icon('archive', 18) ?></div>
                <div>
                    <div class="su-trust__label">Auto-Backup</div>
                    <div class="su-trust__desc">Vor jeder Installation wird automatisch ein Backup erstellt.</div>
                </div>
            </div>
            <div class="su-trust__item">
                <div class="su-trust__icon"><?= render_icon('shield-check', 18) ?></div>
                <div>
                    <div class="su-trust__label">Verschlüsselt verifiziert</div>
                    <div class="su-trust__desc">Ed25519-Signatur und SHA256-Prüfsumme garantieren Echtheit.</div>
                </div>
            </div>
            <div class="su-trust__item">
                <div class="su-trust__icon"><?= render_icon('refresh-cw', 18) ?></div>
                <div>
                    <div class="su-trust__label">Auto-Rollback</div>
                    <div class="su-trust__desc">Bei Problemen wird die Seite automatisch wiederhergestellt.</div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── Last install + rollback ────────────────────────────── -->
    <?php if (!empty($lastInstall)): ?>
    <div class="su-card">
        <div class="su-card__head">
            <?= render_icon('clock', 18) ?>
            <h3 class="su-card__title">Letzte Installation</h3>
        </div>
        <div class="su-card__body">
            <div class="su-history">
                <?php if (!empty($lastInstall['success'])): ?>
                <span class="su-history__badge su-history__badge--ok">Erfolgreich</span>
                <span>Version <?= e($lastInstall['version'] ?? '') ?></span>
                <span style="color:var(--su-muted);">&middot; <?= e($lastInstall['at'] ?? '') ?></span>
                <?php else: ?>
                <span class="su-history__badge su-history__badge--err">Fehlgeschlagen</span>
                <span><?= e($lastInstall['error'] ?? 'Unbekannter Fehler') ?></span>
                <?php endif; ?>
            </div>
            <?php if ($preBackupExists): ?>
            <form method="POST" action="<?= admin_url('system/updates/rollback') ?>"
                  onsubmit="return confirm('Pre-Update-Backup wirklich einspielen? Alle Änderungen seit dem Backup werden rückgängig gemacht.');">
                <?= $csrf->field() ?>
                <button type="submit" class="su-btn su-btn--ghost">
                    <?= render_icon('refresh-cw', 14) ?>
                    Auf vorherige Version zurückrollen
                </button>
                <div style="font-size:.75rem; color:var(--su-muted); margin-top:.35rem;"><?= e(basename($preBackupPath)) ?></div>
            </form>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- ── Settings ────────────────────────────────────────────── -->
    <div class="su-card">
        <div class="su-card__head">
            <?= render_icon('settings', 18) ?>
            <h3 class="su-card__title">Einstellungen</h3>
        </div>
        <div class="su-card__body">
            <div class="su-settings">
                <div>
                    <div class="su-setting__label">Automatische Prüfung</div>
                    <div class="su-setting__value">
                        <?php if ($checkEnabled): ?>
                        <span style="color:var(--su-green); font-weight:600;"><?= render_icon('check-circle', 14) ?> Aktiv</span>
                        <?php else: ?>
                        <span style="color:var(--su-muted);">Inaktiv</span>
                        <?php endif; ?>
                    </div>
                </div>
                <div>
                    <div class="su-setting__label">Update-Quelle</div>
                    <div class="su-setting__value" style="font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:.82rem;"><?= e($registryUrl) ?></div>
                </div>
            </div>
        </div>
    </div>

</div>

<script>
(function() {
    var csrfToken = <?= json_encode($csrf->token(), JSON_UNESCAPED_SLASHES) ?>;
    var installUrl = <?= json_encode(admin_url('system/updates/install'), JSON_UNESCAPED_SLASHES) ?>;
    var statusUrl  = <?= json_encode(admin_url('system/updates/status'), JSON_UNESCAPED_SLASHES) ?>;

    window.suStartInstall = function () {
        var btn = document.getElementById('su-install-btn');
        var spinner = document.getElementById('su-install-spinner');
        var wrap = document.getElementById('su-progress-wrap');
        var label = document.getElementById('su-progress-label');
        var fill = document.getElementById('su-progress-fill');
        var result = document.getElementById('su-install-result');
        var includeUploads = document.getElementById('scope_uploads').checked ? '1' : '0';

        btn.disabled = true;
        spinner.style.display = 'inline';
        wrap.style.display = 'block';
        result.innerHTML = '';
        fill.style.width = '0%';
        fill.style.background = '';

        var body = '_csrf_token=' + encodeURIComponent(csrfToken) +
                   '&backup_uploads=' + includeUploads;

        fetch(installUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'same-origin',
            body: body
        }).then(function(r) {
            return r.json().catch(function() {
                throw new Error('HTTP ' + r.status + ' (keine JSON-Antwort)');
            });
        }).then(function(data) {
            if (data.success) {
                fill.style.width = '100%';
                label.innerHTML = '<span style="color:#14532d; font-weight:600;">✓ Update erfolgreich installiert</span>';
                result.innerHTML = '<div class="su-alert su-alert--success">Update auf v' + (data.version || '') + ' erfolgreich. Seite wird neu geladen…</div>';
                setTimeout(function() { location.reload(); }, 2200);
            } else {
                fill.style.width = '100%';
                fill.style.background = '#dc2626';
                label.innerHTML = '<span style="color:#7f1d1d; font-weight:600;">✗ ' + (data.rolled_back ? 'Zurückgerollt' : 'Fehlgeschlagen') + '</span>';
                result.innerHTML = '<div class="su-alert su-alert--error">' + (data.error || 'Installation fehlgeschlagen.') + '</div>';
                btn.disabled = false;
                spinner.style.display = 'none';
            }
        }).catch(function(err) {
            label.innerHTML = '<span style="color:#7f1d1d; font-weight:600;">✗ Verbindungsfehler</span>';
            result.innerHTML = '<div class="su-alert su-alert--error">Verbindung zum Server fehlgeschlagen. Bitte Console/Error-Log prüfen.<br><small>' + (err && err.message ? err.message : '') + '</small></div>';
            btn.disabled = false;
            spinner.style.display = 'none';
        });

        // Poll progress
        var poll = setInterval(function () {
            fetch(statusUrl, { credentials: 'same-origin' })
                .then(function(r) { return r.json(); })
                .then(function(p) {
                    if (p && p.label) label.textContent = p.label;
                    if (p && typeof p.percent !== 'undefined') fill.style.width = p.percent + '%';
                    if (p && (p.status === 'done' || p.status === 'error')) clearInterval(poll);
                })
                .catch(function() { /* ignore transient errors */ });
        }, 700);
    };
})();
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
