<?php
/**
 * author_profile.php
 * Place at: /journals/author_profile.php
 * URL: /journals/author_profile.php?username=ayushigautam6528
 *      OR /journals/author_profile.php?id=USER_ID
 *
 * Shows:
 *  - Author bio / stats
 *  - Published articles (where this user is an author)  + SIQ count per article
 *  - Reviewed articles (from editorial_decisions / reviewers tables) + SIQ count
 */

if (session_status() === PHP_SESSION_NONE) session_start();
ini_set('display_errors', 0); error_reporting(0);
include_once __DIR__ . '/../config/db_new.php';

/* ═══════════════════════════════════════════════════
   RESOLVE USER
═══════════════════════════════════════════════════ */
$username   = trim($_GET['username'] ?? '');
$userId     = (int)($_GET['id'] ?? 0);
$userRow    = null;

if ($pdo) {
    try {
        if ($username !== '') {
            $st = $pdo->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
            $st->execute([$username]);
        } elseif ($userId > 0) {
            $st = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
            $st->execute([$userId]);
        }
        if (isset($st)) $userRow = $st->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {}
}

/* ── Fall back: look up by email match in submission_authors ── */
$authorEmail  = $userRow['email'] ?? '';
$authorFirst  = $userRow['first_name'] ?? ($userRow['name'] ?? '');
$authorLast   = $userRow['last_name'] ?? '';
$displayName  = trim($authorFirst.' '.$authorLast) ?: ($userRow['username'] ?? $username ?: 'Author');
$profilePic   = $userRow['profile_photo'] ?? ($userRow['avatar'] ?? '');
$institution  = $userRow['institution'] ?? ($userRow['university'] ?? ($userRow['affiliation'] ?? ''));
$bio          = $userRow['bio'] ?? ($userRow['about'] ?? '');
$orcid        = $userRow['orcid'] ?? '';
$profileEmail = $userRow['email'] ?? '';

/* ═══════════════════════════════════════════════════
   PUBLISHED ARTICLES (author on submission_authors)
   — match by user_id, OR email, OR first+last name
═══════════════════════════════════════════════════ */
$publishedArticles = [];
if ($pdo) {
    try {
        /* Build WHERE clause: try user_id first, then email, then name */
        $conditions = [];
        $params     = [];

        if (!empty($userRow['id'])) {
            $conditions[] = 'sa.user_id = ?';
            $params[]     = (int)$userRow['id'];
        }
        if ($authorEmail !== '') {
            $conditions[] = 'sa.email = ?';
            $params[]     = $authorEmail;
        }
        if ($authorFirst !== '' && $authorLast !== '') {
            $conditions[] = '(sa.first_name = ? AND sa.last_name = ?)';
            $params[]     = $authorFirst;
            $params[]     = $authorLast;
        }
        /* If nothing to match on, try username as email prefix */
        if (empty($conditions) && $username !== '') {
            $conditions[] = 'sa.email LIKE ?';
            $params[]     = $username.'%';
        }

        if ($conditions) {
            $where = implode(' OR ', $conditions);
            $sql = "
                SELECT
                    s.submission_id,
                    mi.article_title,
                    mi.abstract,
                    pf.doi,
                    pf.page_no,
                    pf.publication_date,
                    pf.article_slug,
                    pf.published_pdf_path,
                    pf.volume_id,
                    jv.volume  AS vol_num,
                    jv.issue   AS vol_iss,
                    jv.year    AS vol_year,
                    j.name     AS journal_name,
                    j.slug     AS journal_slug,
                    sa.is_corresponding,
                    sa.author_order,
                    /* SIQ aggregate */
                    (SELECT COUNT(*) FROM article_siq_ratings asr
                     WHERE asr.submission_id = s.submission_id AND asr.status = 1)  AS siq_count,
                    (SELECT AVG(asr.siq_score) FROM article_siq_ratings asr
                     WHERE asr.submission_id = s.submission_id AND asr.status = 1)  AS siq_avg,
                    /* comment count */
                    (SELECT COUNT(*) FROM article_comments ac
                     WHERE ac.submission_id = s.submission_id AND ac.status = 1)    AS comment_count
                FROM submission_authors sa
                JOIN submissions s      ON s.submission_id  = sa.submission_id
                LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
                LEFT JOIN submission_files pf ON pf.submission_id = s.submission_id
                    AND pf.file_type IN ('payment_receipt','final_manuscript_revised','declaration_form')
                    AND pf.publication_date IS NOT NULL
                LEFT JOIN journal_volumes jv ON jv.id = pf.volume_id
                LEFT JOIN journals j         ON j.journal_id = s.journal_id
                WHERE ($where)
                GROUP BY s.submission_id
                ORDER BY pf.publication_date DESC, s.submission_id DESC
            ";
            $st2 = $pdo->prepare($sql);
            $st2->execute($params);
            $publishedArticles = $st2->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (PDOException $e) {}
}

/* ═══════════════════════════════════════════════════
   REVIEWED ARTICLES
   Try common table names: editorial_decisions, reviewers,
   submission_reviewers, review_assignments
═══════════════════════════════════════════════════ */
$reviewedArticles = [];
if ($pdo && !empty($userRow['id'])) {
    $rid = (int)$userRow['id'];
    /* ── Try editorial_decisions (reviewer_id column) ── */
    $reviewQueries = [
        /* editorial_decisions with reviewer_id */
        "SELECT
             s.submission_id,
             mi.article_title,
             pf.publication_date,
             pf.article_slug,
             j.name  AS journal_name,
             j.slug  AS journal_slug,
             jv.volume AS vol_num, jv.issue AS vol_iss, jv.year AS vol_year,
             ed.decision,
             ed.created_at AS reviewed_at,
             (SELECT COUNT(*) FROM article_siq_ratings asr
              WHERE asr.submission_id = s.submission_id AND asr.status=1) AS siq_count,
             (SELECT AVG(asr.siq_score) FROM article_siq_ratings asr
              WHERE asr.submission_id = s.submission_id AND asr.status=1) AS siq_avg
         FROM editorial_decisions ed
         JOIN submissions s      ON s.submission_id = ed.submission_id
         LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
         LEFT JOIN submission_files pf ON pf.submission_id = s.submission_id
             AND pf.file_type IN ('payment_receipt','final_manuscript_revised','declaration_form')
             AND pf.publication_date IS NOT NULL
         LEFT JOIN journal_volumes jv ON jv.id = pf.volume_id
         LEFT JOIN journals j         ON j.journal_id = s.journal_id
         WHERE ed.reviewer_id = ?
         GROUP BY s.submission_id
         ORDER BY ed.created_at DESC",

        /* submission_reviewers table */
        "SELECT
             s.submission_id,
             mi.article_title,
             pf.publication_date,
             pf.article_slug,
             j.name  AS journal_name,
             j.slug  AS journal_slug,
             jv.volume AS vol_num, jv.issue AS vol_iss, jv.year AS vol_year,
             sr.status AS decision,
             sr.assigned_at AS reviewed_at,
             (SELECT COUNT(*) FROM article_siq_ratings asr
              WHERE asr.submission_id = s.submission_id AND asr.status=1) AS siq_count,
             (SELECT AVG(asr.siq_score) FROM article_siq_ratings asr
              WHERE asr.submission_id = s.submission_id AND asr.status=1) AS siq_avg
         FROM submission_reviewers sr
         JOIN submissions s      ON s.submission_id = sr.submission_id
         LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
         LEFT JOIN submission_files pf ON pf.submission_id = s.submission_id
             AND pf.file_type IN ('payment_receipt','final_manuscript_revised','declaration_form')
             AND pf.publication_date IS NOT NULL
         LEFT JOIN journal_volumes jv ON jv.id = pf.volume_id
         LEFT JOIN journals j         ON j.journal_id = s.journal_id
         WHERE sr.user_id = ?
         GROUP BY s.submission_id
         ORDER BY sr.assigned_at DESC",

        /* review_assignments table */
        "SELECT
             s.submission_id,
             mi.article_title,
             pf.publication_date,
             pf.article_slug,
             j.name  AS journal_name,
             j.slug  AS journal_slug,
             jv.volume AS vol_num, jv.issue AS vol_iss, jv.year AS vol_year,
             ra.status AS decision,
             ra.created_at AS reviewed_at,
             (SELECT COUNT(*) FROM article_siq_ratings asr
              WHERE asr.submission_id = s.submission_id AND asr.status=1) AS siq_count,
             (SELECT AVG(asr.siq_score) FROM article_siq_ratings asr
              WHERE asr.submission_id = s.submission_id AND asr.status=1) AS siq_avg
         FROM review_assignments ra
         JOIN submissions s      ON s.submission_id = ra.submission_id
         LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
         LEFT JOIN submission_files pf ON pf.submission_id = s.submission_id
             AND pf.file_type IN ('payment_receipt','final_manuscript_revised','declaration_form')
             AND pf.publication_date IS NOT NULL
         LEFT JOIN journal_volumes jv ON jv.id = pf.volume_id
         LEFT JOIN journals j         ON j.journal_id = s.journal_id
         WHERE ra.reviewer_id = ?
         GROUP BY s.submission_id
         ORDER BY ra.created_at DESC",
    ];

    foreach ($reviewQueries as $q) {
        try {
            $st3 = $pdo->prepare($q);
            $st3->execute([$rid]);
            $rows = $st3->fetchAll(PDO::FETCH_ASSOC);
            if ($rows) { $reviewedArticles = $rows; break; }
        } catch (PDOException $e) { /* table doesn't exist — try next */ }
    }

    /* ── If still empty, try by email in editorial_decisions ── */
    if (empty($reviewedArticles) && $authorEmail !== '') {
        try {
            $st4 = $pdo->prepare("
                SELECT
                    s.submission_id,
                    mi.article_title,
                    pf.publication_date,
                    pf.article_slug,
                    j.name  AS journal_name,
                    j.slug  AS journal_slug,
                    jv.volume AS vol_num, jv.issue AS vol_iss, jv.year AS vol_year,
                    ed.decision,
                    ed.created_at AS reviewed_at,
                    (SELECT COUNT(*) FROM article_siq_ratings asr
                     WHERE asr.submission_id = s.submission_id AND asr.status=1) AS siq_count,
                    (SELECT AVG(asr.siq_score) FROM article_siq_ratings asr
                     WHERE asr.submission_id = s.submission_id AND asr.status=1) AS siq_avg
                FROM editorial_decisions ed
                JOIN submissions s      ON s.submission_id = ed.submission_id
                LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
                LEFT JOIN submission_files pf ON pf.submission_id = s.submission_id
                    AND pf.file_type IN ('payment_receipt','final_manuscript_revised','declaration_form')
                    AND pf.publication_date IS NOT NULL
                LEFT JOIN journal_volumes jv ON jv.id = pf.volume_id
                LEFT JOIN journals j         ON j.journal_id = s.journal_id
                WHERE ed.reviewer_email = ?
                GROUP BY s.submission_id
                ORDER BY ed.created_at DESC
            ");
            $st4->execute([$authorEmail]);
            $reviewedArticles = $st4->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {}
    }
}

/* ── Exclude from reviewed those already in published (overlap) ── */
$publishedIds = array_column($publishedArticles, 'submission_id');
$reviewedArticles = array_filter($reviewedArticles, fn($r) => !in_array($r['submission_id'], $publishedIds));

/* ── Summary stats ── */
$totalPublished  = count($publishedArticles);
$totalReviewed   = count($reviewedArticles);
$totalSiqRatings = array_sum(array_column($publishedArticles, 'siq_count'))
                 + array_sum(array_column($reviewedArticles,  'siq_count'));
$totalComments   = array_sum(array_column($publishedArticles, 'comment_count'));

/* ── Helpers ── */
function hx($v): string { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function pdfU($p, $sr = 'https://communeglobal.com'): string {
    $p = trim((string)$p);
    if (!$p || $p === '0') return '';
    if (str_starts_with($p, 'http')) return $p;
    return $sr . (str_contains(ltrim($p, '/'), 'uploads/') ? '/author/' : '/') . ltrim($p, '/');
}
function articleUrl($row, $siteUrl): string {
    $slug = $row['article_slug'] ?? '';
    $jSlug = $row['journal_slug'] ?? 'journal';
    if ($slug) return $siteUrl . '/journals/' . $jSlug . '/article/' . urlencode($slug);
    return $siteUrl . '/journals/article.php?id=' . (int)$row['submission_id'];
}
function volLabel($row): string {
    if (!($row['vol_num'] ?? '')) return '';
    return 'Vol.' . $row['vol_num'] . ', Issue ' . $row['vol_iss'] . ($row['vol_year'] ? ' (' . $row['vol_year'] . ')' : '');
}
function siqBadge($count, $avg): string {
    if (!$count) return '<span class="siq-zero">No ratings yet</span>';
    $score = $count >= 2 ? number_format((float)$avg, 1) : '—';
    return '<span class="siq-badge-inline"><svg viewBox="0 0 44 50" width="22" height="25"><path d="M22 1.5L41 9V27C41 38.5 22 48.5 22 48.5S3 38.5 3 27V9Z" fill="#2196a0"/><text x="50%" y="43%" text-anchor="middle" fill="#fff" font-size="9.5" font-weight="700" font-family="Georgia,serif" dy=".1em">SIQ</text><text x="50%" y="70%" text-anchor="middle" fill="rgba(255,255,255,.9)" font-size="8.5" font-family="Georgia,serif" dy=".1em">' . hx($score) . '</text></svg><span class="siq-badge-text"><strong>' . (int)$count . '</strong> rating' . ($count > 1 ? 's' : '') . ($count >= 2 ? ' &bull; avg ' . number_format((float)$avg, 1) : '') . '</span></span>';
}

$siteUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
$initials = strtoupper(substr($authorFirst, 0, 1) . substr($authorLast, 0, 1)) ?: strtoupper(substr($displayName, 0, 2));

include __DIR__ . '/../include/header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<style>
*,*::before,*::after{box-sizing:border-box}
:root{
  --ink:#0d1b2a;--ink2:#1e3a5f;--blue:#1a56db;--teal:#2196a0;
  --green:#0a6640;--red:#dc2626;--orange:#e07b3a;
  --muted:#64748b;--border:#e2e8f0;--bg:#f8fafc;--w:#fff;
  --serif:'Georgia',serif;--sans:system-ui,-apple-system,sans-serif;
}
body{background:var(--bg);font-family:var(--sans);color:var(--ink)}
.wrap{max-width:1100px;margin:0 auto;padding:0 20px}

/* ── Hero ── */
.ap-hero{background:linear-gradient(150deg,#0b1c35,#1a3a6b 60%,#152e5e);padding:40px 0 0;position:relative;overflow:hidden}
.ap-hero::after{content:'';position:absolute;inset:0;background:url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.025'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");pointer-events:none}
.profile-hero-inner{position:relative;z-index:1;display:flex;align-items:flex-end;gap:24px;padding-bottom:0}
.profile-avatar-wrap{position:relative;flex-shrink:0}
.profile-avatar{width:108px;height:108px;border-radius:50%;background:var(--ink2);border:4px solid rgba(255,255,255,.2);display:flex;align-items:center;justify-content:center;font-size:32px;font-weight:700;color:#fff;font-family:var(--serif);overflow:hidden;flex-shrink:0}
.profile-avatar img{width:100%;height:100%;object-fit:cover}
.profile-badge{position:absolute;bottom:4px;right:4px;background:var(--teal);color:#fff;border-radius:50%;width:26px;height:26px;display:flex;align-items:center;justify-content:center;font-size:11px;border:2px solid #fff}
.profile-hero-text{flex:1;padding-bottom:20px}
.profile-name{font-family:var(--serif);font-size:clamp(20px,3vw,30px);font-weight:700;color:#fff;margin:0 0 5px;line-height:1.2}
.profile-role-tags{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:10px}
.role-tag{display:inline-flex;align-items:center;gap:5px;padding:3px 12px;border-radius:14px;font-size:11.5px;font-weight:700;letter-spacing:.5px}
.rt-author{background:rgba(33,150,160,.25);color:#7de8f0;border:1px solid rgba(33,150,160,.4)}
.rt-reviewer{background:rgba(224,123,58,.2);color:#ffc49a;border:1px solid rgba(224,123,58,.35)}
.profile-inst{font-size:13px;color:rgba(255,255,255,.65);display:flex;align-items:center;gap:5px}
.profile-tabs-nav{display:flex;gap:0;margin-top:18px;border-bottom:none;position:relative;z-index:2}
.tab-btn{padding:11px 22px;font-size:13.5px;font-weight:700;color:rgba(255,255,255,.5);border:none;background:none;cursor:pointer;font-family:inherit;border-bottom:3px solid transparent;transition:all .15s;display:flex;align-items:center;gap:7px}
.tab-btn.active{color:#fff;border-bottom-color:var(--teal)}
.tab-btn:hover:not(.active){color:rgba(255,255,255,.8)}
.tab-count{background:rgba(255,255,255,.15);color:rgba(255,255,255,.8);border-radius:10px;padding:1px 8px;font-size:11px;font-weight:700}
.tab-btn.active .tab-count{background:var(--teal);color:#fff}

/* ── Stats row ── */
.stats-bar{background:var(--w);border-bottom:1px solid var(--border);padding:0}
.stats-inner{display:flex;flex-wrap:wrap;gap:0}
.stat-item{flex:1;min-width:120px;text-align:center;padding:16px 14px;border-right:1px solid var(--border)}
.stat-item:last-child{border-right:none}
.stat-n{font-family:var(--serif);font-size:26px;font-weight:700;color:var(--ink2)}
.stat-l{font-size:11px;color:var(--muted);margin-top:2px;font-weight:600;text-transform:uppercase;letter-spacing:.5px}

/* ── Body ── */
.ap-body{padding:28px 0 60px}
.tab-panel{display:none}.tab-panel.active{display:block}
.section-title{font-family:var(--serif);font-size:18px;font-weight:700;color:var(--ink2);margin-bottom:16px;display:flex;align-items:center;gap:8px}
.section-title i{color:var(--teal);font-size:15px}

/* ── Article card ── */
.art-card{background:var(--w);border:1px solid var(--border);border-radius:10px;padding:18px 20px;margin-bottom:12px;transition:border-color .15s,box-shadow .15s;position:relative}
.art-card:hover{border-color:#b6d4f0;box-shadow:0 2px 12px rgba(26,86,219,.06)}
.art-card-top{display:flex;align-items:flex-start;gap:14px}
.art-card-num{width:34px;height:34px;border-radius:8px;background:var(--bg);border:1.5px solid var(--border);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:var(--ink2);flex-shrink:0;margin-top:2px}
.art-card-body{flex:1;min-width:0}
.art-card-title{font-size:14.5px;font-weight:700;color:var(--ink);line-height:1.4;margin-bottom:7px;text-decoration:none;display:block}
.art-card-title:hover{color:var(--blue)}
.art-card-meta{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:10px}
.art-meta-chip{display:inline-flex;align-items:center;gap:4px;font-size:11.5px;font-weight:600;padding:3px 9px;border-radius:5px}
.amc-journal{background:#eff6ff;color:#1a56db}
.amc-vol{background:#f0f9ff;color:#0369a1}
.amc-date{background:#f1f5f9;color:#374151}
.amc-doi{background:#f5f3ff;color:#6d28d9}
.amc-corr{background:#fef3e8;color:#c2560c}
.amc-reviewer{background:#fffbf0;color:#92400e;border:1px solid #fde68a}
.art-card-footer{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding-top:10px;border-top:1px solid var(--bg)}
.art-card-abstract{font-size:12.5px;color:var(--muted);line-height:1.65;margin-bottom:9px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}

/* ── SIQ inline badge ── */
.siq-badge-inline{display:inline-flex;align-items:center;gap:6px}
.siq-badge-inline svg{flex-shrink:0}
.siq-badge-text{font-size:12px;color:var(--teal);font-weight:600}
.siq-badge-text strong{color:var(--ink2)}
.siq-zero{font-size:12px;color:var(--muted);font-style:italic}

/* ── Action links ── */
.art-action{display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:600;color:var(--blue);text-decoration:none;padding:4px 10px;background:#eff6ff;border-radius:5px;transition:all .15s}
.art-action:hover{background:#dbeafe;color:#1648c2}
.art-action.red{color:var(--red);background:#fee2e2}.art-action.red:hover{background:#fca5a5}

/* ── Bio / about section ── */
.about-card{background:var(--w);border:1px solid var(--border);border-radius:10px;padding:22px 24px;margin-bottom:16px}
.about-row{display:flex;gap:12px;align-items:flex-start;margin-bottom:12px;font-size:13.5px;color:var(--ink)}
.about-row i{color:var(--teal);width:18px;margin-top:2px;flex-shrink:0}
.about-row a{color:var(--blue);text-decoration:none}.about-row a:hover{text-decoration:underline}
.empty-state{text-align:center;padding:48px 20px;color:var(--muted)}
.empty-state i{font-size:40px;display:block;margin-bottom:12px;color:#cbd5e1}
.empty-state p{font-size:14px}

@media(max-width:700px){
  .profile-hero-inner{flex-direction:column;align-items:flex-start}
  .profile-avatar{width:80px;height:80px;font-size:24px}
  .stats-inner{gap:0}
  .stat-item{min-width:50%}
}
</style>

<!-- ── HERO ── -->
<div class="ap-hero">
  <div class="wrap">
    <div class="profile-hero-inner">
      <div class="profile-avatar-wrap">
        <div class="profile-avatar">
          <?php if ($profilePic && file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$profilePic)): ?>
            <img src="<?=hx(pdfU($profilePic))?>" alt="<?=hx($displayName)?>">
          <?php else: ?>
            <?=hx($initials)?>
          <?php endif; ?>
        </div>
        <div class="profile-badge" title="Verified member"><i class="fas fa-check"></i></div>
      </div>
      <div class="profile-hero-text">
        <h1 class="profile-name"><?=hx($displayName)?></h1>
        <div class="profile-role-tags">
          <?php if ($totalPublished > 0): ?>
          <span class="role-tag rt-author"><i class="fas fa-pen-nib"></i> Author</span>
          <?php endif; ?>
          <?php if ($totalReviewed > 0): ?>
          <span class="role-tag rt-reviewer"><i class="fas fa-search"></i> Reviewer</span>
          <?php endif; ?>
          <?php if (!$totalPublished && !$totalReviewed): ?>
          <span class="role-tag rt-author"><i class="fas fa-user"></i> Member</span>
          <?php endif; ?>
        </div>
        <?php if ($institution): ?>
        <div class="profile-inst"><i class="fas fa-university" style="color:rgba(255,255,255,.5)"></i> <?=hx($institution)?></div>
        <?php endif; ?>
        <?php if ($orcid): ?>
        <div class="profile-inst" style="margin-top:4px"><i class="fab fa-orcid" style="color:#a6ce39"></i>
          <a href="https://orcid.org/<?=hx($orcid)?>" target="_blank" style="color:rgba(255,255,255,.75);text-decoration:none"><?=hx($orcid)?></a>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Tabs nav -->
    <div class="profile-tabs-nav">
      <button class="tab-btn active" onclick="switchTab('published',this)">
        <i class="fas fa-newspaper"></i> Published Articles
        <span class="tab-count"><?=(int)$totalPublished?></span>
      </button>
      <button class="tab-btn" onclick="switchTab('reviewed',this)">
        <i class="fas fa-search"></i> Reviewed Articles
        <span class="tab-count"><?=(int)$totalReviewed?></span>
      </button>
      <button class="tab-btn" onclick="switchTab('about',this)">
        <i class="fas fa-user"></i> About
      </button>
    </div>
  </div>
</div>

<!-- ── STATS BAR ── -->
<div class="stats-bar">
  <div class="wrap">
    <div class="stats-inner">
      <div class="stat-item">
        <div class="stat-n"><?=(int)$totalPublished?></div>
        <div class="stat-l">Publications</div>
      </div>
      <div class="stat-item">
        <div class="stat-n"><?=(int)$totalReviewed?></div>
        <div class="stat-l">Reviews</div>
      </div>
      <div class="stat-item">
        <div class="stat-n" style="color:var(--teal)"><?=(int)$totalSiqRatings?></div>
        <div class="stat-l">SIQ Ratings Received</div>
      </div>
      <div class="stat-item">
        <div class="stat-n"><?=(int)$totalComments?></div>
        <div class="stat-l">Comments on Articles</div>
      </div>
    </div>
  </div>
</div>

<!-- ── BODY ── -->
<div class="ap-body">
  <div class="wrap">

    <!-- ═══ TAB: PUBLISHED ═══ -->
    <div class="tab-panel active" id="tab-published">
      <div class="section-title"><i class="fas fa-newspaper"></i> Published Articles (<?=(int)$totalPublished?>)</div>

      <?php if (empty($publishedArticles)): ?>
      <div class="empty-state">
        <i class="fas fa-file-alt"></i>
        <p>No published articles found for this author.</p>
      </div>
      <?php else: ?>
      <?php foreach ($publishedArticles as $i => $art): ?>
      <?php
        $aUrl    = articleUrl($art, $siteUrl);
        $pdfLink = pdfU($art['published_pdf_path'] ?? '');
        $vl      = volLabel($art);
        $siqHtml = siqBadge((int)$art['siq_count'], (float)($art['siq_avg'] ?? 0));
      ?>
      <div class="art-card">
        <div class="art-card-top">
          <div class="art-card-num"><?=$i+1?></div>
          <div class="art-card-body">
            <a href="<?=hx($aUrl)?>" class="art-card-title" target="_blank"><?=hx($art['article_title'] ?? 'Untitled')?></a>
            <div class="art-card-meta">
              <?php if ($art['journal_name']??''): ?><span class="art-meta-chip amc-journal"><i class="fas fa-graduation-cap"></i> <?=hx($art['journal_name'])?></span><?php endif; ?>
              <?php if ($vl): ?><span class="art-meta-chip amc-vol"><i class="fas fa-book-open"></i> <?=hx($vl)?></span><?php endif; ?>
              <?php if ($art['publication_date']??''): ?><span class="art-meta-chip amc-date"><i class="fas fa-calendar-check"></i> <?=hx(date('d M Y', strtotime($art['publication_date'])))?></span><?php endif; ?>
              <?php if ($art['doi']??''): ?><span class="art-meta-chip amc-doi"><i class="fas fa-fingerprint"></i> <?=hx($art['doi'])?></span><?php endif; ?>
              <?php if ($art['is_corresponding']??false): ?><span class="art-meta-chip amc-corr"><i class="fas fa-envelope"></i> Corresponding Author</span><?php endif; ?>
            </div>
            <?php if ($art['abstract']??''): ?><div class="art-card-abstract"><?=hx(mb_strimwidth(strip_tags($art['abstract']),0,220,'…'))?></div><?php endif; ?>
            <div class="art-card-footer">
              <!-- SIQ COUNT + SCORE -->
              <?=$siqHtml?>
              <?php if ((int)$art['comment_count'] > 0): ?>
              <span style="font-size:12px;color:var(--muted)"><i class="fas fa-comments" style="color:#94a3b8"></i> <?=(int)$art['comment_count']?> comment<?=$art['comment_count']>1?'s':''?></span>
              <?php endif; ?>
              <a href="<?=hx($aUrl)?>" class="art-action" target="_blank"><i class="fas fa-external-link-alt"></i> View</a>
              <?php if ($pdfLink): ?><a href="<?=hx($pdfLink)?>" class="art-action red" target="_blank"><i class="fas fa-file-pdf"></i> PDF</a><?php endif; ?>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <!-- ═══ TAB: REVIEWED ═══ -->
    <div class="tab-panel" id="tab-reviewed">
      <div class="section-title"><i class="fas fa-search"></i> Reviewed Articles (<?=(int)$totalReviewed?>)</div>

      <?php if (empty($reviewedArticles)): ?>
      <div class="empty-state">
        <i class="fas fa-search"></i>
        <p>No reviewed articles found for this user.<br><small style="color:#b0bec5">Reviewer data may be stored under a different table structure.</small></p>
      </div>
      <?php else: ?>
      <?php foreach (array_values($reviewedArticles) as $i => $art): ?>
      <?php
        $aUrl    = articleUrl($art, $siteUrl);
        $vl      = volLabel($art);
        $siqHtml = siqBadge((int)$art['siq_count'], (float)($art['siq_avg'] ?? 0));
        $reviewedAt = $art['reviewed_at'] ?? '';
        $decision   = $art['decision'] ?? '';
      ?>
      <div class="art-card">
        <div class="art-card-top">
          <div class="art-card-num"><?=$i+1?></div>
          <div class="art-card-body">
            <a href="<?=hx($aUrl)?>" class="art-card-title" target="_blank"><?=hx($art['article_title'] ?? 'Untitled')?></a>
            <div class="art-card-meta">
              <?php if ($art['journal_name']??''): ?><span class="art-meta-chip amc-journal"><i class="fas fa-graduation-cap"></i> <?=hx($art['journal_name'])?></span><?php endif; ?>
              <?php if ($vl): ?><span class="art-meta-chip amc-vol"><i class="fas fa-book-open"></i> <?=hx($vl)?></span><?php endif; ?>
              <?php if ($art['publication_date']??''): ?><span class="art-meta-chip amc-date"><i class="fas fa-calendar-check"></i> Published <?=hx(date('d M Y', strtotime($art['publication_date'])))?></span><?php endif; ?>
              <?php if ($reviewedAt): ?><span class="art-meta-chip amc-reviewer"><i class="fas fa-clock"></i> Reviewed <?=hx(date('d M Y', strtotime($reviewedAt)))?></span><?php endif; ?>
              <?php if ($decision): ?><span class="art-meta-chip" style="background:#f0fdf4;color:#166534"><i class="fas fa-check-circle"></i> <?=hx(ucfirst($decision))?></span><?php endif; ?>
            </div>
            <div class="art-card-footer">
              <?=$siqHtml?>
              <a href="<?=hx($aUrl)?>" class="art-action" target="_blank"><i class="fas fa-external-link-alt"></i> View Article</a>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <!-- ═══ TAB: ABOUT ═══ -->
    <div class="tab-panel" id="tab-about">
      <div class="section-title"><i class="fas fa-user"></i> About</div>
      <div class="about-card">
        <?php if ($displayName): ?>
        <div class="about-row"><i class="fas fa-user"></i><div><?=hx($displayName)?></div></div>
        <?php endif; ?>
        <?php if ($institution): ?>
        <div class="about-row"><i class="fas fa-university"></i><div><?=hx($institution)?></div></div>
        <?php endif; ?>
        <?php if ($profileEmail): ?>
        <div class="about-row"><i class="fas fa-envelope"></i><div><a href="mailto:<?=hx($profileEmail)?>"><?=hx($profileEmail)?></a></div></div>
        <?php endif; ?>
        <?php if ($orcid): ?>
        <div class="about-row"><i class="fab fa-orcid" style="color:#a6ce39"></i><div><a href="https://orcid.org/<?=hx($orcid)?>" target="_blank"><?=hx($orcid)?></a></div></div>
        <?php endif; ?>
        <?php if ($bio): ?>
        <div class="about-row" style="margin-top:14px;flex-direction:column;gap:6px">
          <div style="font-size:12px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.7px">Bio</div>
          <div style="font-size:13.5px;line-height:1.75;color:var(--ink)"><?=nl2br(hx($bio))?></div>
        </div>
        <?php elseif (!$displayName && !$institution && !$profileEmail): ?>
        <div class="empty-state"><i class="fas fa-user-slash"></i><p>No profile information available.</p></div>
        <?php endif; ?>

        <!-- Summary of contributions -->
        <div style="margin-top:20px;padding-top:16px;border-top:1px solid var(--border)">
          <div style="font-size:12px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.7px;margin-bottom:12px">Contributions Summary</div>
          <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px">
            <div style="background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:12px;text-align:center">
              <div style="font-size:22px;font-weight:700;color:var(--ink2);font-family:var(--serif)"><?=(int)$totalPublished?></div>
              <div style="font-size:11px;color:var(--muted);margin-top:2px">Published Articles</div>
            </div>
            <div style="background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:12px;text-align:center">
              <div style="font-size:22px;font-weight:700;color:var(--orange);font-family:var(--serif)"><?=(int)$totalReviewed?></div>
              <div style="font-size:11px;color:var(--muted);margin-top:2px">Articles Reviewed</div>
            </div>
            <div style="background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:12px;text-align:center">
              <div style="font-size:22px;font-weight:700;color:var(--teal);font-family:var(--serif)"><?=(int)$totalSiqRatings?></div>
              <div style="font-size:11px;color:var(--muted);margin-top:2px">SIQ Ratings Received</div>
            </div>
            <div style="background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:12px;text-align:center">
              <div style="font-size:22px;font-weight:700;color:var(--green);font-family:var(--serif)"><?=(int)$totalComments?></div>
              <div style="font-size:11px;color:var(--muted);margin-top:2px">Article Comments</div>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div><!-- /.wrap -->
</div><!-- /.ap-body -->

<script>
function switchTab(name, btn) {
  document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.getElementById('tab-' + name).classList.add('active');
  btn.classList.add('active');
}
</script>

<?php include __DIR__ . '/../include/footer.php'; ?>