<?php
/**
 * admin/reviewer_profile_approvals.php
 * Reviewer Profile Approval Queue — Communeglobal Admin
 *
 * Layout matches: reviewer-due-dates.php
 * - session_start + config/db.php + config/auth.php + require_page_access()
 * - $pdo, include/sidebar.php
 * - Tailwind + FontAwesome + SweetAlert2 + Roboto font
 * - Dark mode toggle, sidebar collapse
 */

ini_set('display_errors', 0);
session_start();

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

// ── AJAX: Profile detail HTML (same-file GET) ─────────────────
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['detail_id'])) {
    $pid  = (int)$_GET['detail_id'];
    $stmt = $pdo->prepare("
        SELECT rpp.*,
               u.first_name, u.last_name, u.title AS user_title,
               u.institutional_email, u.country,
               a.name    AS affil_name,
               a.city    AS affil_city,
               a.country AS affil_country,
               ra.first_name AS rev_by_fname,
               ra.last_name  AS rev_by_lname
        FROM reviewer_public_profile rpp
        JOIN  users u  ON u.user_id = rpp.user_id
        LEFT JOIN affiliations a  ON a.affiliation_id = COALESCE(rpp.profile_affiliation_id, u.affiliation_id)
        LEFT JOIN users ra        ON ra.user_id = rpp.reviewed_by
        WHERE rpp.id = ?
    ");
    $stmt->execute([$pid]);
    $p = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$p) { echo '<div style="padding:20px;color:#ef4444;">Profile not found.</div>'; exit; }

    $edu     = json_decode($p['education']    ?? '[]', true) ?: [];
    $pubs    = json_decode($p['publications'] ?? '[]', true) ?: [];
    $socs    = json_decode($p['societies']    ?? '[]', true) ?: [];
    $pending = $p['pending_changes'] ? json_decode($p['pending_changes'], true) : null;
    $pend    = $pending ?? [];

    function diffRow(string $label, $live, $updated): string {
        $changed = ($live !== $updated && $updated !== null);
        $out  = '<div style="border-bottom:1px solid #e2e8f0;padding:10px 0;">';
        $out .= '<div style="font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#64748b;margin-bottom:4px;">' . htmlspecialchars($label) . '</div>';
        if ($changed) {
            $out .= '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">';
            $out .= '<div style="background:#fef2f2;border-radius:6px;padding:8px 10px;font-size:.83rem;color:#991b1b;"><small style="display:block;color:#94a3b8;margin-bottom:3px;">Current (Live)</small>' . nl2br(htmlspecialchars((string)($live ?? '—'))) . '</div>';
            $out .= '<div style="background:#f0fdf4;border-radius:6px;padding:8px 10px;font-size:.83rem;color:#166534;"><small style="display:block;color:#94a3b8;margin-bottom:3px;"><i class="fas fa-arrow-right" style="color:#16a34a;font-size:.58rem;margin-right:3px;"></i>Pending Update</small>' . nl2br(htmlspecialchars((string)($updated ?? '—'))) . '</div>';
            $out .= '</div>';
        } else {
            $val = (string)($live ?? '');
            $out .= '<div style="font-size:.83rem;color:#374151;padding:3px 0;">' . ($val !== '' ? nl2br(htmlspecialchars($val)) : '<span style="color:#94a3b8;font-style:italic;">Not set</span>') . '</div>';
        }
        $out .= '</div>';
        return $out;
    }

    $isUpdate = !empty($p['pending_changes']);
    $fullName = trim(($p['user_title'] ? $p['user_title'].'. ' : '') . $p['first_name'] . ' ' . $p['last_name']);
    $initials = strtoupper(substr($p['first_name'],0,1).substr($p['last_name'],0,1));

    $statusMap = [
        'pending'           => ['#f59e0b','fa-clock',        'Pending Review'],
        'approved'          => ['#10b981','fa-check-circle', 'Approved'],
        'rejected'          => ['#ef4444','fa-times-circle', 'Rejected'],
        'changes_requested' => ['#3b82f6','fa-edit',         'Changes Requested'],
    ];
    [$sc,$si,$sl] = $statusMap[$p['approval_status']] ?? ['#64748b','fa-question','Unknown'];
    ?>
    <div style="padding:20px;font-family:'Roboto',sans-serif;">

        <!-- Header -->
        <div style="display:flex;align-items:flex-start;gap:14px;margin-bottom:18px;padding-bottom:16px;border-bottom:1px solid #e2e8f0;">
            <div style="width:50px;height:50px;border-radius:10px;background:linear-gradient(135deg,#1e293b,#3b82f6);display:flex;align-items:center;justify-content:center;font-weight:700;font-size:1rem;color:#fff;flex-shrink:0;">
                <?= htmlspecialchars($initials) ?>
            </div>
            <div style="flex:1;">
                <div style="font-size:1rem;font-weight:700;color:#0f172a;"><?= htmlspecialchars($fullName) ?></div>
                <div style="font-size:.78rem;color:#64748b;"><?= htmlspecialchars($p['institutional_email'] ?? '') ?></div>
                <?php if ($p['affil_name']): ?>
                <div style="font-size:.75rem;color:#64748b;margin-top:2px;">
                    <i class="fas fa-building-columns" style="font-size:.6rem;margin-right:4px;"></i>
                    <?= htmlspecialchars($p['affil_name'].($p['affil_city']?', '.$p['affil_city']:'').($p['affil_country']?', '.$p['affil_country']:'')) ?>
                </div>
                <?php endif; ?>
            </div>
            <div style="text-align:right;flex-shrink:0;">
                <span style="display:inline-flex;align-items:center;gap:4px;background:<?= $isUpdate?'#fffbeb':'#eff6ff' ?>;color:<?= $isUpdate?'#92400e':'#1e40af' ?>;border:1px solid <?= $isUpdate?'#fcd34d':'#bfdbfe' ?>;border-radius:20px;padding:3px 10px;font-size:.7rem;font-weight:700;">
                    <i class="fas <?= $isUpdate?'fa-sync':'fa-plus-circle' ?>" style="font-size:.58rem;"></i>
                    <?= $isUpdate?'Profile Update':'New Profile' ?>
                </span>
                <br>
                <span style="display:inline-flex;align-items:center;gap:4px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:20px;padding:3px 10px;font-size:.7rem;font-weight:700;color:<?= $sc ?>;margin-top:5px;">
                    <i class="fas <?= $si ?>" style="font-size:.58rem;"></i><?= $sl ?>
                </span>
                <?php if ($p['slug']): ?>
                <br><a href="https://communeglobal.com/reviewer-profile3.php?slug=<?= urlencode($p['slug']) ?>" target="_blank"
                       style="font-size:.7rem;color:#6366f1;text-decoration:none;display:inline-block;margin-top:4px;">
                    <i class="fas fa-external-link-alt" style="font-size:.58rem;margin-right:3px;"></i>/<?= htmlspecialchars($p['slug']) ?>
                </a>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($isUpdate): ?>
        <div style="background:#fffbeb;border:1px solid #fcd34d;border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:.82rem;color:#92400e;">
            <i class="fas fa-info-circle" style="margin-right:6px;"></i>
            Reviewer submitted <strong>changes to their live profile</strong>.
            <span style="color:#b45309;">Red = current live</span> &nbsp;|&nbsp; <span style="color:#166534;">Green = pending change</span>
        </div>
        <?php endif; ?>

        <!-- Timestamps -->
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:14px;">
            <?php
            $ts_cards = [
                ['Submitted At', $p['submitted_at'], '#3b82f6', 'fa-paper-plane', null],
                ['Last Updated', $p['updated_at'],   '#f59e0b', 'fa-clock',       null],
                ['Reviewed At',  $p['reviewed_at'],  '#10b981', 'fa-check',
                    ($p['rev_by_fname'] ? 'by '.trim($p['rev_by_fname'].' '.$p['rev_by_lname']) : null)],
            ];
            foreach ($ts_cards as [$lbl,$ts,$color,$icon,$sub]):
            ?>
            <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:10px 12px;">
                <div style="font-size:.62rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#64748b;margin-bottom:4px;">
                    <i class="fas <?= $icon ?>" style="color:<?= $color ?>;margin-right:4px;font-size:.58rem;"></i><?= htmlspecialchars($lbl) ?>
                </div>
                <div style="font-size:.85rem;font-weight:700;color:#0f172a;">
                    <?= $ts ? date('d M Y, H:i', strtotime($ts)) : '<span style="color:#94a3b8;">—</span>' ?>
                </div>
                <?php if ($sub): ?><div style="font-size:.68rem;color:#64748b;margin-top:1px;"><?= htmlspecialchars($sub) ?></div><?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>

        <?php if (!empty($p['admin_note'])): ?>
        <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:10px 14px;margin-bottom:12px;font-size:.82rem;color:#374151;">
            <i class="fas fa-comment" style="color:#6366f1;margin-right:6px;"></i>
            <strong>Previous Admin Note:</strong> <?= nl2br(htmlspecialchars($p['admin_note'])) ?>
        </div>
        <?php endif; ?>

        <!-- Profile fields -->
        <div style="border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;margin-bottom:14px;">
            <div style="background:#f8fafc;padding:9px 14px;border-bottom:1px solid #e2e8f0;font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#0f172a;display:flex;align-items:center;gap:8px;">
                Profile Content
                <?php if ($isUpdate): ?>
                <span style="background:#fef9c3;color:#92400e;border:1px solid #fcd34d;border-radius:4px;padding:2px 7px;font-size:.6rem;">
                    DIFF — red=live · green=pending
                </span>
                <?php endif; ?>
            </div>
            <div style="padding:14px;">
                <?php
                if ($isUpdate) {
                    echo diffRow('Bio',                    $p['bio'],                  $pend['bio']                    ?? null);
                    echo diffRow('Current Position',       $p['current_position'],     $pend['current_position']       ?? null);
                    echo diffRow('Years of Experience',    $p['total_experience_yrs'], $pend['total_experience_yrs']   ?? null);
                    echo diffRow('h-Index',                $p['h_index'],              $pend['h_index']                ?? null);
                    echo diffRow('Total Citations',        $p['total_citations'],      $pend['total_citations']        ?? null);
                    echo diffRow('ORCID iD',               $p['orcid_id'],             $pend['orcid_id']               ?? null);
                    echo diffRow('Affiliation ID',         $p['profile_affiliation_id'], $pend['profile_affiliation_id'] ?? null);

                    $lE = json_decode($p['education']    ?? '[]', true) ?: [];
                    $pE = json_decode($pend['education'] ?? '[]', true) ?: [];
                    $lEs = implode("\n", array_map(fn($e) => ($e['degree']??'').' @ '.($e['institution']??'').' ('.$e['year'].')', $lE));
                    $pEs = implode("\n", array_map(fn($e) => ($e['degree']??'').' @ '.($e['institution']??'').' ('.$e['year'].')', $pE));
                    echo diffRow('Education', $lEs ?: '—', $pEs !== $lEs ? $pEs : null);

                    $lP = json_decode($p['publications']    ?? '[]', true) ?: [];
                    $pP = json_decode($pend['publications'] ?? '[]', true) ?: [];
                    $lPs = implode("\n", array_map(fn($x) => ($x['title']??'').' — '.($x['journal']??'').' ('.$x['year'].')', $lP));
                    $pPs = implode("\n", array_map(fn($x) => ($x['title']??'').' — '.($x['journal']??'').' ('.$x['year'].')', $pP));
                    echo diffRow('Publications', $lPs ?: '—', $pPs !== $lPs ? $pPs : null);

                    $lS = json_decode($p['societies']    ?? '[]', true) ?: [];
                    $pS = json_decode($pend['societies'] ?? '[]', true) ?: [];
                    echo diffRow('Societies', implode(', ',$lS) ?: '—', implode(', ',$pS) !== implode(', ',$lS) ? implode(', ',$pS) : null);

                } else {
                    echo diffRow('Bio',                 $p['bio'],                  null);
                    echo diffRow('Current Position',    $p['current_position'],     null);
                    echo diffRow('Years of Experience', $p['total_experience_yrs'], null);
                    echo diffRow('h-Index',             $p['h_index'],              null);
                    echo diffRow('Total Citations',     $p['total_citations'],      null);
                    echo diffRow('ORCID iD',            $p['orcid_id'],             null);
                    if ($p['affil_name']) echo diffRow('Affiliation', $p['affil_name'].($p['affil_city']?', '.$p['affil_city']:'').($p['affil_country']?', '.$p['affil_country']:''), null);

                    if ($edu): ?>
                    <div style="border-bottom:1px solid #e2e8f0;padding:10px 0;">
                        <div style="font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#64748b;margin-bottom:6px;">Education</div>
                        <?php foreach ($edu as $e): ?>
                        <div style="margin-bottom:5px;font-size:.83rem;">
                            🎓 <strong><?= htmlspecialchars($e['degree'] ?? '') ?></strong> — <?= htmlspecialchars($e['institution'] ?? '') ?>
                            <span style="background:#e0e7ff;color:#3730a3;font-size:.67rem;font-weight:700;padding:1px 6px;border-radius:4px;margin-left:4px;"><?= (int)($e['year'] ?? 0) ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif;

                    if ($pubs): ?>
                    <div style="border-bottom:1px solid #e2e8f0;padding:10px 0;">
                        <div style="font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#64748b;margin-bottom:6px;">Publications (<?= count($pubs) ?>)</div>
                        <?php foreach ($pubs as $pub): ?>
                        <div style="margin-bottom:8px;padding-bottom:8px;border-bottom:1px solid #f1f5f9;">
                            <div style="font-size:.85rem;font-weight:600;color:#0f172a;"><?= htmlspecialchars($pub['title'] ?? '') ?></div>
                            <div style="font-size:.78rem;color:#64748b;margin-top:2px;">
                                <?= htmlspecialchars($pub['journal'] ?? '') ?>
                                <span style="background:#e0e7ff;color:#3730a3;font-size:.67rem;font-weight:700;padding:1px 6px;border-radius:4px;margin-left:4px;"><?= $pub['year'] ?? '' ?></span>
                                <span style="background:#eff6ff;color:#2563eb;font-size:.67rem;font-weight:700;padding:1px 6px;border-radius:4px;margin-left:3px;"><?= (int)($pub['citations'] ?? 0) ?> cit.</span>
                                <?php if (!empty($pub['doi'])): ?>
                                <span style="font-size:.7rem;color:#94a3b8;font-family:monospace;margin-left:4px;">DOI: <?= htmlspecialchars($pub['doi']) ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif;

                    if ($socs): ?>
                    <div style="padding:10px 0;">
                        <div style="font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#64748b;margin-bottom:6px;">Professional Societies</div>
                        <?php foreach ($socs as $s): ?>
                        <div style="font-size:.83rem;color:#374151;padding:2px 0;">
                            <i class="fas fa-circle-dot" style="color:#93c5fd;font-size:.55rem;margin-right:5px;"></i><?= htmlspecialchars($s) ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                <?php } ?>
            </div>
        </div>

        <!-- Metrics strip -->
        <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;">
            <?php
            $metrics = [
                ['Profile Views', $p['profile_views'],   'fa-eye',         '#3b82f6'],
                ['Version',       'v'.$p['version'],      'fa-code-branch', '#7c3aed'],
                ['Published',     $p['is_published'] ? 'Live' : 'Draft', 'fa-globe', $p['is_published'] ? '#10b981' : '#f59e0b'],
                ['Verified',      $p['is_verified']  ? 'Yes' : 'No',     'fa-shield-halved', $p['is_verified'] ? '#10b981' : '#94a3b8'],
            ];
            foreach ($metrics as [$label,$val,$icon,$color]): ?>
            <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:9px 12px;display:flex;align-items:center;gap:8px;">
                <i class="fas <?= $icon ?>" style="color:<?= $color ?>;font-size:.88rem;width:16px;text-align:center;flex-shrink:0;"></i>
                <div>
                    <div style="font-size:.58rem;text-transform:uppercase;letter-spacing:.05em;color:#64748b;font-weight:600;"><?= htmlspecialchars($label) ?></div>
                    <div style="font-size:.85rem;font-weight:700;color:#0f172a;"><?= htmlspecialchars((string)$val) ?></div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

    </div>
    <?php
    exit;
}

// ── AJAX: Approve / Reject / Request Changes ──────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    header('Content-Type: application/json');

    $action     = $_POST['ajax_action'];
    $profile_id = (int)($_POST['profile_id'] ?? 0);
    $note       = trim($_POST['admin_note'] ?? '');

    if (!$profile_id) { echo json_encode(['success'=>false,'message'=>'Invalid profile ID']); exit; }

    $stmt = $pdo->prepare("
        SELECT rpp.*, u.first_name, u.last_name
        FROM reviewer_public_profile rpp
        JOIN users u ON u.user_id = rpp.user_id
        WHERE rpp.id = ?
    ");
    $stmt->execute([$profile_id]);
    $profile = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$profile) { echo json_encode(['success'=>false,'message'=>'Profile not found']); exit; }

    try {
        if ($action === 'approve') {
            $pending = $profile['pending_changes'] ? json_decode($profile['pending_changes'], true) : null;
            if ($pending) {
                $fields = ['bio','current_position','total_experience_yrs','h_index',
                           'total_citations','orcid_id','website_url','profile_affiliation_id',
                           'education','publications','societies'];
                $sets = []; $vals = [];
                foreach ($fields as $f) {
                    if (array_key_exists($f, $pending)) { $sets[] = "{$f} = ?"; $vals[] = $pending[$f]; }
                }
                if ($sets) {
                    $vals = array_merge($vals, [$_SESSION['user_id'], $note, $profile_id]);
                    $pdo->prepare("UPDATE reviewer_public_profile SET ".implode(', ',$sets).",
                        is_published=1, approval_status='approved', reviewed_at=NOW(),
                        reviewed_by=?, admin_note=?, pending_changes=NULL, version=version+1
                        WHERE id=?")->execute($vals);
                }
            } else {
                $pdo->prepare("UPDATE reviewer_public_profile SET is_published=1, approval_status='approved',
                    reviewed_at=NOW(), reviewed_by=?, admin_note=?, version=version+1
                    WHERE id=?")->execute([$_SESSION['user_id'], $note, $profile_id]);
            }
            echo json_encode(['success'=>true,'message'=>'Profile approved and published.']);

        } elseif ($action === 'reject') {
            $pdo->prepare("UPDATE reviewer_public_profile SET approval_status='rejected', is_published=0,
                reviewed_at=NOW(), reviewed_by=?, admin_note=?, pending_changes=NULL
                WHERE id=?")->execute([$_SESSION['user_id'], $note, $profile_id]);
            echo json_encode(['success'=>true,'message'=>'Profile rejected.']);

        } elseif ($action === 'request_changes') {
            $pdo->prepare("UPDATE reviewer_public_profile SET approval_status='changes_requested',
                reviewed_at=NOW(), reviewed_by=?, admin_note=?
                WHERE id=?")->execute([$_SESSION['user_id'], $note, $profile_id]);
            echo json_encode(['success'=>true,'message'=>'Change request sent to reviewer.']);

        } else {
            echo json_encode(['success'=>false,'message'=>'Unknown action']);
        }
    } catch (PDOException $e) {
        error_log('reviewer_profile_approvals: '.$e->getMessage());
        echo json_encode(['success'=>false,'message'=>'Database error: '.$e->getMessage()]);
    }
    exit;
}



// ── Filters / pagination ──────────────────────────────────────
$tab    = in_array($_GET['tab'] ?? '', ['pending','approved','rejected','changes_requested','all']) ? ($_GET['tab'] ?? 'pending') : 'pending';
$search = trim($_GET['q'] ?? '');
$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = 20;
$offset = ($page - 1) * $limit;

$where = []; $params = [];
if ($tab !== 'all') { $where[] = "rpp.approval_status = ?"; $params[] = $tab; }
if ($search) {
    $where[] = "(CONCAT(u.first_name,' ',u.last_name) LIKE ? OR u.institutional_email LIKE ? OR rpp.slug LIKE ?)";
    $s = "%{$search}%";
    $params = array_merge($params, [$s,$s,$s]);
}
$wsql = $where ? 'WHERE '.implode(' AND ',$where) : '';

// Tab counts
$counts = [];
foreach (['pending','approved','rejected','changes_requested'] as $st) {
    $cs = $pdo->prepare("SELECT COUNT(*) FROM reviewer_public_profile rpp JOIN users u ON u.user_id=rpp.user_id WHERE rpp.approval_status=?");
    $cs->execute([$st]);
    $counts[$st] = (int)$cs->fetchColumn();
}

// Main query
$total = 0; $items = [];
try {
    $ts = $pdo->prepare("SELECT COUNT(*) FROM reviewer_public_profile rpp JOIN users u ON u.user_id=rpp.user_id LEFT JOIN affiliations a ON a.affiliation_id=COALESCE(rpp.profile_affiliation_id,u.affiliation_id) {$wsql}");
    $ts->execute($params);
    $total = (int)$ts->fetchColumn();

    $ds = $pdo->prepare("
        SELECT rpp.id, rpp.slug, rpp.approval_status, rpp.submitted_at, rpp.reviewed_at,
               rpp.updated_at, rpp.admin_note, rpp.is_published, rpp.version,
               rpp.pending_changes,
               u.user_id, u.first_name, u.last_name, u.title AS user_title,
               u.institutional_email, u.country,
               a.name AS affil_name,
               ra.first_name AS rev_by_fname, ra.last_name AS rev_by_lname
        FROM reviewer_public_profile rpp
        JOIN  users u ON u.user_id = rpp.user_id
        LEFT JOIN affiliations a ON a.affiliation_id = COALESCE(rpp.profile_affiliation_id, u.affiliation_id)
        LEFT JOIN users ra ON ra.user_id = rpp.reviewed_by
        {$wsql}
        ORDER BY
            CASE rpp.approval_status WHEN 'pending' THEN 0 WHEN 'changes_requested' THEN 1 ELSE 2 END,
            GREATEST(COALESCE(rpp.submitted_at,'2000-01-01'), COALESCE(rpp.updated_at,'2000-01-01')) DESC
        LIMIT {$limit} OFFSET {$offset}
    ");
    $ds->execute($params);
    $items = $ds->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log('reviewer_profile_approvals list: '.$e->getMessage());
}

$total_pages = max(1, ceil($total / $limit));

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

function statusBadgeHtml(string $s): string {
    $map = [
        'pending'           => ['#f59e0b','#fffbeb','fa-clock',        'Pending'],
        'approved'          => ['#10b981','#f0fdf4','fa-check-circle', 'Approved'],
        'rejected'          => ['#ef4444','#fef2f2','fa-times-circle', 'Rejected'],
        'changes_requested' => ['#3b82f6','#eff6ff','fa-edit',         'Changes Requested'],
    ];
    [$color,$bg,$icon,$label] = $map[$s] ?? ['#64748b','#f8fafc','fa-question','Unknown'];
    return "<span style='display:inline-flex;align-items:center;gap:4px;background:{$bg};color:{$color};border:1px solid {$color}33;border-radius:20px;padding:3px 9px;font-size:.7rem;font-weight:700;white-space:nowrap;'>
        <i class='fas {$icon}' style='font-size:.58rem;'></i>{$label}</span>";
}

function latestActivityHtml(array $item): string {
    $status   = $item['approval_status'];
    $isUpdate = !empty($item['pending_changes']);
    $bg     = $isUpdate ? '#fffbeb' : '#eff6ff';
    $border = $isUpdate ? '#fcd34d' : '#bfdbfe';

    if (in_array($status, ['pending','changes_requested']) && $item['submitted_at']) {
        $ts = strtotime($item['submitted_at']);
        $upd = ($item['updated_at'] && $item['updated_at'] !== $item['submitted_at'])
            ? "<div style='font-size:.6rem;color:#94a3b8;margin-top:2px;'>Updated: ".date('d M Y H:i', strtotime($item['updated_at']))."</div>"
            : '';
        return "<div style='background:{$bg};border:1px solid {$border};border-radius:7px;padding:6px 10px;'>
            <div style='font-size:.8rem;font-weight:700;color:#0f172a;'>".date('d M Y',$ts)."</div>
            <div style='font-size:.7rem;color:#64748b;'>".date('H:i',$ts)."</div>
            <div style='font-size:.63rem;font-weight:700;color:#f59e0b;margin-top:2px;'>Awaiting review</div>
            {$upd}</div>";
    }
    if (in_array($status, ['approved','rejected']) && $item['reviewed_at']) {
        $ts    = strtotime($item['reviewed_at']);
        $color = $status === 'approved' ? '#10b981' : '#ef4444';
        $lbl   = $status === 'approved' ? 'Approved' : 'Rejected';
        return "<div style='background:#f8fafc;border:1px solid #e2e8f0;border-radius:7px;padding:6px 10px;'>
            <div style='font-size:.8rem;font-weight:700;color:#0f172a;'>".date('d M Y',$ts)."</div>
            <div style='font-size:.7rem;color:#64748b;'>".date('H:i',$ts)."</div>
            <div style='font-size:.63rem;font-weight:700;color:{$color};margin-top:2px;'>{$lbl}</div>
        </div>";
    }
    if ($item['updated_at']) {
        $ts = strtotime($item['updated_at']);
        return "<div style='background:#f8fafc;border:1px solid #e2e8f0;border-radius:7px;padding:6px 10px;'>
            <div style='font-size:.8rem;font-weight:700;color:#0f172a;'>".date('d M Y',$ts)."</div>
            <div style='font-size:.7rem;color:#64748b;'>".date('H:i',$ts)."</div>
        </div>";
    }
    return '<span style="color:#94a3b8;font-size:.8rem;">—</span>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Reviewer Profile Approvals — Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></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:#0F172A; color:#E2E8F0; }

/* ── Sidebar (matches reviewer-due-dates.php exactly) ── */
.sidebar { width:250px;background:#1E293B;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,.sidebar.collapsed nav ul li a span { 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:#334155; }
.nav-item.active { background:#334155;border-left:3px solid #3B82F6; }
@media(max-width:768px){
    .sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}
}

/* ── Dark mode ── */
body.dark .bg-white{background:#1E293B}
body.dark .bg-slate-100,.dark .bg-gray-50,.dark .bg-gray-100{background:#0F172A}
body.dark .border-gray-200{border-color:#334155}
body.dark .text-gray-800{color:#F1F5F9}
body.dark .text-gray-700{color:#CBD5E1}
body.dark .text-gray-600{color:#94A3B8}
body.dark .text-gray-500{color:#64748B}
body.dark select,body.dark input,body.dark textarea{background:#334155;border-color:#475569;color:#E2E8F0}
body.dark .data-table th{background:#0F172A;border-color:#334155;color:#64748B}
body.dark .data-table td{border-color:#1E293B}
body.dark .data-table tr:hover td{background:#1E293B}
body.dark .stat-card{background:#1E293B;border-color:#334155}
body.dark .tab-bar{background:#1E293B;border-color:#334155}
body.dark .tab-btn{color:#94A3B8}
body.dark .tab-btn:hover{background:#334155;color:#E2E8F0}
body.dark .tab-btn.tab-active{color:#6366F1;border-color:#6366F1}
body.dark .filter-card{background:#1E293B;border-color:#334155}

/* ── Tabs ── */
.tab-bar{background:white;border-bottom:1px solid #E5E7EB}
.tab-btn{padding:12px 20px;font-size:13.5px;font-weight:500;color:#6B7280;border-bottom:3px solid transparent;cursor:pointer;transition:all .15s;white-space:nowrap;background:none;border-top:0;border-left:0;border-right:0}
.tab-btn:hover{background:#F9FAFB;color:#374151}
.tab-btn.tab-active{color:#4F46E5;border-bottom-color:#4F46E5;font-weight:700}
.tab-pane{display:none}.tab-pane.active{display:block}

/* ── Form inputs ── */
.inp{width:100%;border:1px solid #D1D5DB;border-radius:8px;padding:7px 11px;font-size:13px;color:#374151;outline:none;background:white;transition:border-color .15s}
.inp:focus{border-color:#6366F1;box-shadow:0 0 0 2px rgba(99,102,241,.1)}
body.dark .inp{background:#334155;border-color:#475569;color:#E2E8F0}

/* ── Cards ── */
.stat-card{background:white;border-radius:12px;border:1px solid #E2E8F0;padding:18px 20px}
.filter-card{background:white;border:1px solid #E5E7EB;border-radius:12px;padding:16px}

/* ── Table ── */
.data-table{width:100%;border-collapse:collapse;font-size:13px}
.data-table th{background:#F9FAFB;padding:9px 12px;text-align:left;font-size:11px;font-weight:700;color:#6B7280;text-transform:uppercase;letter-spacing:.4px;border-bottom:1px solid #E5E7EB;white-space:nowrap;position:sticky;top:0;z-index:1}
.data-table td{padding:9px 12px;border-bottom:1px solid #F3F4F6;vertical-align:middle}
.data-table tr:hover td{background:#F9FAFB}
.act-btn{padding:5px 8px;border-radius:6px;font-size:12px;cursor:pointer;transition:all .15s;border:none;background:transparent}
.act-btn:hover{opacity:.8;transform:scale(1.1)}

/* ── Detail modal ── */
#detailModal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:50;align-items:center;justify-content:center}
#detailModal.open{display:flex}
#detailModalInner{background:white;border-radius:14px;width:92%;max-width:880px;max-height:88vh;overflow-y:auto;box-shadow:0 25px 60px rgba(0,0,0,.25)}
body.dark #detailModalInner{background:#1E293B;color:#E2E8F0}
.modal-header{position:sticky;top:0;background:white;z-index:2;padding:14px 20px;border-bottom:1px solid #e2e8f0;display:flex;align-items:center;justify-content:space-between}
body.dark .modal-header{background:#1E293B;border-color:#334155}

/* ── Action modal ── */
#actionModal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:60;align-items:center;justify-content:center}
#actionModal.open{display:flex}
#actionModalInner{background:white;border-radius:14px;width:92%;max-width:520px;box-shadow:0 25px 60px rgba(0,0,0,.25);overflow:hidden}
body.dark #actionModalInner{background:#1E293B;color:#E2E8F0}
</style>
</head>
<body class="bg-slate-100">

<button onclick="toggleMobile()" class="fixed top-3 left-3 z-20 bg-slate-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-400 hover:text-gray-600 hidden md:block">
        <i class="fas fa-bars text-lg"></i>
      </button>
      <i class="fas fa-user-check text-indigo-600 text-xl"></i>
      <span class="font-bold text-gray-800 text-lg">Reviewer Profile Approvals</span>
    </div>
    <div class="flex items-center gap-3">
      <span class="text-xs text-gray-400 bg-gray-100 px-3 py-1 rounded-full">
        <?= $total ?> profiles · <?= array_sum($counts) ?> total submissions
      </span>
      <button id="darkToggle" class="text-gray-400 hover:text-gray-600 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
        <i class="fas fa-moon text-sm"></i>
      </button>
    </div>
  </div>

  <!-- ── Tab bar ── -->
  <div class="tab-bar flex overflow-x-auto sticky top-[65px] z-10 shadow-sm mt-3">
    <button class="tab-btn tab-active" data-tab="approvals">✅ Profile Approvals</button>
  </div>

  <!-- ══ TAB: APPROVALS ══════════════════════════════════════ -->
  <div id="tab-approvals" class="tab-pane active">
  <div class="p-5 space-y-5">

    <!-- Stat cards -->
    <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
      <?php
      $statDefs = [
        ['pending',           'Pending Review',    'fa-clock',        '#f59e0b','#fffbeb','#fcd34d'],
        ['approved',          'Approved & Live',   'fa-check-circle', '#10b981','#f0fdf4','#a7f3d0'],
        ['rejected',          'Rejected',          'fa-times-circle', '#ef4444','#fef2f2','#fecaca'],
        ['changes_requested', 'Changes Requested', 'fa-edit',         '#3b82f6','#eff6ff','#bfdbfe'],
      ];
      foreach ($statDefs as [$key,$label,$icon,$color,$bg,$border]):
        $ring = ($tab === $key) ? "ring:2px ring:{$color};" : '';
      ?>
      <a href="?tab=<?= $key ?><?= $search?'&q='.urlencode($search):'' ?>" style="text-decoration:none;">
        <div class="stat-card flex items-center gap-4" style="border-left:4px solid <?= $color ?>;<?= ($tab===$key)?'box-shadow:0 0 0 2px '.$color.';':'' ?>">
          <div style="width:40px;height:40px;border-radius:10px;background:<?= $bg ?>;border:1px solid <?= $border ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="fas <?= $icon ?>" style="color:<?= $color ?>;font-size:1rem;"></i>
          </div>
          <div>
            <div style="font-size:1.8rem;font-weight:700;color:<?= $color ?>;line-height:1;"><?= $counts[$key] ?? 0 ?></div>
            <div class="text-gray-500" style="font-size:.75rem;margin-top:2px;"><?= $label ?></div>
          </div>
        </div>
      </a>
      <?php endforeach; ?>
    </div>

    <!-- Filter bar -->
    <div class="filter-card">
      <form method="GET">
        <div class="flex flex-wrap gap-3 items-end">
          <div>
            <label class="block text-xs text-gray-500 mb-1">Status</label>
            <select name="tab" class="inp" style="width:175px;">
              <option value="all"               <?= $tab==='all'               ?'selected':'' ?>>All</option>
              <option value="pending"           <?= $tab==='pending'           ?'selected':'' ?>>Pending</option>
              <option value="approved"          <?= $tab==='approved'          ?'selected':'' ?>>Approved</option>
              <option value="rejected"          <?= $tab==='rejected'          ?'selected':'' ?>>Rejected</option>
              <option value="changes_requested" <?= $tab==='changes_requested' ?'selected':'' ?>>Changes Requested</option>
            </select>
          </div>
          <div>
            <label class="block text-xs text-gray-500 mb-1">Search Reviewer</label>
            <input type="text" name="q" class="inp" style="width:230px;" placeholder="Name, email or slug…" value="<?= esc($search) ?>">
          </div>
          <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-2 rounded-lg text-sm font-bold flex items-center gap-2">
            <i class="fas fa-filter text-xs"></i> Apply
          </button>
          <a href="reviewer_profile_approvals.php" class="border border-gray-300 text-gray-600 hover:bg-gray-50 px-5 py-2 rounded-lg text-sm font-bold flex items-center gap-2">
            <i class="fas fa-times text-xs"></i> Clear
          </a>
        </div>
      </form>
    </div>

    <!-- Table -->
    <div class="bg-white border border-gray-200 rounded-xl overflow-hidden">
      <div class="px-5 py-3 border-b border-gray-100 flex items-center gap-3 flex-wrap">
        <span class="text-sm font-bold text-gray-700">Profile Submissions</span>
        <span class="text-xs bg-indigo-50 text-indigo-600 font-bold px-2 py-0.5 rounded-full"><?= $total ?></span>
        <span class="text-xs text-blue-600 bg-blue-50 px-2 py-0.5 rounded">🔵 New Profile</span>
        <span class="text-xs text-amber-600 bg-amber-50 px-2 py-0.5 rounded">🟡 Update</span>
      </div>

      <div style="overflow-x:auto;max-height:600px;">
        <table class="data-table">
          <thead>
            <tr>
              <th style="padding-left:20px;">#</th>
              <th>Reviewer</th>
              <th>Institution</th>
              <th>Type</th>
              <th>Status</th>
              <th>Latest Activity</th>
              <th>Reviewed By</th>
              <th class="text-center" style="padding-right:16px;">Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (empty($items)): ?>
          <tr><td colspan="8" class="text-center py-16 text-gray-400">
            <i class="fas fa-user-check text-5xl mb-3 block text-gray-200"></i>
            No profile submissions found<?= $search ? ' for "'.esc($search).'"' : '' ?>.
          </td></tr>
          <?php endif; ?>

          <?php
          $avatarColors = ['#1a3a8f','#0d6efd','#059669','#7c3aed','#dc2626','#b45309','#0891b2'];
          foreach ($items as $idx => $item):
            $initials = strtoupper(substr($item['first_name'],0,1).substr($item['last_name'],0,1));
            $avatarBg = $avatarColors[$idx % count($avatarColors)];
            $isUpdate = !empty($item['pending_changes']);
            $hasNote  = !empty($item['admin_note']);
            $revBy    = $item['rev_by_fname'] ? esc(trim($item['rev_by_fname'].' '.$item['rev_by_lname'])) : '—';
            $fullName = esc(($item['user_title']?$item['user_title'].'. ':'').trim($item['first_name'].' '.$item['last_name']));
          ?>
          <tr>
            <td style="padding-left:20px;font-size:.78rem;color:#94a3b8;"><?= $offset+$idx+1 ?></td>

            <!-- Reviewer -->
            <td>
              <div style="display:flex;align-items:center;gap:10px;">
                <div style="width:38px;height:38px;border-radius:8px;background:<?= $avatarBg ?>;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.8rem;color:#fff;flex-shrink:0;">
                  <?= esc($initials) ?>
                </div>
                <div>
                  <div style="font-weight:700;font-size:.85rem;color:#0f172a;"><?= $fullName ?></div>
                  <div style="font-size:.72rem;color:#64748b;"><?= esc($item['institutional_email'] ?? '') ?></div>
                  <?php if ($item['slug']): ?>
                  <a href="https://communeglobal.com/reviewer-profile3.php?slug=<?= urlencode($item['slug']) ?>"
                     target="_blank" style="font-size:.68rem;color:#6366f1;text-decoration:none;">
                    <i class="fas fa-external-link-alt" style="font-size:.55rem;margin-right:2px;"></i>/<?= esc($item['slug']) ?>
                  </a>
                  <?php endif; ?>
                </div>
              </div>
            </td>

            <!-- Institution -->
            <td>
              <div style="font-size:.83rem;color:#374151;"><?= esc($item['affil_name'] ?? '—') ?></div>
              <div style="font-size:.72rem;color:#64748b;"><?= esc($item['country'] ?? '') ?></div>
            </td>

            <!-- Type -->
            <td>
              <?php if ($isUpdate): ?>
              <span style="display:inline-flex;align-items:center;gap:4px;background:#fffbeb;color:#92400e;border:1px solid #fcd34d;border-radius:20px;padding:3px 9px;font-size:.7rem;font-weight:700;">
                <i class="fas fa-sync" style="font-size:.58rem;"></i> Update
              </span>
              <?php else: ?>
              <span style="display:inline-flex;align-items:center;gap:4px;background:#eff6ff;color:#1e40af;border:1px solid #bfdbfe;border-radius:20px;padding:3px 9px;font-size:.7rem;font-weight:700;">
                <i class="fas fa-plus-circle" style="font-size:.58rem;"></i> New
              </span>
              <?php endif; ?>
              <?php if ($item['version'] > 1): ?>
              <div style="font-size:.65rem;color:#94a3b8;margin-top:2px;">v<?= $item['version'] ?></div>
              <?php endif; ?>
            </td>

            <!-- Status -->
            <td><?= statusBadgeHtml($item['approval_status']) ?></td>

            <!-- Latest Activity -->
            <td style="min-width:130px;"><?= latestActivityHtml($item) ?></td>

            <!-- Reviewed By -->
            <td style="font-size:.8rem;color:#374151;"><?= $revBy ?></td>

            <!-- Actions -->
            <td class="text-center" style="padding-right:16px;">
              <div style="display:flex;align-items:center;justify-content:center;gap:4px;">
                <button onclick="openDetail(<?= $item['id'] ?>)"
                        class="act-btn" style="color:#4f46e5;background:#eff6ff;border:1px solid #bfdbfe;" title="View Details">
                  <i class="fas fa-eye"></i>
                </button>

                <?php if (in_array($item['approval_status'], ['pending','changes_requested'])): ?>
                <button onclick="openAction(<?= $item['id'] ?>, 'approve', '<?= esc(addslashes(($item['user_title']?$item['user_title'].'. ':'').trim($item['first_name'].' '.$item['last_name']))) ?>')"
                        class="act-btn" style="color:#166534;background:#f0fdf4;border:1px solid #a7f3d0;" title="Approve">
                  <i class="fas fa-check"></i>
                </button>
                <button onclick="openAction(<?= $item['id'] ?>, 'request_changes', '<?= esc(addslashes(($item['user_title']?$item['user_title'].'. ':'').trim($item['first_name'].' '.$item['last_name']))) ?>')"
                        class="act-btn" style="color:#1e40af;background:#eff6ff;border:1px solid #bfdbfe;" title="Request Changes">
                  <i class="fas fa-edit"></i>
                </button>
                <button onclick="openAction(<?= $item['id'] ?>, 'reject', '<?= esc(addslashes(($item['user_title']?$item['user_title'].'. ':'').trim($item['first_name'].' '.$item['last_name']))) ?>')"
                        class="act-btn" style="color:#991b1b;background:#fef2f2;border:1px solid #fecaca;" title="Reject">
                  <i class="fas fa-times"></i>
                </button>

                <?php elseif ($item['approval_status'] === 'approved'): ?>
                <button onclick="openAction(<?= $item['id'] ?>, 'reject', '<?= esc(addslashes(($item['user_title']?$item['user_title'].'. ':'').trim($item['first_name'].' '.$item['last_name']))) ?>')"
                        class="act-btn" style="color:#92400e;background:#fffbeb;border:1px solid #fcd34d;" title="Unpublish">
                  <i class="fas fa-ban"></i>
                </button>
                <?php endif; ?>
              </div>
            </td>
          </tr>

          <!-- Inline admin note row -->
          <?php if ($hasNote): ?>
          <tr style="background:#fefce8;">
            <td colspan="8" style="padding:5px 20px;font-size:.75rem;color:#92400e;border-bottom:1px solid #fde68a;">
              <i class="fas fa-comment-alt" style="margin-right:5px;"></i>
              <strong>Admin note:</strong> <?= esc($item['admin_note']) ?>
            </td>
          </tr>
          <?php endif; ?>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <?php if ($total_pages > 1): ?>
      <div class="flex justify-between items-center px-5 py-3 border-t border-gray-100">
        <span class="text-xs text-gray-500">Showing <?= $offset+1 ?>–<?= min($offset+$limit,$total) ?> of <?= $total ?></span>
        <div class="flex gap-1">
          <a href="?tab=<?= esc($tab) ?>&page=<?= $page-1 ?><?= $search?'&q='.urlencode($search):'' ?>"
             class="px-3 py-1.5 rounded-lg border border-gray-200 text-sm text-gray-500 <?= $page<=1?'pointer-events-none opacity-40':'' ?>">‹</a>
          <?php for ($pg = max(1,$page-2); $pg <= min($total_pages,$page+2); $pg++): ?>
          <a href="?tab=<?= esc($tab) ?>&page=<?= $pg ?><?= $search?'&q='.urlencode($search):'' ?>"
             class="px-3 py-1.5 rounded-lg border text-sm <?= $pg===$page?'bg-indigo-600 text-white border-indigo-600':'border-gray-200 text-gray-600 hover:bg-gray-50' ?>"><?= $pg ?></a>
          <?php endfor; ?>
          <a href="?tab=<?= esc($tab) ?>&page=<?= $page+1 ?><?= $search?'&q='.urlencode($search):'' ?>"
             class="px-3 py-1.5 rounded-lg border border-gray-200 text-sm text-gray-500 <?= $page>=$total_pages?'pointer-events-none opacity-40':'' ?>">›</a>
        </div>
      </div>
      <?php endif; ?>
    </div>

  </div>
  </div>

</div><!-- /content -->

<!-- ══ DETAIL MODAL ════════════════════════════════════════════ -->
<div id="detailModal">
  <div id="detailModalInner">
    <div class="modal-header">
      <div class="flex items-center gap-2">
        <i class="fas fa-eye text-indigo-600"></i>
        <span class="font-bold text-gray-800 text-sm">Profile Details</span>
      </div>
      <div class="flex items-center gap-2">
        <button id="detailApproveBtn"
                style="background:#10b981;color:white;border:none;padding:6px 14px;border-radius:8px;font-size:.82rem;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:6px;">
          <i class="fas fa-check" style="font-size:.7rem;"></i> Approve
        </button>
        <button onclick="closeDetail()"
                style="background:none;border:1px solid #e2e8f0;border-radius:8px;width:32px;height:32px;cursor:pointer;color:#64748b;font-size:.85rem;">
          <i class="fas fa-times"></i>
        </button>
      </div>
    </div>
    <div id="detailBody">
      <div class="text-center py-16 text-gray-400">
        <i class="fas fa-spinner fa-spin text-3xl mb-2 block"></i>Loading…
      </div>
    </div>
  </div>
</div>

<!-- ══ ACTION MODAL ════════════════════════════════════════════ -->
<div id="actionModal">
  <div id="actionModalInner">
    <div style="padding:16px 20px;border-bottom:1px solid #e2e8f0;display:flex;align-items:center;justify-content:space-between;">
      <span id="actionModalTitle" style="font-weight:700;font-size:.95rem;color:#0f172a;">Confirm Action</span>
      <button onclick="closeActionModal()" style="background:none;border:none;cursor:pointer;color:#64748b;font-size:.9rem;"><i class="fas fa-times"></i></button>
    </div>
    <div style="padding:18px 20px;">
      <div id="actionDesc" style="font-size:.88rem;color:#374151;margin-bottom:14px;"></div>
      <label style="display:block;font-size:.75rem;font-weight:700;color:#64748b;margin-bottom:4px;">
        Note to reviewer <span style="font-weight:400;color:#94a3b8;">(optional for approve, required for reject/changes)</span>
      </label>
      <textarea id="actionNote" class="inp" rows="4"
                placeholder="Explain the decision or what needs to be changed…"
                style="resize:vertical;"></textarea>
      <div id="actionAlert" style="display:none;margin-top:10px;font-size:.83rem;border-radius:8px;padding:8px 12px;"></div>
    </div>
    <div style="padding:10px 20px 18px;display:flex;gap:10px;justify-content:flex-end;">
      <button onclick="closeActionModal()"
              style="border:1px solid #d1d5db;background:white;color:#374151;padding:8px 20px;border-radius:8px;font-size:.85rem;font-weight:700;cursor:pointer;">
        Cancel
      </button>
      <button id="actionConfirmBtn" onclick="submitAction()"
              style="color:white;padding:8px 20px;border-radius:8px;font-size:.85rem;font-weight:700;cursor:pointer;border:none;display:flex;align-items:center;gap:6px;">
        <i class="fas fa-check"></i> Confirm
      </button>
    </div>
  </div>
</div>

<script>
/* ── Sidebar (identical to reviewer-due-dates.php) ────────────── */
let sc = false;
function toggleMobile() { document.getElementById('sidebar')?.classList.toggle('mobile-open'); }
function toggleSidebar() {
    sc = !sc;
    document.getElementById('sidebar')?.classList.toggle('collapsed', sc);
    document.getElementById('content')?.classList.toggle('collapsed-sidebar', sc);
}

/* ── Dark mode ───────────────────────────────────────────────── */
document.getElementById('darkToggle').addEventListener('click', function () {
    document.body.classList.toggle('dark');
    this.querySelector('i').classList.toggle('fa-moon');
    this.querySelector('i').classList.toggle('fa-sun');
    localStorage.setItem('dm', document.body.classList.contains('dark') ? '1' : '0');
});
if (localStorage.getItem('dm') === '1') {
    document.body.classList.add('dark');
    document.getElementById('darkToggle').querySelector('i').classList.replace('fa-moon', 'fa-sun');
}

/* ── Tabs ────────────────────────────────────────────────────── */
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('tab-active'));
        btn.classList.add('tab-active');
        document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
        document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
    });
});

/* ── Detail modal ────────────────────────────────────────────── */
function openDetail(id) {
    document.getElementById('detailModal').classList.add('open');
    document.getElementById('detailBody').innerHTML =
        '<div class="text-center py-16 text-gray-400"><i class="fas fa-spinner fa-spin text-3xl mb-2 block"></i>Loading…</div>';

    document.getElementById('detailApproveBtn').onclick = function () {
        closeDetail();
        openAction(id, 'approve', '');
    };

    fetch('reviewer_profile_approvals.php?detail_id=' + id)
        .then(r => r.text())
        .then(html => { document.getElementById('detailBody').innerHTML = html; })
        .catch(() => {
            document.getElementById('detailBody').innerHTML =
                '<div class="text-center py-16 text-red-400"><i class="fas fa-exclamation-circle text-3xl mb-2 block"></i>Failed to load details.</div>';
        });
}
function closeDetail() { document.getElementById('detailModal').classList.remove('open'); }
document.getElementById('detailModal').addEventListener('click', function (e) { if (e.target === this) closeDetail(); });

/* ── Action modal ────────────────────────────────────────────── */
let currentProfileId = null, currentActionType = null;

function openAction(profileId, action, name) {
    currentProfileId  = profileId;
    currentActionType = action;

    const titles = { approve:'Approve Profile', reject:'Reject Profile', request_changes:'Request Changes' };
    const descs  = {
        approve:         `You are about to <strong>approve and publish</strong> the profile for <strong>${name || 'this reviewer'}</strong>. They will receive an email notification.`,
        reject:          `You are about to <strong>reject</strong> the profile for <strong>${name || 'this reviewer'}</strong>. Please provide a reason below.`,
        request_changes: `You are requesting <strong>changes</strong> from <strong>${name || 'this reviewer'}</strong>. Please describe what needs to be updated.`,
    };
    const btnColors = { approve:'#10b981', reject:'#ef4444', request_changes:'#3b82f6' };

    document.getElementById('actionModalTitle').textContent = titles[action] || 'Confirm';
    document.getElementById('actionDesc').innerHTML         = descs[action]  || '';
    document.getElementById('actionNote').value             = '';
    const alertEl = document.getElementById('actionAlert');
    alertEl.style.display = 'none'; alertEl.textContent = '';

    const btn = document.getElementById('actionConfirmBtn');
    btn.style.background = btnColors[action] || '#4F46E5';
    btn.innerHTML = `<i class="fas fa-check"></i> ${titles[action] || 'Confirm'}`;
    btn.disabled  = false;

    document.getElementById('actionModal').classList.add('open');
}
function closeActionModal() { document.getElementById('actionModal').classList.remove('open'); }
document.getElementById('actionModal').addEventListener('click', function (e) { if (e.target === this) closeActionModal(); });

function submitAction() {
    const note    = document.getElementById('actionNote').value.trim();
    const alertEl = document.getElementById('actionAlert');

    if ((currentActionType === 'reject' || currentActionType === 'request_changes') && !note) {
        alertEl.style.display = 'block';
        alertEl.style.background = '#fffbeb';
        alertEl.style.color      = '#92400e';
        alertEl.style.border     = '1px solid #fcd34d';
        alertEl.textContent = 'Please provide a note explaining the decision.';
        return;
    }

    const btn = document.getElementById('actionConfirmBtn');
    btn.disabled  = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing…';

    const fd = new FormData();
    fd.append('ajax_action', currentActionType);
    fd.append('profile_id',  currentProfileId);
    fd.append('admin_note',  note);

    fetch('reviewer_profile_approvals.php', { method:'POST', body:fd })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                closeActionModal();
                Swal.fire({ icon:'success', title:'Done!', text:data.message, timer:2000, showConfirmButton:false });
                setTimeout(() => location.reload(), 1800);
            } else {
                alertEl.style.display    = 'block';
                alertEl.style.background = '#fef2f2';
                alertEl.style.color      = '#991b1b';
                alertEl.style.border     = '1px solid #fecaca';
                alertEl.textContent = data.message || 'Something went wrong.';
                btn.disabled  = false;
                btn.innerHTML = '<i class="fas fa-check"></i> Confirm';
            }
        })
        .catch(() => {
            alertEl.style.display    = 'block';
            alertEl.style.background = '#fef2f2';
            alertEl.style.color      = '#991b1b';
            alertEl.style.border     = '1px solid #fecaca';
            alertEl.textContent = 'Network error. Please try again.';
            btn.disabled  = false;
            btn.innerHTML = '<i class="fas fa-check"></i> Confirm';
        });
}
</script>
</body>
</html>