<?php ob_start(); ?>

<?php admin_content_header(__('admin.marketplace_audit.title'), 'marketplace', [
    ['label' => __('admin.marketplace.title'), 'url' => admin_url('marketplace')],
]); ?>

<!-- Filters -->
<div style="display:flex;gap:1rem;margin-bottom:1.5rem;flex-wrap:wrap;align-items:center;">
    <form method="GET" action="<?= admin_url('marketplace/audit-log') ?>" style="display:flex;gap:0.5rem;flex-wrap:wrap;align-items:center;">

        <select name="action" onchange="this.form.submit()" style="min-width:150px;">
            <option value=""><?= __('admin.marketplace_audit.all_actions') ?></option>
            <?php foreach (['install','update','rollback','allowlist_add','allowlist_remove'] as $a): ?>
            <option value="<?= e($a) ?>" <?= ($filterAction ?? '') === $a ? 'selected' : '' ?>><?= e($a) ?></option>
            <?php endforeach; ?>
        </select>

        <select name="result" onchange="this.form.submit()" style="min-width:130px;">
            <option value=""><?= __('admin.marketplace_audit.all_results') ?></option>
            <?php foreach (['success','failed','rolled_back'] as $r): ?>
            <option value="<?= e($r) ?>" <?= ($filterResult ?? '') === $r ? 'selected' : '' ?>><?= e($r) ?></option>
            <?php endforeach; ?>
        </select>

        <input type="text" name="slug" value="<?= e($filterSlug ?? '') ?>"
               placeholder="<?= __('admin.marketplace_audit.filter_slug') ?>"
               style="min-width:160px;" />
        <button type="submit" class="btn btn-sm btn-secondary"><?= icon('search', 14) ?> <?= __('admin.common.filter') ?></button>

        <?php if ($filterAction || $filterResult || $filterSlug): ?>
        <a href="<?= admin_url('marketplace/audit-log') ?>" class="btn btn-sm btn-ghost"><?= icon('x', 14) ?> <?= __('admin.common.reset') ?></a>
        <?php endif; ?>
    </form>
    <span style="margin-left:auto;color:var(--color-muted);font-size:0.85rem;">
        <?= number_format($total) ?> <?= __('admin.marketplace_audit.entries') ?>
    </span>
</div>

<div class="table-responsive">
<table class="data-table">
    <thead>
        <tr>
            <th><?= __('admin.marketplace_audit.col_time') ?></th>
            <th><?= __('admin.marketplace_audit.col_slug') ?></th>
            <th><?= __('admin.marketplace_audit.col_action') ?></th>
            <th><?= __('admin.marketplace_audit.col_version') ?></th>
            <th><?= __('admin.marketplace_audit.col_verified') ?></th>
            <th><?= __('admin.marketplace_audit.col_result') ?></th>
            <th><?= __('admin.marketplace_audit.col_user') ?></th>
            <th><?= __('admin.marketplace_audit.col_ip') ?></th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <?php if (empty($items)): ?>
        <?php admin_empty_state(__('admin.marketplace_audit.no_entries'), 'activity', '', '', true, 9); ?>
        <?php else: ?>
        <?php foreach ($items as $log): ?>
        <?php
            $resultClass = match($log['result'] ?? '') {
                'success'     => 'badge-success',
                'rolled_back' => 'badge-info',
                'failed'      => 'badge-danger',
                default       => 'badge-default',
            };
            $actionClass = match($log['action'] ?? '') {
                'install'          => 'badge-success',
                'update'           => 'badge-info',
                'rollback'         => 'badge-warning',
                'allowlist_add'    => 'badge-default',
                'allowlist_remove' => 'badge-danger',
                default            => 'badge-default',
            };
            $sha256 = (bool) ($log['sha256_verified'] ?? false);
            $sig    = (bool) ($log['sig_verified']    ?? false);
        ?>
        <tr>
            <td style="white-space:nowrap;">
                <time datetime="<?= e($log['created_at']) ?>">
                    <?= e(date('d.m.Y H:i', strtotime($log['created_at']))) ?>
                </time>
            </td>
            <td>
                <strong><?= e($log['slug'] ?? '') ?></strong>
                <?php if ($log['type'] ?? ''): ?>
                <br><small style="color:var(--color-muted);"><?= e($log['type']) ?></small>
                <?php endif; ?>
            </td>
            <td><span class="badge <?= $actionClass ?>"><?= e($log['action'] ?? '') ?></span></td>
            <td><?= e($log['version_target'] ?? '–') ?></td>
            <td>
                <?php if (in_array($log['action'], ['install','update'], true)): ?>
                <span title="SHA256" style="margin-right:0.25rem;">
                    <?= $sha256 ? icon('shield-check', 14, 'color:var(--color-success)') : icon('shield-x', 14, 'color:var(--color-danger)') ?>
                </span>
                <span title="Ed25519">
                    <?= $sig ? icon('key', 14, 'color:var(--color-success)') : icon('key', 14, 'color:var(--color-danger)') ?>
                </span>
                <?php else: ?>
                <span style="color:var(--color-muted);">–</span>
                <?php endif; ?>
            </td>
            <td><span class="badge <?= $resultClass ?>"><?= e($log['result'] ?? '') ?></span></td>
            <td><?= e($log['user_name'] ?? __('admin.marketplace_audit.system')) ?></td>
            <td><code style="font-size:0.8em;"><?= e($log['ip_address'] ?? '') ?></code></td>
            <td>
                <?php if (!empty($log['error_message']) || !empty($log['backup_path'])): ?>
                <button type="button" class="btn btn-xs btn-ghost"
                        onclick="this.closest('tr').nextElementSibling.classList.toggle('hidden')"
                        title="<?= __('admin.marketplace_audit.show_details') ?>">
                    <?= icon('chevron-down', 14) ?>
                </button>
                <?php endif; ?>
            </td>
        </tr>
        <?php if (!empty($log['error_message']) || !empty($log['backup_path'])): ?>
        <tr class="hidden" style="background:var(--color-surface-alt,#f8f8f8);">
            <td colspan="9" style="padding:0.75rem 1rem;font-size:0.85rem;">
                <?php if (!empty($log['error_message'])): ?>
                <div style="margin-bottom:0.25rem;">
                    <strong><?= __('admin.marketplace_audit.error') ?>:</strong>
                    <code style="word-break:break-all;"><?= e($log['error_message']) ?></code>
                </div>
                <?php endif; ?>
                <?php if (!empty($log['backup_path'])): ?>
                <div>
                    <strong><?= __('admin.marketplace_audit.backup') ?>:</strong>
                    <code style="word-break:break-all;"><?= e($log['backup_path']) ?></code>
                </div>
                <?php endif; ?>
                <?php if (!empty($log['key_id'])): ?>
                <div style="margin-top:0.25rem;">
                    <strong><?= __('admin.marketplace_audit.key_id') ?>:</strong>
                    <code><?= e($log['key_id']) ?></code>
                    &nbsp;|&nbsp;
                    <strong><?= __('admin.marketplace_audit.registry') ?>:</strong>
                    <code><?= e($log['registry_url'] ?? '') ?></code>
                </div>
                <?php endif; ?>
            </td>
        </tr>
        <?php endif; ?>
        <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>
</div>

<?php if ($pages > 1): ?>
<div class="pagination" style="margin-top:1.5rem;display:flex;gap:0.25rem;justify-content:center;flex-wrap:wrap;">
    <?php for ($p = 1; $p <= $pages; $p++): ?>
    <?php
    $qs = http_build_query(array_filter([
        'page'   => $p > 1 ? $p : null,
        'action' => $filterAction,
        'result' => $filterResult,
        'slug'   => $filterSlug ?: null,
    ]));
    ?>
    <a href="<?= admin_url('marketplace/audit-log') ?><?= $qs ? '?' . $qs : '' ?>"
       class="btn btn-sm <?= $p === $page ? 'btn-primary' : 'btn-secondary' ?>">
        <?= $p ?>
    </a>
    <?php endfor; ?>
</div>
<?php endif; ?>

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