<?php
$comments = $commentsResult['comments'] ?? [];
$totalPages = max(1, (int) ($commentsResult['total_pages'] ?? 1));
$currentPage = max(1, (int) ($commentsResult['page'] ?? $page ?? 1));
$selectedStatus = (string) ($selectedStatus ?? 'all');
$commentsEnabled = !empty($commentSettings['success']) && !empty($commentSettings['comments_enabled']);

$statusLabels = [
    'all' => 'Wszystkie',
    'hold' => 'Oczekujace',
    'approve' => 'Zatwierdzone',
    'spam' => 'Spam',
    'trash' => 'Kosz',
];

$badgeClasses = [
    'approved' => 'bg-success',
    'approve' => 'bg-success',
    'hold' => 'bg-warning text-dark',
    'spam' => 'bg-danger',
    'trash' => 'bg-secondary',
];
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1">Komentarze: <?= htmlspecialchars((string) $site['name']) ?></h2>
        <a href="<?= htmlspecialchars((string) $site['url']) ?>" target="_blank" class="text-muted small">
            <?= htmlspecialchars((string) $site['url']) ?>
        </a>
    </div>
    <div class="d-flex gap-2">
        <a href="/sites/<?= (int) $site['id'] ?>/dashboard" class="btn btn-outline-secondary">
            <i class="bi bi-sliders me-1"></i>WP Dashboard
        </a>
        <a href="/sites" class="btn btn-outline-dark">
            <i class="bi bi-arrow-left me-1"></i>Lista stron
        </a>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Komentowanie nowych wpisow</h5>
        <?php if (!empty($commentSettings['success'])): ?>
            <?php if ($commentsEnabled): ?>
                <span class="badge bg-success">ON</span>
            <?php else: ?>
                <span class="badge bg-secondary">OFF</span>
            <?php endif; ?>
        <?php else: ?>
            <span class="badge bg-warning text-dark">Brak danych</span>
        <?php endif; ?>
    </div>
    <div class="card-body">
        <p class="text-muted small mb-3">
            Przelacznik zmienia domyslne ustawienie komentowania dla nowych wpisow WordPress.
            Nie zamyka komentarzy masowo w juz opublikowanych artykulach.
        </p>
        <p class="mb-3">
            <?= htmlspecialchars((string) ($commentSettings['message'] ?? 'Brak informacji z WordPress.')) ?>
        </p>
        <div class="d-flex gap-2 flex-wrap">
            <form method="post" action="/sites/<?= (int) $site['id'] ?>/comments/settings">
                <input type="hidden" name="enabled" value="1">
                <button type="submit" class="btn btn-success" <?= $commentsEnabled ? 'disabled' : '' ?>>
                    <i class="bi bi-chat-dots me-1"></i>Wlacz komentarze
                </button>
            </form>
            <form method="post" action="/sites/<?= (int) $site['id'] ?>/comments/settings" data-confirm="Wylaczyc komentowanie nowych wpisow na tej stronie?">
                <input type="hidden" name="enabled" value="0">
                <button type="submit" class="btn btn-outline-danger" <?= (!$commentsEnabled && !empty($commentSettings['success'])) ? 'disabled' : '' ?>>
                    <i class="bi bi-chat-slash me-1"></i>Wylacz komentarze
                </button>
            </form>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Lista komentarzy</h5>
        <span class="badge bg-primary"><?= (int) ($commentsResult['total'] ?? 0) ?> lacznie</span>
    </div>
    <div class="card-body border-bottom">
        <div class="d-flex gap-2 flex-wrap">
            <?php foreach ($statusLabels as $status => $label): ?>
                <a
                    href="/sites/<?= (int) $site['id'] ?>/comments?status=<?= urlencode($status) ?>"
                    class="btn btn-sm <?= $selectedStatus === $status ? 'btn-primary' : 'btn-outline-secondary' ?>"
                >
                    <?= htmlspecialchars($label) ?>
                </a>
            <?php endforeach; ?>
        </div>
    </div>

    <?php if (empty($commentsResult['success'])): ?>
        <div class="card-body">
            <div class="alert alert-warning mb-0">
                <?= htmlspecialchars((string) ($commentsResult['message'] ?? 'Nie udalo sie pobrac komentarzy.')) ?>
            </div>
        </div>
    <?php elseif (empty($comments)): ?>
        <div class="card-body text-center text-muted py-5">
            Brak komentarzy dla wybranego statusu.
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr>
                        <th>Autor</th>
                        <th>Komentarz</th>
                        <th>Data</th>
                        <th>Status</th>
                        <th>Wpis</th>
                        <th class="text-end">Akcje</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($comments as $comment): ?>
                        <?php
                            $commentId = (int) ($comment['id'] ?? 0);
                            $authorName = (string) ($comment['author_name'] ?? '');
                            $authorEmail = (string) ($comment['author_email'] ?? '');
                            $authorUrl = (string) ($comment['author_url'] ?? '');
                            $rawContent = $comment['content']['rendered'] ?? $comment['content']['raw'] ?? '';
                            $content = trim(preg_replace('/\s+/', ' ', strip_tags((string) $rawContent)) ?? '');
                            $content = mb_strlen($content) > 220 ? mb_substr($content, 0, 220) . '...' : $content;
                            $status = (string) ($comment['status'] ?? '');
                            $date = (string) ($comment['date'] ?? '');
                            $postId = (int) ($comment['post'] ?? 0);
                            $commentLink = (string) ($comment['link'] ?? '');
                            $badgeClass = $badgeClasses[$status] ?? 'bg-secondary';
                        ?>
                        <tr>
                            <td>
                                <strong><?= htmlspecialchars($authorName !== '' ? $authorName : 'Anonim') ?></strong>
                                <?php if ($authorEmail !== ''): ?>
                                    <div class="small text-muted"><?= htmlspecialchars($authorEmail) ?></div>
                                <?php endif; ?>
                                <?php if ($authorUrl !== ''): ?>
                                    <a href="<?= htmlspecialchars($authorUrl) ?>" target="_blank" class="small">URL autora</a>
                                <?php endif; ?>
                            </td>
                            <td class="small" style="max-width: 520px;">
                                <?= htmlspecialchars($content !== '' ? $content : '-') ?>
                            </td>
                            <td class="text-nowrap">
                                <?= $date !== '' ? htmlspecialchars(date('d.m.Y H:i', strtotime($date))) : '-' ?>
                            </td>
                            <td>
                                <span class="badge <?= htmlspecialchars($badgeClass) ?>">
                                    <?= htmlspecialchars($status !== '' ? $status : '-') ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($commentLink !== ''): ?>
                                    <a href="<?= htmlspecialchars($commentLink) ?>" target="_blank">#<?= $postId ?></a>
                                <?php elseif ($postId > 0): ?>
                                    #<?= $postId ?>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td class="text-end">
                                <form
                                    method="post"
                                    action="/sites/<?= (int) $site['id'] ?>/comments/<?= $commentId ?>/delete"
                                    class="d-inline"
                                    data-confirm="Usunac ten komentarz z WordPress?"
                                >
                                    <input type="hidden" name="status" value="<?= htmlspecialchars($selectedStatus) ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger" <?= $commentId <= 0 ? 'disabled' : '' ?>>
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>

    <?php if (!empty($commentsResult['success']) && $totalPages > 1): ?>
        <div class="card-footer d-flex justify-content-between align-items-center">
            <span class="text-muted small">Strona <?= $currentPage ?> z <?= $totalPages ?></span>
            <div class="btn-group btn-group-sm">
                <a
                    href="/sites/<?= (int) $site['id'] ?>/comments?status=<?= urlencode($selectedStatus) ?>&page=<?= max(1, $currentPage - 1) ?>"
                    class="btn btn-outline-secondary <?= $currentPage <= 1 ? 'disabled' : '' ?>"
                >
                    Poprzednia
                </a>
                <a
                    href="/sites/<?= (int) $site['id'] ?>/comments?status=<?= urlencode($selectedStatus) ?>&page=<?= min($totalPages, $currentPage + 1) ?>"
                    class="btn btn-outline-secondary <?= $currentPage >= $totalPages ? 'disabled' : '' ?>"
                >
                    Nastepna
                </a>
            </div>
        </div>
    <?php endif; ?>
</div>
