<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

$success = '';
$error   = '';

// ── Handle actions ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id     = (int)($_POST['id'] ?? 0);
    try {
        if ($action === 'approve' && $id) {
            $pdo->prepare("UPDATE article_comments SET status = 1 WHERE comment_id = ?")->execute([$id]);
            $success = 'Comment approved and now visible on the article page.';
        } elseif ($action === 'pending' && $id) {
            $pdo->prepare("UPDATE article_comments SET status = 0 WHERE comment_id = ?")->execute([$id]);
            $success = 'Comment moved back to pending.';
        } elseif ($action === 'delete' && $id) {
            $pdo->prepare("DELETE FROM article_comments WHERE comment_id = ?")->execute([$id]);
            $success = 'Comment deleted successfully.';
        } elseif ($action === 'delete_all_pending') {
            $pdo->exec("DELETE FROM article_comments WHERE status = 0");
            $success = 'All pending comments deleted.';
        } elseif ($action === 'approve_all_pending') {
            $pdo->exec("UPDATE article_comments SET status = 1 WHERE status = 0");
            $success = 'All pending comments approved.';
        }
    } catch (PDOException $e) {
        $error = $e->getMessage();
    }
    header('Location: article_comments.php?msg=' . urlencode($success ?: $error));
    exit;
}

if (isset($_GET['msg'])) $success = $_GET['msg'];

// ── Search & filter ───────────────────────────────────────────────────────
$search  = trim($_GET['q']      ?? '');
$filter  = $_GET['status']      ?? '';
$page    = max(1, (int)($_GET['p'] ?? 1));
$perPage = 20;

$where  = [];
$params = [];

if ($search !== '') {
    $where[]  = '(ac.name LIKE ? OR ac.comment LIKE ? OR ac.email LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($filter !== '') {
    $where[]  = 'ac.status = ?';
    $params[] = (int)$filter;
}

$whereStr = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "
    SELECT ac.*,
           mi.article_title,
           j.name  AS journal_name,
           j.slug  AS journal_slug,
           jv.volume AS vol_num,
           jv.issue  AS vol_iss
    FROM article_comments ac
    LEFT JOIN submissions s  ON s.submission_id  = ac.submission_id
    LEFT JOIN manuscript_info mi ON mi.submission_id = ac.submission_id
    LEFT JOIN journals j     ON j.journal_id     = s.journal_id
    LEFT JOIN submission_files sf ON sf.submission_id = ac.submission_id
        AND sf.file_type IN ('payment_receipt','final_manuscript_revised','declaration_form')
        AND sf.publication_date IS NOT NULL
    LEFT JOIN journal_volumes jv ON jv.id = sf.volume_id
    $whereStr
    ORDER BY ac.created_at DESC
";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows  = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $total = count($rows);

    // Stats
    // $statsRow = $pdo->query("SELECT COUNT(*) total, SUM(status=1) approved, SUM(status=0) pending, ROUND(AVG(rating),1) avg_rating FROM article_comments")->fetch();
    
    $statsRow = $pdo->query("SELECT COUNT(*) total, SUM(status=1) approved, SUM(status=0) pending, ROUND(AVG(rating),1) avg_rating FROM article_comments")->fetch();

    // ADD this below:
    $siqStats = $pdo->query("
        SELECT COUNT(*) total, ROUND(AVG(siq_score),2) avg_score,
               SUM(conflict='yes') conflict_count, SUM(status=1) active_count
        FROM article_siq_ratings
    ")->fetch();

    // Paginate
    $totalPages = max(1, ceil($total / $perPage));
    $page       = min($page, $totalPages);
    $rows       = array_slice($rows, ($page - 1) * $perPage, $perPage);

} catch (PDOException $e) {
    $error     = $e->getMessage();
    $rows      = []; $total = 0; $totalPages = 1;
    $statsRow  = ['total' => 0, 'approved' => 0, 'pending' => 0, 'avg_rating' => 0];
}

function starHtml(int $r): string {
    $out = '';
    for ($i = 1; $i <= 5; $i++) {
        $out .= '<span style="color:' . ($i <= $r ? '#f59e0b' : '#d1d5db') . ';font-size:13px">★</span>';
    }
    return $out;
}

$siteUrl = 'https://communeglobal.com'; // adjust if needed
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Article Comments — Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family:'Roboto',sans-serif; margin:0; height:100vh; overflow:hidden; }
        body.dark { background-color:#1a202c; color:#e2e8f0; }
        .sidebar { width:250px; background:#2d3748; color:white; transition:all .3s; height:100%; position:fixed; top:0; left:0; z-index:10; overflow-y:auto; }
        .sidebar.collapsed { width:70px; }
        .sidebar.collapsed .sidebar-title { display:none; }
        .content { margin-left:250px; transition:margin-left .3s; height:100vh; overflow-y:auto; }
        .content.collapsed-sidebar { margin-left:70px; }
        .nav-item { padding:10px 12px; cursor:pointer; transition:background .2s; display:flex; align-items:center; }
        .nav-item:hover { background:#4a5568; }
        .nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }
        body.dark .bg-white { background-color:#2d3748; }
        body.dark input, body.dark select { background-color:#374151; color:#e5e7eb; border-color:#4b5563; }
        body.dark table { color:#e2e8f0; }
        body.dark .border-gray-200 { border-color:#4a5568; }
        body.dark .bg-gray-50 { background-color:#374151; }
        .comment-text { display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }
        .comment-text.expanded { -webkit-line-clamp:unset; }
        @media(max-width:768px){ .sidebar{transform:translateX(-250px);} .sidebar.mobile-open{transform:translateX(0);} .content{margin-left:0;} }
    </style>
</head>
<body class="bg-gray-100">

<button onclick="toggleMobileSidebar()" class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>
<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content" id="content">

    <!-- Topbar -->
    <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
        <div class="flex items-center gap-3">
            <button onclick="toggleSidebar()" class="text-gray-500 hover:text-gray-700 hidden md:block">
                <i class="fas fa-bars text-lg"></i>
            </button>
            <div class="flex items-center gap-2 text-sm text-gray-500">
                <a href="pages.php" class="hover:text-blue-600"><i class="fas fa-home"></i></a>
                <i class="fas fa-chevron-right text-xs text-gray-300"></i>
                <span class="text-gray-800 font-semibold">Article Comments</span>
            </div>
        </div>
        <div class="flex items-center gap-3">
            <button id="darkModeToggle" class="text-gray-500 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
                <i class="fas fa-moon"></i>
            </button>
        </div>
    </div>

<main class="p-6">

    <?php if ($success): ?>
    <div class="bg-green-50 border-l-4 border-green-500 text-green-700 p-4 mb-5 rounded-lg flex items-center gap-2" id="flash">
        <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?>
    </div>
    <?php endif; ?>
    <?php if ($error): ?>
    <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-5 rounded-lg">
        <i class="fas fa-exclamation-circle mr-2"></i><?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>

    <!-- Combined Stats Cards -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 text-center">
            <div class="text-3xl font-bold text-blue-600"><?= number_format($statsRow['total']) ?></div>
            <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Total Comments</div>
        </div>
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 text-center">
            <div class="text-3xl font-bold text-yellow-500"><?= number_format($statsRow['pending']) ?></div>
            <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Pending Comments</div>
        </div>
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 text-center">
            <div class="text-3xl font-bold text-teal-600"><?= number_format($siqStats['total']) ?></div>
            <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">SIQ Ratings</div>
        </div>
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 text-center">
            <div class="text-3xl font-bold text-amber-500">
                <?= $siqStats['avg_score'] ? number_format($siqStats['avg_score'], 1) : '—' ?>
                <?php if ($siqStats['avg_score']): ?><span class="text-lg">★</span><?php endif; ?>
            </div>
            <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Avg SIQ Score</div>
        </div>
    </div>

    <!-- Tabs -->
    <div class="flex gap-1 mb-5 border-b border-gray-200">
        <button onclick="switchTab('comments')" id="tab-comments"
            class="tab-btn px-5 py-2.5 text-sm font-semibold text-blue-600 border-b-2 border-blue-600 -mb-px bg-white rounded-t-lg transition">
            <i class="fas fa-comments mr-1.5"></i> Comments
            <span class="ml-1.5 bg-yellow-100 text-yellow-700 text-xs font-bold px-2 py-0.5 rounded-full"><?= $statsRow['pending'] ?> pending</span>
        </button>
        <button onclick="switchTab('siq')" id="tab-siq"
            class="tab-btn px-5 py-2.5 text-sm font-semibold text-gray-500 border-b-2 border-transparent -mb-px bg-transparent hover:text-gray-700 rounded-t-lg transition">
            <i class="fas fa-shield-alt mr-1.5"></i> SIQ Ratings
            <span class="ml-1.5 bg-teal-100 text-teal-700 text-xs font-bold px-2 py-0.5 rounded-full"><?= $siqStats['total'] ?></span>
        </button>
    </div>

    <!-- ══════════════ COMMENTS TAB ══════════════ -->
    <div id="panel-comments">
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">

            <!-- Toolbar -->
            <div class="p-4 border-b border-gray-100 flex flex-wrap gap-3 items-center">
                <form method="GET" class="flex flex-wrap gap-3 flex-1">
                    <input type="hidden" name="tab" value="comments">
                    <div class="relative flex-1 min-w-[200px] max-w-sm">
                        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                        <input type="text" name="q" placeholder="Search name, email, comment…"
                            value="<?= htmlspecialchars($search) ?>"
                            class="w-full border border-gray-300 rounded-lg pl-9 pr-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <select name="status" onchange="this.form.submit()"
                        class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">All Status</option>
                        <option value="1" <?= $filter === '1' ? 'selected' : '' ?>>Approved</option>
                        <option value="0" <?= $filter === '0' ? 'selected' : '' ?>>Pending</option>
                    </select>
                    <?php if ($search || $filter !== ''): ?>
                    <a href="article_comments.php" class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 flex items-center gap-1">
                        <i class="fas fa-times"></i> Clear
                    </a>
                    <?php endif; ?>
                </form>
                <span class="text-sm text-gray-400"><?= $total ?> result<?= $total !== 1 ? 's' : '' ?></span>
                <?php if ((int)$statsRow['pending'] > 0): ?>
                <form method="POST" onsubmit="return confirm('Approve all <?= (int)$statsRow['pending'] ?> pending comments?')">
                    <input type="hidden" name="action" value="approve_all_pending">
                    <button type="submit" class="text-xs bg-green-50 hover:bg-green-100 text-green-700 border border-green-200 px-3 py-2 rounded-lg flex items-center gap-1 transition">
                        <i class="fas fa-check-double"></i> Approve All Pending
                    </button>
                </form>
                <form method="POST" onsubmit="return confirm('Permanently delete all <?= (int)$statsRow['pending'] ?> pending comments?')">
                    <input type="hidden" name="action" value="delete_all_pending">
                    <button type="submit" class="text-xs bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 px-3 py-2 rounded-lg flex items-center gap-1 transition">
                        <i class="fas fa-trash"></i> Delete All Pending
                    </button>
                </form>
                <?php endif; ?>
            </div>

            <div class="overflow-x-auto">
                <?php if (empty($rows)): ?>
                <div class="text-center py-16">
                    <i class="fas fa-comments text-4xl text-gray-200 mb-3 block"></i>
                    <p class="text-gray-500 font-medium">No comments found</p>
                </div>
                <?php else: ?>
                <table class="w-full text-sm text-left text-gray-600">
                    <thead class="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">#</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Reviewer</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Rating</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Comment</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Article</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Status</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide whitespace-nowrap">Submitted</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        <?php foreach ($rows as $i => $r):
                            $ini      = strtoupper(substr($r['name'], 0, 1));
                            $artUrl   = $siteUrl . '/journals/' . ($r['journal_slug'] ?? 'social-science') . '/article.php?id=' . (int)$r['submission_id'];
                            $artTitle = $r['article_title'] ? mb_strimwidth($r['article_title'], 0, 60, '…') : 'Submission #' . $r['submission_id'];
                        ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-4 py-3 text-gray-400 font-mono text-xs align-top"><?= ($page - 1) * $perPage + $i + 1 ?></td>
                            <td class="px-4 py-3 align-top">
                                <div class="flex items-start gap-2">
                                    <div class="w-8 h-8 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center text-xs font-bold flex-shrink-0 mt-0.5"><?= htmlspecialchars($ini) ?></div>
                                    <div>
                                        <div class="font-semibold text-gray-800 text-sm"><?= htmlspecialchars($r['name']) ?></div>
                                        <?php if ($r['email']): ?><div class="text-xs text-gray-400 mt-0.5"><?= htmlspecialchars($r['email']) ?></div><?php endif; ?>
                                        <div class="text-xs text-gray-400 font-mono mt-0.5"><?= htmlspecialchars($r['ip_address'] ?? '—') ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 py-3 align-top whitespace-nowrap">
                                <div><?= starHtml((int)$r['rating']) ?></div>
                                <div class="text-xs text-gray-400 mt-1 font-semibold"><?= (int)$r['rating'] ?>/5</div>
                            </td>
                            <td class="px-4 py-3 align-top" style="max-width:280px">
                                <div class="comment-text text-gray-700 text-sm leading-relaxed" id="ct-<?= $r['comment_id'] ?>"><?= nl2br(htmlspecialchars($r['comment'])) ?></div>
                                <?php if (mb_strlen($r['comment']) > 120): ?>
                                <button onclick="toggleComment(<?= $r['comment_id'] ?>)" id="ctbtn-<?= $r['comment_id'] ?>" class="text-xs text-blue-500 hover:underline mt-1 focus:outline-none">Show more</button>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-3 align-top" style="max-width:200px">
                                <a href="<?= htmlspecialchars($artUrl) ?>" target="_blank" class="text-xs text-blue-600 hover:underline font-medium leading-snug block">
                                    <?= htmlspecialchars($artTitle) ?> <i class="fas fa-external-link-alt text-xs opacity-50 ml-1"></i>
                                </a>
                                <?php if ($r['vol_num']): ?><div class="text-xs text-gray-400 mt-1">Vol.<?= (int)$r['vol_num'] ?> · Issue <?= (int)$r['vol_iss'] ?></div><?php endif; ?>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <?php if ($r['status'] == 1): ?>
                                <span class="inline-flex items-center gap-1.5 bg-green-100 text-green-700 text-xs font-semibold px-2.5 py-1 rounded-full"><span class="w-1.5 h-1.5 rounded-full bg-green-500"></span> Approved</span>
                                <?php else: ?>
                                <span class="inline-flex items-center gap-1.5 bg-yellow-100 text-yellow-700 text-xs font-semibold px-2.5 py-1 rounded-full"><span class="w-1.5 h-1.5 rounded-full bg-yellow-400"></span> Pending</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-3 text-xs text-gray-500 font-mono align-top whitespace-nowrap">
                                <?= date('d M Y', strtotime($r['created_at'])) ?><br>
                                <span class="text-gray-400"><?= date('H:i', strtotime($r['created_at'])) ?></span>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <div class="flex flex-col gap-2 items-center min-w-[110px]">
                                    <?php if ($r['status'] == 0): ?>
                                    <form method="POST" class="w-full">
                                        <input type="hidden" name="action" value="approve">
                                        <input type="hidden" name="id" value="<?= $r['comment_id'] ?>">
                                        <button type="submit" class="w-full text-xs bg-green-50 hover:bg-green-100 text-green-700 border border-green-200 px-3 py-1.5 rounded-lg flex items-center justify-center gap-1 transition font-medium">
                                            <i class="fas fa-check"></i> Approve
                                        </button>
                                    </form>
                                    <?php else: ?>
                                    <form method="POST" class="w-full">
                                        <input type="hidden" name="action" value="pending">
                                        <input type="hidden" name="id" value="<?= $r['comment_id'] ?>">
                                        <button type="submit" class="w-full text-xs bg-yellow-50 hover:bg-yellow-100 text-yellow-700 border border-yellow-200 px-3 py-1.5 rounded-lg flex items-center justify-center gap-1 transition font-medium">
                                            <i class="fas fa-pause"></i> Unpublish
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                    <form method="POST" class="w-full" onsubmit="return confirm('Delete this comment from <?= htmlspecialchars(addslashes($r['name'])) ?>?')">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $r['comment_id'] ?>">
                                        <button type="submit" class="w-full text-xs bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 px-3 py-1.5 rounded-lg flex items-center justify-center gap-1 transition font-medium">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <?php if ($totalPages > 1): ?>
            <div class="px-5 py-4 border-t border-gray-100 flex items-center justify-between text-sm text-gray-600">
                <span>Page <?= $page ?> of <?= $totalPages ?> (<?= $total ?> total)</span>
                <div class="flex gap-1 flex-wrap">
                    <?php
                    $qStr  = ($search ? '&q=' . urlencode($search) : '') . ($filter !== '' ? '&status=' . $filter : '');
                    $start = max(1, $page - 2);
                    $end   = min($totalPages, $page + 2);
                    if ($start > 1): ?>
                        <a href="?p=1<?= $qStr ?>" class="w-8 h-8 flex items-center justify-center rounded-lg text-xs font-medium bg-gray-100 hover:bg-gray-200 text-gray-600">1</a>
                        <?php if ($start > 2): ?><span class="w-8 h-8 flex items-center justify-center text-xs text-gray-400">…</span><?php endif; ?>
                    <?php endif; ?>
                    <?php for ($pg = $start; $pg <= $end; $pg++): ?>
                    <a href="?p=<?= $pg ?><?= $qStr ?>&tab=comments"
                       class="w-8 h-8 flex items-center justify-center rounded-lg text-xs font-medium transition
                              <?= $pg === $page ? 'bg-blue-600 text-white' : 'bg-gray-100 hover:bg-gray-200 text-gray-600' ?>">
                        <?= $pg ?>
                    </a>
                    <?php endfor; ?>
                    <?php if ($end < $totalPages): ?>
                        <?php if ($end < $totalPages - 1): ?><span class="w-8 h-8 flex items-center justify-center text-xs text-gray-400">…</span><?php endif; ?>
                        <a href="?p=<?= $totalPages ?><?= $qStr ?>&tab=comments" class="w-8 h-8 flex items-center justify-center rounded-lg text-xs font-medium bg-gray-100 hover:bg-gray-200 text-gray-600"><?= $totalPages ?></a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div><!-- /panel-comments -->


    <!-- ══════════════ SIQ RATINGS TAB ══════════════ -->
    <div id="panel-siq" style="display:none">
        <?php
        try {
            $siqRows = $pdo->query("
                SELECT ar.*,
                       mi.article_title,
                       j.slug AS journal_slug,
                       s.submission_id AS sid
                FROM article_siq_ratings ar
                LEFT JOIN submissions s    ON s.submission_id  = ar.submission_id
                LEFT JOIN manuscript_info mi ON mi.submission_id = ar.submission_id
                LEFT JOIN journals j         ON j.journal_id    = s.journal_id
                ORDER BY ar.created_at DESC
            ")->fetchAll(PDO::FETCH_ASSOC);
        } catch(PDOException $e) { $siqRows = []; }
        ?>

        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div class="p-4 border-b border-gray-100 flex items-center justify-between">
                <h3 class="font-semibold text-gray-700 text-sm flex items-center gap-2">
                    <i class="fas fa-shield-alt text-teal-500"></i> Scholar Impact Quotient Ratings
                </h3>
                <div class="flex gap-4 text-xs text-gray-500">
                    <span><i class="fas fa-exclamation-triangle text-yellow-400 mr-1"></i><?= $siqStats['conflict_count'] ?> with COI declared</span>
                    <span><i class="fas fa-check-circle text-teal-400 mr-1"></i><?= $siqStats['active_count'] ?> active</span>
                </div>
            </div>

            <div class="overflow-x-auto">
                <?php if (empty($siqRows)): ?>
                <div class="text-center py-16">
                    <i class="fas fa-star text-4xl text-gray-200 mb-3 block"></i>
                    <p class="text-gray-500 font-medium">No SIQ ratings yet</p>
                </div>
                <?php else: ?>
                <table class="w-full text-sm text-left text-gray-600">
                    <thead class="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">#</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Article</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide text-center">SIQ Score</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Criteria Breakdown</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">COI</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">IP</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Status</th>
                            <th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide whitespace-nowrap">Date</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        <?php foreach ($siqRows as $si => $sq):
                            $artUrl2   = $siteUrl . '/journals/' . ($sq['journal_slug'] ?? 'social-science') . '/article.php?id=' . (int)$sq['submission_id'];
                            $artTitle2 = $sq['article_title'] ? mb_strimwidth($sq['article_title'], 0, 55, '…') : 'Submission #' . $sq['submission_id'];
                            $score     = (float)$sq['siq_score'];
                            $scoreColor = $score >= 7 ? 'text-green-600' : ($score >= 4 ? 'text-yellow-600' : 'text-red-500');
                        ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-4 py-3 text-gray-400 font-mono text-xs align-top"><?= $si + 1 ?></td>

                            <!-- Article -->
                            <td class="px-4 py-3 align-top" style="max-width:220px">
                                <a href="<?= htmlspecialchars($artUrl2) ?>" target="_blank"
                                   class="text-xs text-blue-600 hover:underline font-medium leading-snug block">
                                    <?= htmlspecialchars($artTitle2) ?>
                                    <i class="fas fa-external-link-alt text-xs opacity-40 ml-1"></i>
                                </a>
                                <div class="text-xs text-gray-400 mt-0.5">ID: <?= (int)$sq['submission_id'] ?></div>
                            </td>

                            <!-- SIQ Score -->
                            <td class="px-4 py-3 align-top text-center">
                                <div class="inline-flex flex-col items-center">
                                    <span class="text-2xl font-bold <?= $scoreColor ?>"><?= number_format($score, 1) ?></span>
                                    <span class="text-xs text-gray-400 mt-0.5">/ 10</span>
                                </div>
                            </td>

                            <!-- Criteria Breakdown -->
                            <td class="px-4 py-3 align-top" style="min-width:200px">
                                <div class="grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-gray-600">
                                    <div><span class="text-gray-400">Clarity</span> <strong class="ml-1"><?= (int)$sq['clarity'] ?></strong></div>
                                    <div><span class="text-gray-400">Clinical</span> <strong class="ml-1"><?= (int)$sq['clinical'] ?></strong></div>
                                    <div><span class="text-gray-400">Study</span> <strong class="ml-1"><?= (int)$sq['study'] ?></strong></div>
                                    <div><span class="text-gray-400">Data</span> <strong class="ml-1"><?= (int)$sq['data_analysis'] ?></strong></div>
                                    <div><span class="text-gray-400">Novelty</span> <strong class="ml-1"><?= (int)$sq['novelty'] ?></strong></div>
                                    <div><span class="text-gray-400">Presentation</span> <strong class="ml-1"><?= (int)$sq['presentation'] ?></strong></div>
                                </div>
                            </td>

                            <!-- COI -->
                            <td class="px-4 py-3 align-top">
                                <?php if ($sq['conflict'] === 'yes'): ?>
                                <span class="inline-flex items-center gap-1 bg-red-50 text-red-600 text-xs font-semibold px-2 py-1 rounded-full border border-red-200">
                                    <i class="fas fa-exclamation-triangle text-xs"></i> Yes
                                </span>
                                <?php if ($sq['conflict_detail']): ?>
                                <div class="text-xs text-gray-400 mt-1 max-w-[140px]" title="<?= htmlspecialchars($sq['conflict_detail']) ?>">
                                    <?= htmlspecialchars(mb_strimwidth($sq['conflict_detail'], 0, 50, '…')) ?>
                                </div>
                                <?php endif; ?>
                                <?php else: ?>
                                <span class="inline-flex items-center gap-1 bg-green-50 text-green-600 text-xs font-semibold px-2 py-1 rounded-full border border-green-200">
                                    <i class="fas fa-check text-xs"></i> None
                                </span>
                                <?php endif; ?>
                            </td>

                            <!-- IP -->
                            <td class="px-4 py-3 align-top">
                                <span class="text-xs text-gray-500 font-mono"><?= htmlspecialchars($sq['ip_address']) ?></span>
                            </td>

                            <!-- Status -->
                            <td class="px-4 py-3 align-top">
                                <?php if ($sq['status'] == 1): ?>
                                <span class="inline-flex items-center gap-1 bg-teal-50 text-teal-700 text-xs font-semibold px-2.5 py-1 rounded-full">
                                    <span class="w-1.5 h-1.5 rounded-full bg-teal-500"></span> Active
                                </span>
                                <?php else: ?>
                                <span class="inline-flex items-center gap-1 bg-gray-100 text-gray-500 text-xs font-semibold px-2.5 py-1 rounded-full">
                                    <span class="w-1.5 h-1.5 rounded-full bg-gray-400"></span> Inactive
                                </span>
                                <?php endif; ?>
                            </td>

                            <!-- Date -->
                            <td class="px-4 py-3 text-xs text-gray-500 font-mono align-top whitespace-nowrap">
                                <?= date('d M Y', strtotime($sq['created_at'])) ?><br>
                                <span class="text-gray-400"><?= date('H:i', strtotime($sq['created_at'])) ?></span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>
    </div><!-- /panel-siq -->

</main>

</div>

<script>
// Flash auto-dismiss
var fl = document.getElementById('flash');
if (fl) setTimeout(function(){ fl.style.transition='opacity .5s'; fl.style.opacity='0'; setTimeout(function(){ fl.remove(); }, 500); }, 3500);

// Sidebar toggles
function toggleMobileSidebar(){ document.getElementById('sidebar').classList.toggle('mobile-open'); }
var sc = false;
function toggleSidebar(){
    sc = !sc;
    document.getElementById('sidebar').classList.toggle('collapsed', sc);
    document.getElementById('content').classList.toggle('collapsed-sidebar', sc);
}

// Dark mode
document.getElementById('darkModeToggle').addEventListener('click', function(){
    document.body.classList.toggle('dark');
    this.querySelector('i').classList.toggle('fa-moon');
    this.querySelector('i').classList.toggle('fa-sun');
    localStorage.setItem('darkMode', document.body.classList.contains('dark') ? 'enabled' : 'disabled');
});
if (localStorage.getItem('darkMode') === 'enabled'){
    document.body.classList.add('dark');
    document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon','fa-sun');
}

// Expand/collapse comment text
function toggleComment(id){
    var el = document.getElementById('ct-' + id);
    var btn = document.getElementById('ctbtn-' + id);
    btn.textContent = el.classList.toggle('expanded') ? 'Show less' : 'Show more';
}

// Tab switching
function switchTab(tab) {
    var panels = ['comments', 'siq'];
    panels.forEach(function(t) {
        document.getElementById('panel-' + t).style.display = t === tab ? '' : 'none';
        var btn = document.getElementById('tab-' + t);
        if (t === tab) {
            btn.classList.add('text-blue-600', 'border-blue-600', 'bg-white');
            btn.classList.remove('text-gray-500', 'border-transparent', 'bg-transparent');
        } else {
            btn.classList.remove('text-blue-600', 'border-blue-600', 'bg-white');
            btn.classList.add('text-gray-500', 'border-transparent', 'bg-transparent');
        }
    });
    localStorage.setItem('acTab', tab);
}

// Restore active tab on load
var savedTab = new URLSearchParams(window.location.search).get('tab') || localStorage.getItem('acTab') || 'comments';
switchTab(savedTab);
</script>

</body>
</html>