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

$sid = (int)($_GET['id'] ?? 0);
$requestSlug = trim($_GET['slug'] ?? '');
$journalSlug = trim($_GET['journal'] ?? '');
if (!$journalSlug) { $uri=$_SERVER['REQUEST_URI']??''; if(preg_match('#/journals/([a-z0-9-]+)/article#',$uri,$m)) $journalSlug=$m[1]; }

if ($pdo) {
    if (!$sid && $requestSlug !== '') {
        try {
            $st = $pdo->prepare("SELECT submission_id FROM submission_files WHERE article_slug=? AND file_type IN('payment_receipt','final_manuscript_revised','declaration_form') AND publication_date IS NOT NULL LIMIT 1");
            $st->execute([$requestSlug]);
            $row = $st->fetch(PDO::FETCH_ASSOC);
            if ($row) $sid = (int)$row['submission_id'];
        } catch(PDOException $e) {}
    }
    if ($sid && $requestSlug === '') {
        try {
            $st2 = $pdo->prepare("SELECT sf.article_slug, j.slug AS jslug FROM submission_files sf JOIN submissions s ON s.submission_id=sf.submission_id JOIN journals j ON j.journal_id=s.journal_id WHERE sf.submission_id=? AND sf.file_type IN('payment_receipt','final_manuscript_revised','declaration_form') AND sf.publication_date IS NOT NULL AND sf.article_slug IS NOT NULL AND sf.article_slug!='' ORDER BY sf.uploaded_at DESC LIMIT 1");
            $st2->execute([$sid]);
            $sd2 = $st2->fetch(PDO::FETCH_ASSOC);
            if ($sd2 && $sd2['article_slug']) {
                $useJSlug = $journalSlug ?: $sd2['jslug'];
                header('HTTP/1.1 301 Moved Permanently');
                header('Location: '.(isset($_SERVER['HTTPS'])?'https':'http').'://'.$_SERVER['HTTP_HOST'].'/journals/'.rawurlencode($useJSlug).'/article/'.rawurlencode($sd2['article_slug']));
                exit;
            }
        } catch(PDOException $e) {}
    }
}

$article=null; $journal=null; $volume=null; $authors=[]; $keywords=[]; $related=[];
$allVolumes=[]; $refText=''; $submittedDate=''; $acceptedDate='';

if ($sid && $pdo) {
    try {
        $stmt=$pdo->prepare("
            SELECT s.submission_id,s.tracking_code,s.journal_id,
                   mi.article_title,mi.abstract,mi.running_title,
                   pf.doi,pf.page_no,pf.reference,pf.published_pdf_path,
                   pf.publication_date,pf.volume_id,
                   jv.volume AS vol_num,jv.issue AS vol_iss,
                   jv.title AS vol_title,jv.year AS vol_year,
                   j.name AS journal_name,j.slug AS journal_slug
            FROM submissions s
            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 s.submission_id=?
            ORDER BY pf.uploaded_at DESC LIMIT 1
        ");
        $stmt->execute([$sid]); $article=$stmt->fetch(PDO::FETCH_ASSOC);

        if ($article) {
            $s2=$pdo->prepare("SELECT sa.*,af.name AS aff_name,af.department,af.city,af.country FROM submission_authors sa LEFT JOIN affiliations af ON af.affiliation_id=sa.affiliation_id WHERE sa.submission_id=? ORDER BY sa.author_order");
            $s2->execute([$sid]); $authors=$s2->fetchAll(PDO::FETCH_ASSOC);

            $s3=$pdo->prepare("SELECT k.keyword FROM submission_keywords sk JOIN keywords k ON k.keyword_id=sk.keyword_id WHERE sk.submission_id=? ORDER BY sk.display_order");
            $s3->execute([$sid]); $keywords=array_column($s3->fetchAll(PDO::FETCH_ASSOC),'keyword');

            if ($article['journal_id']) {
                $s4=$pdo->prepare("SELECT * FROM journals WHERE journal_id=? LIMIT 1");
                $s4->execute([$article['journal_id']]); $journal=$s4->fetch(PDO::FETCH_ASSOC);
            }
            if ($article['volume_id']) {
                $s5=$pdo->prepare("SELECT * FROM journal_volumes WHERE id=? LIMIT 1");
                $s5->execute([$article['volume_id']]); $volume=$s5->fetch(PDO::FETCH_ASSOC);
            }
            if ($article['volume_id']) {
                $s6=$pdo->prepare("SELECT s.submission_id,mi.article_title,pf.page_no FROM submission_files pf JOIN submissions s ON s.submission_id=pf.submission_id LEFT JOIN manuscript_info mi ON mi.submission_id=s.submission_id WHERE pf.volume_id=? AND pf.file_type IN('payment_receipt','final_manuscript_revised','declaration_form') AND pf.publication_date IS NOT NULL AND s.submission_id!=? GROUP BY s.submission_id ORDER BY CAST(SUBSTRING_INDEX(COALESCE(pf.page_no,'0'),'-',1) AS UNSIGNED) LIMIT 6");
                $s6->execute([$article['volume_id'],$sid]); $related=$s6->fetchAll(PDO::FETCH_ASSOC);
            }
            if ($journal) {
                $s7=$pdo->prepare("SELECT * FROM journal_volumes WHERE journal_id=? AND is_active=1 ORDER BY year DESC,volume DESC,issue DESC");
                $s7->execute([$journal['journal_id']]); $allVolumes=$s7->fetchAll(PDO::FETCH_ASSOC);
            }
            $s8=$pdo->prepare("SELECT MIN(created_at) AS first_decision FROM editorial_decisions WHERE submission_id=?");
            $s8->execute([$sid]); $ed=$s8->fetch(PDO::FETCH_ASSOC);
            $acceptedDate = $ed['first_decision'] ? date('Y-m-d', strtotime($ed['first_decision'])) : '';

            $s9=$pdo->prepare("SELECT submitted_at,created_at FROM submissions WHERE submission_id=? LIMIT 1");
            $s9->execute([$sid]); $sub=$s9->fetch(PDO::FETCH_ASSOC);
            $submittedDate = $sub ? date('Y-m-d', strtotime($sub['submitted_at'] ?: $sub['created_at'])) : '';
        }
    } catch(PDOException $e) {}
}

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(strpos($p,'http')===0) return $p;
    return $sr.(strpos(ltrim($p,'/'),'uploads/')===0?'/author/':'/').(ltrim($p,'/'));
}

if (!$journalSlug && !empty($article['journal_slug'])) $journalSlug=$article['journal_slug'];
$siteUrl    = (isset($_SERVER['HTTPS'])?'https':'http').'://'.$_SERVER['HTTP_HOST'];
$jName      = $article['journal_name'] ?? ($journal['name'] ?? 'CIJSS');
$jSlug      = $journalSlug ?? ($article['journal_slug'] ?? 'social-science');
$title      = $article['article_title'] ?? 'Article';
$abstract   = $article['abstract'] ?? '';
$doi        = $article['doi'] ?? '';
$pageNo     = $article['page_no'] ?? '';
$pubDate    = $article['publication_date'] ?? '';
$pdfUrl     = pdfU($article['published_pdf_path'] ?? '');
$volLabel   = $volume ? 'Volume '.$volume['vol_num'].', Issue '.$volume['vol_iss'].($volume['vol_year']?' ('.$volume['vol_year'].')':'') : '';
$issueUrl   = $volume ? $siteUrl.'/journals/'.$jSlug.'/issue.php?id='.(int)$volume['id'] : '';
$articleUrl = $siteUrl.'/journals/'.$jSlug.'/article.php?id='.$sid;
$xmlUrl     = $siteUrl.'/journals/article_jats_xml.php?id='.$sid;
$authorStr  = implode(', ', array_map(fn($a)=>trim(($a['title']?$a['title'].' ':'').$a['first_name'].' '.($a['middle_name']?$a['middle_name'].' ':'').$a['last_name']), $authors));

$fpPage = $lpPage = '';
if ($pageNo) {
    if (str_contains($pageNo,'-')) { [$fpPage,$lpPage] = explode('-',$pageNo,2); }
    else { $fpPage = $pageNo; }
}

function buildCite($article,$authors,$format,$jName){
    $al=implode(', ',array_map(fn($a)=>trim(($a['title']?$a['title'].' ':'').$a['first_name'].' '.($a['middle_name']?$a['middle_name'].' ':'').$a['last_name']),$authors));
    $yr=$article['publication_date']?date('Y',strtotime($article['publication_date'])):date('Y');
    $t=$article['article_title']??''; $doi=$article['doi']??''; $v=$article['vol_num']??''; $i=$article['vol_iss']??''; $p=$article['page_no']??'';
    if($format==='apa')     return "{$al} ({$yr}). {$t}. {$jName}".($v?", {$v}":"").($i?"({$i})":"").($p?", pp.{$p}":"").($doi?". https://doi.org/{$doi}":".");
    if($format==='mla')     return "{$al}. \"{$t}.\" {$jName}".($v?", vol. {$v}":"").($i?", no. {$i}":"").($yr?", {$yr}":"").($doi?", doi:{$doi}":".").".";
    if($format==='harvard') return "{$al}, {$yr}. {$t}. {$jName}".($v?", {$v}":"").($i?"({$i})":"").($p?", pp.{$p}":"").($doi?". doi: {$doi}":".");
    return '';
}
$cApa    = hx(buildCite($article,$authors,'apa',$jName));
$cMla    = hx(buildCite($article,$authors,'mla',$jName));
$cHarvard= hx(buildCite($article,$authors,'harvard',$jName));

$kwString       = implode(', ', $keywords);
$citPubDate     = $pubDate ? date('Y/m/d', strtotime($pubDate)) : date('Y');
$htmlTitle      = hx($title.' | '.$jName);
$finalTitle     = $title.' | '.$jName;
$finalDesc      = $abstract ? mb_strimwidth(strip_tags($abstract),0,160,'…') : $finalTitle;
$finalKeywords  = $kwString;
$finalCanonical = $articleUrl;
$finalFeatureImg= $siteUrl.'/asset/og-default.jpg';
$finalImgAlt    = $title;
$siteName       = 'Communeglobal';
$ogType='article'; $ogTitle=$finalTitle;
$ogDesc=$abstract?mb_strimwidth(strip_tags($abstract),0,200,'…'):$finalTitle;
$ogImage=$finalFeatureImg; $twCard='summary_large_image';
$twTitle=$finalTitle; $twDesc=$ogDesc; $twImage=$finalFeatureImg; $twSite='@communeglobal';
$pageData=['title'=>$title,'created_at'=>($pubDate?:date('Y-m-d H:i:s')),'updated_at'=>($pubDate?:date('Y-m-d H:i:s'))];
$aiSummary=$abstract?mb_strimwidth(strip_tags($abstract),0,300,'…'):'';
$schemaAuthors=[];
foreach($authors as $a){
    $an=['@type'=>'Person','name'=>trim(($a['title']?$a['title'].' ':'').$a['first_name'].' '.$a['last_name'])];
    if(!empty($a['aff_name'])) $an['affiliation']=['@type'=>'Organization','name'=>$a['aff_name']];
    $schemaAuthors[]=$an;
}
$schemaObj=['@context'=>'https://schema.org','@type'=>'ScholarlyArticle','headline'=>$title,'datePublished'=>$pubDate?:date('Y-m-d'),'author'=>$schemaAuthors,'abstract'=>mb_strimwidth($abstract,0,500,'…'),'keywords'=>$kwString,'url'=>$articleUrl,'publisher'=>['@type'=>'Organization','name'=>'Commune Global'],'isPartOf'=>['@type'=>'Periodical','name'=>$jName],'inLanguage'=>'en-US'];
if($doi){$schemaObj['identifier']=$doi;$schemaObj['sameAs']='https://doi.org/'.$doi;}
if($fpPage) $schemaObj['pageStart']=trim($fpPage);
if($lpPage) $schemaObj['pageEnd']=trim($lpPage);
$schemaRaw=json_encode($schemaObj,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
$faqSchema='';

$refsHtml=''; $refText=$article['reference']??'';
if($refText){
    $lines=array_filter(explode("\n",trim($refText)),fn($l)=>trim($l)!=='');
    foreach($lines as $i=>$ref){
        $clean=trim(preg_replace('/^\d+\.\s*/','',trim($ref)));
        $gs='https://scholar.google.com/scholar?q='.urlencode($clean);
        $cr='https://search.crossref.org/?q='.urlencode($clean);
        if(preg_match('/10\.\d{4,9}\/[\w\d\.\-\/]+/i',$ref,$m2)) $cr='https://doi.org/'.$m2[0];
        $refsHtml.='<p style="margin-bottom:7px;font-size:13px;color:#334155;line-height:1.6">'.($i+1).'. '.hx($clean).' <a href="'.hx($gs).'" target="_blank" rel="noopener" style="color:#1a56db;text-decoration:none;font-weight:500">[Google Scholar]</a> <a href="'.hx($cr).'" target="_blank" rel="noopener" style="color:#1a56db;text-decoration:none;font-weight:500">[Crossref]</a></p>';
    }
}

/* ══════════════════════════════════════════════════════════
   $userHasRated — TWO-LAYER CHECK
   Layer 1: PHP session (set immediately after rating)
   Layer 2: DB IP check (covers new sessions / page refreshes)
   If either is true → show comment form
══════════════════════════════════════════════════════════ */
$userHasRated = false;

// Layer 1: session flag
if (!empty($_SESSION['siq_rated_'.$sid])) {
    $userHasRated = true;
}

// Layer 2: IP already rated this article in DB (within 24h)
if (!$userHasRated && $sid && $pdo) {
    try {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $chk = $pdo->prepare("
            SELECT COUNT(*) FROM article_siq_ratings
            WHERE submission_id = ? AND ip_address = ?
              AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)
        ");
        $chk->execute([$sid, $ip]);
        if ((int)$chk->fetchColumn() > 0) {
            $userHasRated = true;
            // Also set session so next check is instant
            $_SESSION['siq_rated_'.$sid] = true;
        }
    } catch(PDOException $e) {}
}

/* ── ALWAYS load approved comments ── */
$approvedComments = [];
if ($sid && $pdo) {
    try {
        $sc = $pdo->prepare("SELECT comment_id,name,comment,created_at FROM article_comments WHERE submission_id=? AND status=1 ORDER BY created_at DESC");
        $sc->execute([$sid]);
        $approvedComments = $sc->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {}
}

/* ── SIQ score ── */
$siqScore=null; $siqCount=0; $siqRevealed=false;
if($sid&&$pdo){
    try{
        $sq=$pdo->prepare("SELECT COUNT(*) AS cnt, AVG(siq_score) AS mean FROM article_siq_ratings WHERE submission_id=? AND status=1");
        $sq->execute([$sid]); $sqr=$sq->fetch(PDO::FETCH_ASSOC);
        $siqCount=(int)$sqr['cnt']; $siqRevealed=($siqCount>=2);
        $siqScore=$siqRevealed?number_format((float)$sqr['mean'],1):null;
    } catch(PDOException $e){}
}

include __DIR__ . '/../include/header.php';
?>
<meta name="citation_title"            content="<?=hx($title)?>">
<?php foreach($authors as $a): ?>
<meta name="citation_author"           content="<?=hx(trim(($a['title']?$a['title'].' ':'').$a['first_name'].' '.($a['middle_name']?$a['middle_name'].' ':'').$a['last_name']))?>">
<?php endforeach; ?>
<meta name="citation_publication_date" content="<?=hx($citPubDate)?>">
<meta name="citation_journal_title"    content="<?=hx($jName)?>">
<meta name="citation_journal_abbrev"   content="<?=hx($jName)?>">
<?php if($article['vol_num']??''): ?><meta name="citation_volume" content="<?=hx($article['vol_num'])?>"><?php endif; ?>
<?php if($article['vol_iss']??''): ?><meta name="citation_issue"  content="<?=hx($article['vol_iss'])?>"><?php endif; ?>
<?php if($fpPage): ?><meta name="citation_firstpage" content="<?=hx(trim($fpPage))?>"><?php endif; ?>
<?php if($lpPage): ?><meta name="citation_lastpage"  content="<?=hx(trim($lpPage))?>"><?php endif; ?>
<?php if($doi): ?><meta name="citation_doi" content="<?=hx($doi)?>"><?php endif; ?>
<meta name="citation_language"  content="en">
<meta name="citation_publisher" content="Commune Global">
<?php if($pdfUrl): ?><meta name="citation_pdf_url" content="<?=hx($pdfUrl)?>"><?php endif; ?>
<meta name="citation_abstract_html_url" content="<?=hx($articleUrl)?>">
<meta name="citation_fulltext_html_url" content="<?=hx($articleUrl)?>">
<meta name="DC.type"      content="Article">
<meta name="DC.title"     content="<?=hx($title)?>">
<?php foreach($authors as $a): ?>
<meta name="DC.creator"   content="<?=hx(trim(($a['title']?$a['title'].' ':'').$a['first_name'].' '.$a['last_name']))?>">
<?php endforeach; ?>
<meta name="DC.date"      content="<?=hx($citPubDate)?>">
<meta name="DC.publisher" content="Commune Global">
<meta name="DC.format"    content="application/pdf">
<?php if($doi): ?><meta name="DC.identifier" content="<?=hx($doi)?>"><?php endif; ?>
<meta name="DC.language"  content="en">
<meta name="DC.source"    content="<?=hx($jName)?> Vol <?=hx($article['vol_num']??'')?> Issue <?=hx($article['vol_iss']??'')?>">
<meta name="DC.relation"  content="<?=hx($articleUrl)?>">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

<style>
*,*::before,*::after{box-sizing:border-box}
:root{
  --ink:#0d1b2a;--ink2:#1e3a5f;--blue:#1a56db;--blue-l:#eff6ff;
  --accent:#c8410a;--green:#0a6640;--red:#dc2626;
  --muted:#64748b;--border:#e2e8f0;--bg:#f8fafc;--w:#fff;
  --serif:'Georgia',serif;--sans:system-ui,-apple-system,sans-serif;
  --teal:#2196a0;
}
.ap{background:var(--bg);font-family:var(--sans);color:var(--ink)}
.wrap{max-width:1160px;margin:0 auto;padding:0 20px}
.ap-strip{background:var(--ink2);padding:9px 0;font-size:12px;color:rgba(255,255,255,.7)}
.ap-bc{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
.ap-bc a{color:rgba(255,255,255,.8);text-decoration:none}.ap-bc a:hover{color:#fff;text-decoration:underline}
.ap-bc i{font-size:8px;color:rgba(255,255,255,.35)}
.ap-hero{background:linear-gradient(155deg,#0b1c35 0%,#1a3a6b 58%,#152e5e 100%);padding:36px 0 30px;position:relative;overflow:hidden}
.ap-hero::before{content:'';position:absolute;top:-70px;right:-70px;width:360px;height:360px;border-radius:50%;background:rgba(255,255,255,.03)}
.ap-hero-in{position:relative;z-index:1}
.ap-hero-tags{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:13px}
.ap-htag{display:inline-flex;align-items:center;gap:5px;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.17);color:rgba(255,255,255,.9);border-radius:16px;padding:3px 12px;font-size:11.5px;font-weight:600;text-decoration:none;transition:background .15s}
.ap-htag:hover{background:rgba(255,255,255,.18);color:#fff}
.ap-hero h1{font-family:var(--serif);font-size:clamp(17px,2.8vw,28px);font-weight:700;color:#fff;line-height:1.32;margin:0 0 9px}
.ap-hero-auth{font-size:13px;color:rgba(255,255,255,.75);font-style:italic}
.ap-body{padding:24px 0 60px}
.ap-cols{display:grid;grid-template-columns:1fr 270px;gap:22px;align-items:start}
@media(max-width:920px){.ap-cols{grid-template-columns:1fr}}
.sec{background:var(--w);border-radius:10px;border:1px solid var(--border);padding:20px 22px;margin-bottom:13px}
.sec-h{font-size:15px;font-weight:700;color:var(--ink2);margin-bottom:14px;padding-bottom:9px;border-bottom:2px solid var(--blue-l);display:flex;align-items:center;gap:7px}
.sec-h i{color:var(--blue);font-size:13px}
.ap-chips{display:flex;flex-wrap:wrap;gap:7px;margin-bottom:14px}
.ap-chip{display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:600;padding:4px 11px;border-radius:5px}
.c-doi{background:#e8f0fe;color:#1a56c4}.c-doi a{color:inherit;text-decoration:none}.c-doi a:hover{text-decoration:underline}
.c-pg{background:#fef3e8;color:#8a4a0c}.c-date{background:#f1f5f9;color:#374151}
.c-oa{background:#dcfce7;color:var(--green)}.c-vol{background:#f0f9ff;color:#0369a1}
.c-vol a{color:inherit;text-decoration:none}.c-vol a:hover{text-decoration:underline}
.art-meta-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:14px 0}
@media(max-width:640px){.art-meta-grid{grid-template-columns:1fr}}
.art-meta-item{display:flex;align-items:flex-start;gap:10px;background:#f8fafc;border:1px solid var(--border);border-radius:8px;padding:10px 13px;transition:border-color .15s}
.art-meta-item:hover{border-color:#c7d2fe}
.art-meta-icon{width:32px;height:32px;border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:13px;flex-shrink:0}
.art-meta-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin-bottom:3px}
.art-meta-val{font-size:13px;font-weight:600;color:var(--ink);line-height:1.3}
.art-meta-link{color:var(--blue);text-decoration:none;font-size:12.5px;word-break:break-all}
.art-meta-link:hover{text-decoration:underline}
.tl{display:flex;align-items:flex-start;gap:0;margin-top:14px;position:relative}
.tl::before{content:'';position:absolute;top:10px;left:10px;right:10px;height:2px;background:var(--border);z-index:0}
.tl-step{flex:1;display:flex;flex-direction:column;align-items:center;position:relative;z-index:1}
.tl-dot{width:20px;height:20px;border-radius:50%;background:var(--blue);border:3px solid #fff;box-shadow:0 0 0 2px var(--blue);margin-bottom:6px}
.tl-dot.empty{background:var(--border);box-shadow:0 0 0 2px var(--border)}
.tl-done{background:var(--green);box-shadow:0 0 0 2px var(--green)}
.tl-lbl{font-size:11px;font-weight:700;color:var(--muted);text-align:center}
.tl-date{font-size:11px;color:var(--ink);font-weight:500;text-align:center;margin-top:2px}
.auth-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:10px}
.auth-card{display:flex;align-items:flex-start;gap:10px;background:#f8fafc;border:1px solid var(--border);border-radius:8px;padding:10px 12px}
.auth-av{width:36px;height:36px;border-radius:50%;background:var(--ink2);color:#fff;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;flex-shrink:0}
.auth-name{font-size:13px;font-weight:700;color:var(--ink)}
.auth-aff{font-size:11px;color:var(--muted);line-height:1.4;margin-top:2px}
.auth-corr{font-size:10.5px;font-weight:600;color:var(--accent);margin-top:3px;display:flex;align-items:center;gap:3px}
.ap-abstract{font-size:14px;color:#334155;line-height:1.82}
.kw-wrap{display:flex;flex-wrap:wrap;gap:7px}
.kw{background:var(--w);border:1.5px solid var(--border);border-radius:5px;padding:4px 12px;font-size:12.5px;color:var(--ink);font-weight:500;transition:all .15s}
.kw:hover{background:var(--ink);color:#fff;border-color:var(--ink)}
.dl-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:8px;margin-top:4px}
.dl-btn{display:flex;align-items:center;justify-content:center;gap:6px;padding:9px 14px;border-radius:6px;font-size:13px;font-weight:600;text-decoration:none;transition:all .15s}
.dl-pdf{background:var(--red);color:#fff}.dl-pdf:hover{background:#b91c1c;color:#fff}
.dl-xml{background:#7c3aed;color:#fff}.dl-xml:hover{background:#6d28d9;color:#fff}
.ap-actions{display:flex;flex-wrap:wrap;gap:8px;padding:13px 0;border-top:1px solid var(--border);border-bottom:1px solid var(--border);margin-top:4px}
.ap-btn{display:inline-flex;align-items:center;gap:5px;padding:7px 15px;border-radius:6px;font-size:12.5px;font-weight:600;text-decoration:none;border:none;cursor:pointer;transition:all .15s;font-family:inherit}
.b-blue{background:var(--blue);color:#fff}.b-blue:hover{background:#1648c2;color:#fff}
.b-red{background:var(--red);color:#fff}.b-red:hover{background:#b91c1c;color:#fff}
.b-grn{background:#dcfce7;color:var(--green);border:1.5px solid #a7f3d0}.b-grn:hover{background:#bbf7d0}
.b-out{background:var(--bg);color:var(--ink);border:1.5px solid var(--border)}.b-out:hover{background:#e2e8f0}
.cite-box{position:relative;background:#f8fafc;border:1px solid var(--border);border-radius:7px;padding:12px 14px;font-size:12.5px;line-height:1.72;color:var(--ink);margin-top:8px}
.cite-copy{position:absolute;top:8px;right:8px;background:var(--ink2);color:#fff;border:none;border-radius:4px;padding:3px 9px;font-size:10.5px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .15s}
.cite-copy:hover{background:var(--blue)}
select.cite-sel{border:1.5px solid var(--border);border-radius:6px;padding:6px 10px;font-size:13px;font-family:inherit;color:var(--ink);outline:none;background:var(--w);margin-bottom:2px}
.share-btns{display:flex;gap:8px;flex-wrap:wrap}
.sh-btn{width:36px;height:36px;border-radius:7px;display:flex;align-items:center;justify-content:center;font-size:14px;color:#fff;text-decoration:none;transition:opacity .15s}
.sh-btn:hover{opacity:.85}
.sh-fb{background:#1877f2}.sh-tw{background:#1da1f2}.sh-wa{background:#25d366}.sh-em{background:#ea4335}
.metrics-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.metric-box{text-align:center;padding:14px 10px;background:#f8fafc;border-radius:8px;border:1px solid var(--border)}
.metric-n{font-size:24px;font-weight:700;color:var(--blue);font-family:var(--serif)}
.metric-l{font-size:11px;color:var(--muted);margin-top:2px}
.r-card{background:var(--w);border-radius:10px;border:1px solid var(--border);overflow:hidden;margin-bottom:12px}
.r-head{background:var(--ink2);color:#fff;padding:10px 14px;font-size:11.5px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;display:flex;align-items:center;gap:6px}
.r-body{padding:13px 14px}
.iss-card{background:linear-gradient(135deg,var(--ink2),#0d1f3c);border-radius:10px;padding:15px;color:#fff;margin-bottom:12px}
.iss-lbl{font-size:10px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:#93bff5;margin-bottom:5px}
.iss-title{font-family:var(--serif);font-size:14.5px;font-weight:700;margin-bottom:9px;line-height:1.3}
.iss-link{display:inline-flex;align-items:center;gap:5px;background:rgba(255,255,255,.14);color:#fff;text-decoration:none;padding:5px 11px;border-radius:5px;font-size:12px;font-weight:600;transition:background .15s}
.iss-link:hover{background:rgba(255,255,255,.24);color:#fff}
.s-dl{display:flex;align-items:center;gap:7px;padding:8px 11px;border-radius:6px;font-size:12.5px;font-weight:600;text-decoration:none;margin-bottom:6px;transition:all .15s;cursor:pointer;border:none;width:100%;text-align:left;font-family:inherit}
.s-dl:last-child{margin-bottom:0}
.sd-green{background:#dcfce7;color:var(--green)}.sd-green:hover{background:#bbf7d0}
.sd-yellow{background:#fef9c3;color:#854d0e}.sd-yellow:hover{background:#fef08a}
.sd-red{background:#fee2e2;color:var(--red)}.sd-red:hover{background:#fca5a5}
.sd-indigo{background:#e0e7ff;color:#3730a3}.sd-indigo:hover{background:#c7d2fe}
.sd-pdf{background:#fee2e2;color:var(--red)}.sd-pdf:hover{background:#fca5a5}
.sd-xml{background:#ede9fe;color:#7c3aed}.sd-xml:hover{background:#ddd6fe}
.idx-btn{display:flex;align-items:center;gap:7px;padding:7px 12px;border-radius:6px;font-size:12px;font-weight:600;text-decoration:none;margin-bottom:6px;transition:all .15s}
.idx-btn:last-child{margin-bottom:0}
.i-indigo{background:#e0e7ff;color:#3730a3}.i-indigo:hover{background:#c7d2fe}
.i-teal{background:#ccfbf1;color:#0f766e}.i-teal:hover{background:#99f6e4}
.i-purple{background:#ede9fe;color:#6d28d9}.i-purple:hover{background:#ddd6fe}
.i-yellow{background:#fef9c3;color:#854d0e}.i-yellow:hover{background:#fef08a}
.i-green{background:#dcfce7;color:var(--green)}.i-green:hover{background:#bbf7d0}
.rel-item{display:flex;align-items:flex-start;gap:9px;padding:8px 0;border-bottom:1px solid var(--border)}
.rel-item:last-child{border-bottom:none}
.rel-n{width:20px;height:20px;border-radius:50%;background:#f1f5f9;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;color:var(--ink2);flex-shrink:0;margin-top:1px}
.rel-t{font-size:12px;font-weight:600;color:var(--ink);text-decoration:none;line-height:1.35;display:block}
.rel-t:hover{color:var(--blue)}
.vlist{list-style:none;padding:0}
.vlist li a{display:flex;align-items:center;justify-content:space-between;padding:6px 0;font-size:12px;color:var(--ink);text-decoration:none;border-bottom:1px solid #f1f5f9;transition:color .1s}
.vlist li a:hover{color:var(--blue)}.vlist li a.active{color:var(--blue);font-weight:700}
.popup-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:9999;align-items:center;justify-content:center}
.popup-overlay.open{display:flex}
.popup-box{background:#fff;border-radius:12px;padding:26px 28px;max-width:380px;width:92%;box-shadow:0 8px 40px rgba(0,0,0,.22)}
.popup-box h3{font-family:var(--serif);font-size:17px;font-weight:700;color:var(--ink2);margin-bottom:16px}
.pf-label{font-size:12px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.6px;margin-bottom:4px;display:block}
.pf-input{width:100%;border:1.5px solid var(--border);border-radius:6px;padding:8px 11px;font-size:13px;font-family:inherit;color:var(--ink);outline:none;margin-bottom:12px}
.pf-input:focus{border-color:var(--blue)}
.pf-error{font-size:12px;color:var(--red);margin-bottom:10px;display:none}
.pf-btns{display:flex;gap:9px;justify-content:flex-end}
.ap-modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;align-items:center;justify-content:center}
.ap-modal.open{display:flex}
.ap-mbox{background:#fff;border-radius:13px;padding:24px 28px;max-width:540px;width:92%;box-shadow:0 8px 40px rgba(0,0,0,.2)}
.ap-mbox h3{font-family:var(--serif);font-size:15.5px;margin-bottom:11px;color:var(--ink);display:flex;align-items:center;gap:7px}
.ap-mcite{background:#f8fafc;border:1px solid var(--border);border-radius:7px;padding:12px;font-size:12.5px;line-height:1.7;color:var(--ink);user-select:all;margin-bottom:11px}
.ap-mbtns{display:flex;gap:8px;justify-content:flex-end}
.ap-404{text-align:center;padding:60px 20px;background:var(--w);border-radius:10px;border:1px solid var(--border);margin:30px 0}
/* SIQ */
.siq-wrap{display:inline-flex;align-items:center;gap:0;margin:10px 0 6px}
.siq-shield-btn{cursor:pointer;transition:transform .2s;background:none;border:none;padding:0;line-height:0}
.siq-shield-btn:hover{transform:scale(1.07)}
.siq-rate-btn{background:#e07b3a;color:#fff;border:none;border-radius:0 6px 6px 0;padding:0 22px;font-size:13px;font-weight:700;letter-spacing:.8px;cursor:pointer;font-family:inherit;transition:background .15s,transform .1s;display:inline-flex;align-items:center;gap:7px;height:44px}
.siq-rate-btn:hover{background:#c96b2c;transform:translateY(-1px)}
.siq-overlay{display:none;position:fixed;inset:0;background:rgba(8,18,36,.58);z-index:10000;align-items:center;justify-content:center;backdrop-filter:blur(3px)}
.siq-overlay.open{display:flex}
.siq-modal{background:#fff;border-radius:16px;padding:30px 34px 26px;max-width:540px;width:94%;box-shadow:0 20px 70px rgba(0,0,0,.3);animation:siqIn .3s cubic-bezier(.22,1,.36,1);max-height:92vh;overflow-y:auto}
@keyframes siqIn{from{opacity:0;transform:translateY(-24px) scale(.96)}to{opacity:1;transform:none}}
.siq-modal-head{text-align:center;margin-bottom:2px}
.siq-modal-title{font-family:Georgia,serif;font-size:20px;font-weight:700;color:var(--teal);text-align:center;margin:0 0 20px}
.siq-row{margin-bottom:18px}
.siq-row-lbl{font-size:13.5px;font-weight:600;color:#1a2a3a;margin-bottom:7px}
.siq-tick-row{display:flex;justify-content:space-between;margin-bottom:4px}
.siq-tick{font-size:11px;color:#b0bec5;font-weight:500;width:22px;text-align:center;transition:color .12s;line-height:1}
.siq-tick.on{color:var(--teal);font-weight:700}
.siq-range{-webkit-appearance:none;appearance:none;width:100%;height:5px;border-radius:3px;outline:none;cursor:pointer;background:linear-gradient(to right,var(--teal) 0%,#dde9ec 0%)}
.siq-range::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border-radius:50%;background:var(--teal);border:3px solid #fff;box-shadow:0 0 0 2.5px var(--teal);cursor:pointer;transition:transform .12s}
.siq-range::-webkit-slider-thumb:hover{transform:scale(1.2)}
.siq-range::-moz-range-thumb{width:20px;height:20px;border-radius:50%;background:var(--teal);border:3px solid #fff;box-shadow:0 0 0 2.5px var(--teal);cursor:pointer}
.siq-foot{display:flex;justify-content:flex-end;gap:10px;margin-top:24px;padding-top:16px;border-top:1px solid #e4eeef}
.siq-btn{padding:9px 26px;border-radius:7px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit;border:none;transition:all .15s}
.siq-primary{background:var(--teal);color:#fff}.siq-primary:hover{background:#1a7a85}
.siq-ghost{background:#f0f6f7;color:#4a6270;border:1.5px solid #ccdde0}.siq-ghost:hover{background:#ddeaed}
.siq-orange{background:#e07b3a;color:#fff;padding:11px 30px;font-size:14px}.siq-orange:hover{background:#c86c2f}
.icmje-badge{display:inline-flex;align-items:center;gap:7px;background:linear-gradient(135deg,#f5c842,#e4a800);color:#fff;padding:8px 18px;border-radius:7px;font-size:13px;font-weight:700;box-shadow:0 3px 12px rgba(228,168,0,.35);margin-bottom:14px}
.icmje-badge i{font-size:17px}
.siq-score-line{text-align:right;font-size:14px;font-weight:600;color:#546e7a;margin-bottom:12px}
.siq-coi-text{font-size:13px;color:#455a64;line-height:1.72;margin-bottom:14px}
.siq-radio-group{display:flex;gap:24px;margin-bottom:14px}
.siq-radio-lbl{display:flex;align-items:center;gap:7px;font-size:13.5px;font-weight:500;color:#263238;cursor:pointer}
.siq-radio-lbl input{accent-color:var(--teal);width:16px;height:16px}
.siq-textarea{width:100%;min-height:110px;resize:vertical;border:1.5px solid #c8d8dc;border-radius:8px;padding:10px 13px;font-size:13px;font-family:inherit;color:#263238;outline:none;transition:border-color .15s}
.siq-textarea:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(33,150,160,.1)}
.siq-ty-script{font-family:'Brush Script MT',cursive;font-size:52px;color:#1a2a3a;margin:4px 0 16px;line-height:1;text-align:center}
.siq-ty-sub{font-size:14px;color:#546e7a;line-height:1.75;text-align:center;margin:0 0 10px}
/* Comments */
.cm-wrap{max-width:1160px;margin:0 auto;padding:0 20px 60px}
.cm-section{background:#fff;border-radius:10px;border:1px solid #e2e8f0;padding:24px 26px;margin-bottom:18px}
.cm-head{font-size:16px;font-weight:700;color:#1e3a5f;margin-bottom:18px;padding-bottom:10px;border-bottom:2px solid #eff6ff;display:flex;align-items:center;gap:8px}
.cm-head i{color:#1a56db;font-size:14px}
.cm-list{display:flex;flex-direction:column;gap:14px}
.cm-card{background:#f8fafc;border:1px solid #e2e8f0;border-radius:9px;padding:14px 16px;transition:border-color .15s}
.cm-card:hover{border-color:#bfdbfe}
.cm-card-top{display:flex;align-items:center;gap:10px;margin-bottom:8px}
.cm-avatar{width:38px;height:38px;border-radius:50%;background:#1e3a5f;color:#fff;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;flex-shrink:0}
.cm-author-name{font-size:13.5px;font-weight:700;color:#0d1b2a}
.cm-date{font-size:11px;color:#94a3b8;margin-top:2px}
.cm-text{font-size:13.5px;color:#334155;line-height:1.75}
.cm-empty{text-align:center;padding:28px 0;color:#94a3b8;font-size:13px}
.cm-empty i{font-size:30px;display:block;margin-bottom:8px;color:#cbd5e1}
.cmf-group{display:flex;flex-direction:column;gap:5px;margin-bottom:14px}
.cmf-label{font-size:12px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.6px}
.cmf-required{color:#dc2626;margin-left:2px}
.cmf-input{border:1.5px solid #e2e8f0;border-radius:7px;padding:9px 12px;font-size:13.5px;font-family:inherit;color:#0d1b2a;outline:none;transition:border-color .15s;width:100%;background:#fff}
.cmf-input:focus{border-color:#1a56db;box-shadow:0 0 0 3px rgba(26,86,219,.08)}
.cmf-textarea{border:1.5px solid #e2e8f0;border-radius:7px;padding:9px 12px;font-size:13.5px;font-family:inherit;color:#0d1b2a;outline:none;transition:border-color .15s;width:100%;background:#fff;resize:vertical;min-height:110px}
.cmf-textarea:focus{border-color:#1a56db;box-shadow:0 0 0 3px rgba(26,86,219,.08)}
.cmf-submit{display:inline-flex;align-items:center;gap:7px;background:#1a56db;color:#fff;border:none;border-radius:7px;padding:10px 22px;font-size:13.5px;font-weight:700;cursor:pointer;font-family:inherit;transition:background .15s;margin-top:4px}
.cmf-submit:hover{background:#1648c2}
.cmf-submit:disabled{opacity:.6;cursor:not-allowed}
.cmf-msg{display:none;padding:11px 14px;border-radius:7px;font-size:13px;font-weight:600;margin-top:10px}
.cmf-msg.success{background:#dcfce7;color:#0a6640;border:1px solid #a7f3d0}
.cmf-msg.error{background:#fee2e2;color:#dc2626;border:1px solid #fca5a5}
/* Rate-to-comment nudge */
.cm-rate-nudge{display:flex;align-items:center;gap:14px;flex-wrap:wrap;background:#fffbf0;border:1.5px solid #fde68a;border-radius:10px;padding:16px 20px}
.cm-rate-nudge .nudge-icon{font-size:22px;color:#f59e0b;flex-shrink:0}
.cm-rate-nudge-text{flex:1;min-width:0}
.cm-rate-nudge-title{font-size:14px;font-weight:700;color:#92400e;margin-bottom:3px}
.cm-rate-nudge-sub{font-size:12.5px;color:#a16207;line-height:1.5}
.cm-rate-nudge-btn{display:inline-flex;align-items:center;gap:6px;background:#e07b3a;color:#fff;border:none;border-radius:7px;padding:9px 20px;font-size:13px;font-weight:700;cursor:pointer;font-family:inherit;transition:background .15s;white-space:nowrap;flex-shrink:0}
.cm-rate-nudge-btn:hover{background:#c86c2f}
@media(max-width:920px){.ap-right{order:-1}}
@media(max-width:640px){.sec{padding:14px 12px}.ap-hero{padding:22px 0 20px}.tl{flex-direction:column;gap:12px}.tl::before{display:none}.siq-modal{padding:22px 18px 20px}.cm-rate-nudge{flex-direction:column;text-align:center}}
</style>

<div class="ap">
<div class="ap-strip"><div class="wrap"><div class="ap-bc">
  <a href="<?=hx($siteUrl)?>">Home</a><i class="fas fa-chevron-right"></i>
  <a href="<?=hx($siteUrl.'/journals/'.$jSlug.'/')?>">CIJSS</a><i class="fas fa-chevron-right"></i>
  <?php if($issueUrl&&$volLabel):?><a href="<?=hx($issueUrl)?>"><?=hx($volLabel)?></a><i class="fas fa-chevron-right"></i><?php endif;?>
  <span><?=hx(mb_strimwidth($title,0,55,'…'))?></span>
</div></div></div>

<div class="ap-hero"><div class="wrap"><div class="ap-hero-in">
  <div class="ap-hero-tags">
    <a href="<?=hx($siteUrl.'/journals/'.$jSlug.'/')?>" class="ap-htag"><i class="fas fa-graduation-cap"></i> <?=hx($jName)?></a>
    <?php if($volLabel&&$issueUrl):?><a href="<?=hx($issueUrl)?>" class="ap-htag"><i class="fas fa-book-open"></i> <?=hx($volLabel)?></a><?php endif;?>
    <span class="ap-htag"><i class="fas fa-unlock-alt"></i> Open Access</span>
    <?php if($pageNo):?><span class="ap-htag"><i class="fas fa-file"></i> pp.<?=hx($pageNo)?></span><?php endif;?>
  </div>
  <?php if($article):?>
  <h1><?=hx($title)?></h1>
  <?php if($authorStr):?><div class="ap-hero-auth"><?=hx($authorStr)?></div><?php endif;?>
  <?php else:?><h1>Article Not Found</h1><?php endif;?>
</div></div></div>

<div class="ap-body"><div class="wrap">
<?php if(!$article):?>
<div class="ap-404">
  <i class="fas fa-file-slash" style="font-size:44px;color:#cbd5e1;display:block;margin-bottom:12px"></i>
  <h2 style="font-family:var(--serif);font-size:22px;color:var(--ink);margin-bottom:8px">Article not found</h2>
  <p style="color:var(--muted);font-size:14px;margin-bottom:18px">This article doesn't exist or hasn't been published yet.</p>
  <a href="<?=hx($siteUrl.'/journals/'.$jSlug.'/')?>" class="ap-btn b-blue"><i class="fas fa-arrow-left"></i> Back to Journal</a>
</div>
<?php else:?>
<div class="ap-cols">
<div>

  <?php if(!empty($authors)):?>
  <div class="sec">
    <div class="sec-h"><i class="fas fa-users"></i> Authors</div>
    <div class="auth-grid">
    <?php foreach($authors as $a):
      $fn=trim(($a['title']?$a['title'].' ':'').$a['first_name'].' '.($a['middle_name']?$a['middle_name'].' ':'').$a['last_name']);
      $ini=strtoupper(substr($a['first_name']??'',0,1).substr($a['last_name']??'',0,1));
    ?>
    <div class="auth-card">
      <div class="auth-av"><?=hx($ini)?></div>
      <div>
        <div class="auth-name"><?=hx($fn)?></div>
        <?php if($a['aff_name']):?><div class="auth-aff"><?=hx($a['aff_name'])?><?=$a['city']?', '.hx($a['city']):''?><?=$a['country']?', '.hx($a['country']):''?></div><?php endif;?>
        <?php if($a['is_corresponding']):?><div class="auth-corr"><i class="fas fa-envelope"></i> Corresponding Author</div><?php endif;?>
      </div>
    </div>
    <?php endforeach;?>
    </div>
  </div>
  <?php endif;?>

  <div class="sec">
    <div class="ap-chips">
      <?php if($doi):?><span class="ap-chip c-doi"><i class="fas fa-fingerprint"></i><a href="https://doi.org/<?=hx($doi)?>" target="_blank" rel="noopener"><?=hx($doi)?></a></span><?php endif;?>
      <?php if($pageNo):?><span class="ap-chip c-pg"><i class="fas fa-book-open"></i> pp.&nbsp;<?=hx($pageNo)?></span><?php endif;?>
      <?php if($pubDate):?><span class="ap-chip c-date"><i class="fas fa-calendar-check"></i> <?=hx(date('d M Y',strtotime($pubDate)))?></span><?php endif;?>
      <span class="ap-chip c-oa"><i class="fas fa-unlock-alt"></i> Open Access</span>
      <?php if($volLabel&&$issueUrl):?><span class="ap-chip c-vol"><i class="fas fa-book"></i><a href="<?=hx($issueUrl)?>"><?=hx($volLabel)?></a></span><?php endif;?>
    </div>
    <div class="art-meta-grid">
      <?php if($doi):?>
      <div class="art-meta-item">
        <div class="art-meta-icon" style="background:#e8f0fe"><i class="fas fa-fingerprint" style="color:#1a56db"></i></div>
        <div><div class="art-meta-label">DOI</div><a href="https://doi.org/<?=hx($doi)?>" target="_blank" rel="noopener" class="art-meta-val art-meta-link"><?=hx($doi)?></a></div>
      </div>
      <?php endif;?>
      <?php if($volLabel&&$issueUrl):?>
      <div class="art-meta-item">
        <div class="art-meta-icon" style="background:#f0f9ff"><i class="fas fa-book-open" style="color:#0369a1"></i></div>
        <div><div class="art-meta-label">Volume / Issue</div><a href="<?=hx($issueUrl)?>" class="art-meta-val art-meta-link"><?=hx($volLabel)?></a></div>
      </div>
      <?php endif;?>
      <?php if($pageNo):?>
      <div class="art-meta-item">
        <div class="art-meta-icon" style="background:#fef3e8"><i class="fas fa-file-alt" style="color:#c2560c"></i></div>
        <div><div class="art-meta-label">Page Numbers</div><div class="art-meta-val">pp. <?=hx($pageNo)?></div></div>
      </div>
      <?php endif;?>
      <?php if($pubDate):?>
      <div class="art-meta-item">
        <div class="art-meta-icon" style="background:#f0fdf4"><i class="fas fa-calendar-check" style="color:#16a34a"></i></div>
        <div><div class="art-meta-label">Published</div><div class="art-meta-val"><?=hx(date('d M Y',strtotime($pubDate)))?></div></div>
      </div>
      <?php endif;?>
      <div class="art-meta-item">
        <div class="art-meta-icon" style="background:#dcfce7"><i class="fas fa-unlock-alt" style="color:#0a6640"></i></div>
        <div><div class="art-meta-label">Access Type</div><div class="art-meta-val" style="color:#0a6640;font-weight:700">Open Access</div></div>
      </div>
      <?php if($article['tracking_code']??''):?>
      <div class="art-meta-item">
        <div class="art-meta-icon" style="background:#f5f3ff"><i class="fas fa-hashtag" style="color:#7c3aed"></i></div>
        <div><div class="art-meta-label">Tracking Code</div><div class="art-meta-val" style="font-family:monospace;font-size:12px"><?=hx($article['tracking_code'])?></div></div>
      </div>
      <?php endif;?>
    </div>

    <?php if($submittedDate||$acceptedDate||$pubDate):?>
    <div style="margin-top:16px">
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--muted);margin-bottom:12px">Publication Timeline</div>
      <div class="tl">
        <div class="tl-step"><div class="tl-dot <?=$submittedDate?'tl-done':'empty'?>"></div><div class="tl-lbl">Submitted</div><?php if($submittedDate):?><div class="tl-date"><?=hx(date('d M Y',strtotime($submittedDate)))?></div><?php endif;?></div>
        <div class="tl-step"><div class="tl-dot <?=$acceptedDate?'tl-done':'empty'?>"></div><div class="tl-lbl">Accepted</div><?php if($acceptedDate):?><div class="tl-date"><?=hx(date('d M Y',strtotime($acceptedDate)))?></div><?php endif;?></div>
        <div class="tl-step"><div class="tl-dot <?=$pubDate?'tl-done':'empty'?>"></div><div class="tl-lbl">Published</div><?php if($pubDate):?><div class="tl-date"><?=hx(date('d M Y',strtotime($pubDate)))?></div><?php endif;?></div>
      </div>
    </div>
    <?php endif;?>

    <!-- SIQ BUTTON -->
    <div style="margin-top:18px;padding-top:14px;border-top:1px solid var(--border)">
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--muted);margin-bottom:10px">Scholar Impact Quotient (SIQ)</div>
      <div class="siq-wrap">
        <button class="siq-shield-btn" onclick="siqOpen()" title="Rate this article">
          <svg viewBox="0 0 60 68" fill="none" xmlns="http://www.w3.org/2000/svg" width="50" height="56">
            <path d="M30 2 L56 13 L56 36 C56 52 30 66 30 66 C30 66 4 52 4 36 L4 13 Z" fill="url(#siqG1)" stroke="rgba(255,255,255,.22)" stroke-width="1.5"/>
            <defs><linearGradient id="siqG1" x1="30" y1="0" x2="30" y2="68" gradientUnits="userSpaceOnUse"><stop offset="0%" stop-color="#3bbfc4"/><stop offset="100%" stop-color="#1d93a0"/></linearGradient></defs>
            <text x="50%" y="40%" text-anchor="middle" fill="#fff" font-size="13" font-weight="700" font-family="Georgia,serif" dy=".15em">SIQ</text>
            <text x="50%" y="64%" text-anchor="middle" fill="rgba(255,255,255,.9)" font-size="12" font-family="Georgia,serif" dy=".1em" id="siqBadgeScore"><?=$siqRevealed?hx($siqScore):'-'?></text>
          </svg>
        </button>
        <button class="siq-rate-btn" onclick="siqOpen()"><i class="fas fa-star"></i> RATE ARTICLE</button>
      </div>
      <?php if($siqRevealed):?>
      <div style="font-size:12px;color:var(--muted);margin-top:5px"><i class="fas fa-users" style="color:var(--teal)"></i> Based on <?=(int)$siqCount?> rating<?=$siqCount>1?'s':''?></div>
      <?php elseif($userHasRated):?>
      <div style="font-size:12px;color:var(--muted);margin-top:5px"><i class="fas fa-check-circle" style="color:var(--green)"></i> You have rated this article</div>
      <?php else:?>
      <div style="font-size:12px;color:var(--muted);margin-top:5px"><i class="fas fa-info-circle" style="color:var(--teal)"></i> Be the first to rate this article</div>
      <?php endif;?>
    </div>

    <div class="ap-actions">
      <?php if($pdfUrl):?><a href="<?=hx($pdfUrl)?>" target="_blank" class="ap-btn b-red" onclick="trackDownload('pdf')"><i class="fas fa-file-pdf"></i> Download PDF</a><?php endif;?>
      <button class="ap-btn b-blue" onclick="apShowCite('<?=addslashes($cApa)?>')"><i class="fas fa-quote-left"></i> Cite this Article</button>
      <?php if($doi):?><a href="https://doi.org/<?=hx($doi)?>" target="_blank" class="ap-btn b-grn"><i class="fas fa-external-link-alt"></i> View via DOI</a><?php endif;?>
      <?php if($issueUrl):?><a href="<?=hx($issueUrl)?>" class="ap-btn b-out"><i class="fas fa-arrow-left"></i> Back to Issue</a><?php endif;?>
    </div>
  </div>

  <?php if($abstract):?>
  <div class="sec"><div class="sec-h"><i class="fas fa-align-left"></i> Abstract</div><div class="ap-abstract"><?=nl2br(hx($abstract))?></div></div>
  <?php endif;?>
  <?php if(!empty($keywords)):?>
  <div class="sec"><div class="sec-h"><i class="fas fa-tags"></i> Keywords</div><div class="kw-wrap"><?php foreach($keywords as $k):?><span class="kw"><?=hx($k)?></span><?php endforeach;?></div></div>
  <?php endif;?>
  <div class="sec">
    <div class="sec-h"><i class="fas fa-download"></i> Downloads</div>
    <div class="dl-grid">
      <?php if($pdfUrl):?><a href="<?=hx($pdfUrl)?>" target="_blank" class="dl-btn dl-pdf" onclick="trackDownload('pdf')"><i class="fas fa-file-pdf"></i> PDF</a><?php endif;?>
      <a href="<?=hx($xmlUrl)?>" target="_blank" class="dl-btn dl-xml" onclick="trackDownload('xml')"><i class="fas fa-code"></i> JATS XML</a>
    </div>
  </div>
  <?php if($refsHtml):?>
  <div class="sec"><div class="sec-h"><i class="fas fa-list-ol"></i> References</div><?=$refsHtml?></div>
  <?php endif;?>
  <div class="sec">
    <div class="sec-h"><i class="fas fa-chart-bar"></i> Metrics</div>
    <div style="font-weight:600;font-size:13px;color:var(--muted);margin-bottom:12px">Views &amp; Downloads</div>
    <div style="max-width:380px"><canvas id="metricsChart" height="140"></canvas></div>
  </div>
  <?php if(!empty($related)):?>
  <div class="sec">
    <div class="sec-h"><i class="fas fa-layer-group"></i> Similar Articles</div>
    <?php foreach($related as $ri=>$r):?>
    <div class="rel-item">
      <div class="rel-n"><?=$ri+1?></div>
      <div style="flex:1"><a href="<?=hx($siteUrl.'/journals/'.$jSlug.'/article.php?id='.(int)$r['submission_id'])?>" class="rel-t"><?=hx(mb_strimwidth($r['article_title']??'',0,120,'…'))?></a></div>
    </div>
    <?php endforeach;?>
  </div>
  <?php endif;?>

</div><!-- main col -->
<aside class="ap-right">
  <?php if($volume&&$issueUrl):?>
  <div class="iss-card">
    <div class="iss-lbl">Published In</div>
    <div class="iss-title"><?=hx($volLabel)?><?=$volume['vol_title']?'<br><span style="font-family:sans-serif;font-size:12px;font-weight:400;opacity:.75">'.hx($volume['vol_title']).'</span>':''?></div>
    <a href="<?=hx($issueUrl)?>" class="iss-link"><i class="fas fa-list-ol"></i> View Issue</a>
  </div>
  <?php endif;?>
  <div class="r-card">
    <div class="r-head"><i class="fas fa-star"></i> SIQ Rating</div>
    <div class="r-body" style="text-align:center;padding:16px 14px">
      <svg viewBox="0 0 60 68" fill="none" xmlns="http://www.w3.org/2000/svg" width="60" height="68" style="margin-bottom:8px">
        <path d="M30 2 L56 13 L56 36 C56 52 30 66 30 66 C30 66 4 52 4 36 L4 13 Z" fill="url(#siqGS)" stroke="rgba(255,255,255,.18)" stroke-width="1.5"/>
        <defs><linearGradient id="siqGS" x1="30" y1="0" x2="30" y2="68" gradientUnits="userSpaceOnUse"><stop offset="0%" stop-color="#3bbfc4"/><stop offset="100%" stop-color="#1d93a0"/></linearGradient></defs>
        <text x="50%" y="40%" text-anchor="middle" fill="#fff" font-size="13" font-weight="700" font-family="Georgia,serif" dy=".15em">SIQ</text>
        <text x="50%" y="64%" text-anchor="middle" fill="rgba(255,255,255,.92)" font-size="12" font-family="Georgia,serif" dy=".1em" id="siqSideScore"><?=$siqRevealed?hx($siqScore):'-'?></text>
      </svg>
      <div style="font-size:12px;color:var(--muted);margin-bottom:12px"><?=$siqRevealed?'Based on '.(int)$siqCount.' rating'.($siqCount>1?'s':''):'Not yet revealed'?></div>
      <button class="siq-rate-btn" onclick="siqOpen()" style="border-radius:6px;width:100%;justify-content:center"><i class="fas fa-star"></i> RATE ARTICLE</button>
    </div>
  </div>
  <div class="r-card">
    <div class="r-head"><i class="fas fa-download"></i> Downloads</div>
    <div class="r-body">
      <button class="s-dl sd-green" onclick="openPopup(<?=$sid?>,'certificate')"><i class="fas fa-certificate"></i> Download Certificate</button>
      <button class="s-dl sd-yellow" onclick="openPopup(<?=$sid?>,'acceptance')"><i class="fas fa-envelope-open-text"></i> Download Acceptance Letter</button>
      <a href="https://communeglobal.com/asset/cover-page.pdf" target="_blank" class="s-dl sd-red"><i class="fas fa-file-pdf"></i> Download Cover Page</a>
      <a href="https://communeglobal.com/asset/editorial-board.pdf" target="_blank" class="s-dl sd-indigo"><i class="fas fa-users"></i> Download Editorial Board</a>
      <div style="border-top:1px solid var(--border);margin:8px 0;padding-top:8px">
        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--muted);margin-bottom:6px">Additional Downloads</div>
        <?php if($pdfUrl):?><a href="<?=hx($pdfUrl)?>" target="_blank" class="s-dl sd-pdf" onclick="trackDownload('pdf')"><i class="fas fa-file-pdf"></i> PDF</a><?php endif;?>
        <a href="<?=hx($xmlUrl)?>" target="_blank" class="s-dl sd-xml" onclick="trackDownload('xml')"><i class="fas fa-code"></i> JATS XML</a>
      </div>
    </div>
  </div>
  <div class="r-card">
    <div class="r-head"><i class="fas fa-share-alt"></i> Share</div>
    <div class="r-body">
      <div class="share-btns">
        <a href="https://www.facebook.com/sharer/sharer.php?u=<?=urlencode($articleUrl)?>" target="_blank" class="sh-btn sh-fb"><i class="fab fa-facebook-f"></i></a>
        <a href="https://twitter.com/intent/tweet?url=<?=urlencode($articleUrl)?>&text=<?=urlencode($title)?>" target="_blank" class="sh-btn sh-tw"><i class="fab fa-twitter"></i></a>
        <a href="https://wa.me/?text=<?=urlencode($title.' '.$articleUrl)?>" target="_blank" class="sh-btn sh-wa"><i class="fab fa-whatsapp"></i></a>
        <a href="mailto:?subject=<?=urlencode($title)?>&body=<?=urlencode('Check this article: '.$articleUrl)?>" class="sh-btn sh-em"><i class="fas fa-envelope"></i></a>
      </div>
    </div>
  </div>
  <div class="r-card">
    <div class="r-head"><i class="fas fa-chart-pie"></i> Metrics</div>
    <div class="r-body">
      <div class="metrics-grid">
        <div class="metric-box"><div class="metric-n" id="sideViews">—</div><div class="metric-l">Views</div></div>
        <div class="metric-box"><div class="metric-n" id="sideDl">—</div><div class="metric-l">Downloads</div></div>
      </div>
    </div>
  </div>
  <div class="r-card">
    <div class="r-head"><i class="fas fa-graduation-cap"></i> How to Cite</div>
    <div class="r-body">
      <select class="cite-sel" id="citeFmt" onchange="updateCitation()">
        <option value="apa">APA</option><option value="mla">MLA</option><option value="harvard">Harvard</option>
      </select>
      <div class="cite-box">
        <div id="citeText"><?=$cApa?></div>
        <button class="cite-copy" onclick="copyCite()"><i class="fas fa-copy"></i> Copy</button>
      </div>
    </div>
  </div>
  <div class="r-card">
    <div class="r-head"><i class="fas fa-database"></i> Metrics &amp; Indexing</div>
    <div class="r-body">
      <?php if($doi):?>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px">
        <div style="background:#f0fdf4;border-radius:8px;padding:10px;text-align:center"><div style="font-size:11px;font-weight:700;color:var(--muted);margin-bottom:6px">Dimensions</div><span class="__dimensions_badge_embed__" data-doi="<?=hx($doi)?>" data-style="small_circle"></span></div>
        <div style="background:#f0fdf4;border-radius:8px;padding:10px;text-align:center"><div style="font-size:11px;font-weight:700;color:var(--muted);margin-bottom:6px">PlumX</div><a href="https://plu.mx/plum/a/?doi=<?=urlencode($doi)?>" class="plumx-plum-print-popup" style="font-size:11px"></a></div>
      </div>
      <?php endif;?>
      <a href="https://www.semanticscholar.org/search?q=<?=urlencode($title)?>" target="_blank" rel="noopener" class="idx-btn i-indigo"><i class="fas fa-search"></i> Semantic Scholar</a>
      <a href="https://www.researchgate.net/search?q=<?=urlencode($title)?>" target="_blank" rel="noopener" class="idx-btn i-teal"><i class="fas fa-flask"></i> ResearchGate</a>
      <a href="https://openalex.org/works?filter=title_and_abstract.search:<?=urlencode('"'.$title.'"')?>" target="_blank" rel="noopener" class="idx-btn i-purple"><i class="fas fa-globe"></i> OpenAlex</a>
      <?php if($doi):?><a href="https://www.scilit.net/search?q=<?=urlencode($doi)?>" target="_blank" rel="noopener" class="idx-btn i-yellow"><i class="fas fa-book"></i> Scilit</a><?php endif;?>
      <a href="https://econpapers.repec.org/scripts/search.pf?ft=<?=urlencode($title)?>" target="_blank" rel="noopener" class="idx-btn i-green"><i class="fas fa-chart-line"></i> EconPapers</a>
      <div style="margin-top:10px;font-size:11px;color:var(--muted);line-height:1.55;background:#f8fafc;border-radius:6px;padding:8px;border-left:3px solid var(--border)"><i class="fas fa-info-circle" style="color:var(--blue)"></i> A published paper may take 4–5 working days to appear in these indices.</div>
    </div>
  </div>
  <?php if(!empty($allVolumes)):?>
  <div class="r-card">
    <div class="r-head"><i class="fas fa-archive"></i> All Issues</div>
    <div class="r-body">
      <ul class="vlist">
      <?php foreach($allVolumes as $v):$isAct=$volume&&(int)$v['id']===(int)$volume['id'];?>
      <li><a href="<?=hx($siteUrl.'/journals/'.$jSlug.'/issue.php?id='.(int)$v['id'])?>" class="<?=$isAct?'active':''?>">
        <span><strong>Vol.<?=(int)$v['volume']?> · Issue <?=(int)$v['issue']?></strong><?=$v['vol_year']?' ('.$v['vol_year'].')':''?></span>
        <?php if($isAct):?><i class="fas fa-circle" style="font-size:7px;color:var(--blue)"></i><?php endif;?>
      </a></li>
      <?php endforeach;?>
      </ul>
    </div>
  </div>
  <?php endif;?>
</aside>
</div><!-- .ap-cols -->
<?php endif;?>
</div></div>
</div>

<!-- Verify Popup -->
<div class="popup-overlay" id="dlPopup" onclick="if(event.target===this)closePopup()">
  <div class="popup-box">
    <h3 id="popupTitle">Verify to Download</h3>
    <form id="popupForm" onsubmit="submitPopup(event)">
      <input type="hidden" id="pop_sid" name="id"><input type="hidden" id="pop_type" name="doc_type">
      <label class="pf-label">Author Name</label><input type="text" name="author_name" required class="pf-input" placeholder="Full name as on paper">
      <label class="pf-label">Author Email</label><input type="email" name="author_email" required class="pf-input" placeholder="Email used during submission">
      <div class="pf-error" id="popError"></div>
      <div class="pf-btns"><button type="button" class="ap-btn b-out" onclick="closePopup()">Cancel</button><button type="submit" class="ap-btn b-blue"><i class="fas fa-check"></i> Verify &amp; Download</button></div>
    </form>
  </div>
</div>
<!-- Cite Modal -->
<div class="ap-modal" id="apModal" onclick="if(event.target===this)apCC()">
  <div class="ap-mbox">
    <h3><i class="fas fa-quote-left" style="color:var(--blue)"></i> Cite this Article</h3>
    <div class="ap-mcite" id="apCT"></div>
    <div class="ap-mbtns"><button class="ap-btn b-out" onclick="apCC()">Close</button><button class="ap-btn b-blue" onclick="apCM()"><i class="fas fa-copy"></i> Copy</button></div>
  </div>
</div>
<!-- SIQ Popup -->
<div class="siq-overlay" id="siqOverlay" onclick="if(event.target===this)siqClose()">
  <div class="siq-modal">
    <div class="siq-modal-head">
      <svg viewBox="0 0 60 68" fill="none" xmlns="http://www.w3.org/2000/svg" width="56" height="64">
        <path d="M30 2 L56 13 L56 36 C56 52 30 66 30 66 C30 66 4 52 4 36 L4 13 Z" fill="url(#siqGP)" stroke="rgba(255,255,255,.2)" stroke-width="1.5"/>
        <defs><linearGradient id="siqGP" x1="30" y1="0" x2="30" y2="68" gradientUnits="userSpaceOnUse"><stop offset="0%" stop-color="#3bbfc4"/><stop offset="100%" stop-color="#1d93a0"/></linearGradient></defs>
        <text x="50%" y="40%" text-anchor="middle" fill="#fff" font-size="13" font-weight="700" font-family="Georgia,serif" dy=".15em">SIQ</text>
        <text x="50%" y="64%" text-anchor="middle" fill="rgba(255,255,255,.92)" font-size="12" font-family="Georgia,serif" dy=".1em" id="siqPopScore">-</text>
      </svg>
    </div>
    <div id="siqStep1">
      <h2 class="siq-modal-title">How do you rate this article?</h2>
      <div id="siqSlidersWrap"></div>
      <div class="siq-foot"><button class="siq-btn siq-ghost" onclick="siqClose()">CANCEL</button><button class="siq-btn siq-primary" onclick="siqGoStep2()">NEXT</button></div>
    </div>
    <div id="siqStep2" style="display:none">
      <div style="text-align:center;margin-bottom:16px"><div class="icmje-badge"><i class="fas fa-award"></i> ICMJE</div></div>
      <h2 class="siq-modal-title" style="font-size:18px">Conflicts of Interest</h2>
      <div class="siq-score-line">SIQ: <strong id="siqScoreDisplay" style="color:var(--teal)">-</strong></div>
      <p class="siq-coi-text">Please disclose any and all potential conflicts of interest. Declaring a conflict will not prevent you from rating, but affects the weight assigned. We adhere to <strong>ICMJE guidelines</strong>.</p>
      <div class="siq-radio-group">
        <label class="siq-radio-lbl"><input type="radio" name="siqCOI" value="no" checked onchange="siqToggleCOI()"> No</label>
        <label class="siq-radio-lbl"><input type="radio" name="siqCOI" value="yes" onchange="siqToggleCOI()"> Yes</label>
      </div>
      <textarea id="siqCOIText" class="siq-textarea" placeholder="Describe your conflict of interest…" style="display:none" maxlength="1000"></textarea>
      <div class="siq-foot" style="margin-top:20px">
        <button class="siq-btn siq-ghost" onclick="siqGoStep1()">PREV</button>
        <button class="siq-btn siq-ghost" onclick="siqClose()">CANCEL</button>
        <button class="siq-btn siq-primary" onclick="siqSubmit()" id="siqSubmitBtn">SUBMIT</button>
      </div>
    </div>
    <div id="siqStep3" style="display:none;padding:8px 0 20px">
      <div class="siq-ty-script">Thank you!</div>
      <p class="siq-ty-sub" id="siqThanksMsg">You're the first to rate this article!<br>The SIQ will be revealed after one more rating.</p>
      <div style="text-align:center;margin-top:16px">
        <button class="siq-btn siq-orange" onclick="siqGoComment()"><i class="fas fa-comment-alt"></i> ADD COMMENT</button>
      </div>
    </div>
  </div>
</div>

<?php if($article): ?>
<div class="cm-wrap">

  <!-- Comments list: ALWAYS visible -->
  <div class="cm-section">
    <div class="cm-head">
      <i class="fas fa-comments"></i> Reader Comments
      <?php if($approvedComments): ?>
        <span style="background:#eff6ff;color:#1a56db;font-size:12px;font-weight:700;border-radius:12px;padding:2px 10px;margin-left:4px"><?=count($approvedComments)?></span>
      <?php endif; ?>
    </div>
    <?php if($approvedComments): ?>
    <div class="cm-list">
      <?php foreach($approvedComments as $cm):
        $ini=strtoupper(substr($cm['name'],0,1));
        $ts=strtotime($cm['created_at']); $diff=time()-$ts;
        $timeAgo=$diff<60?'just now':($diff<3600?floor($diff/60).' min ago':($diff<86400?floor($diff/3600).' hr ago':($diff<2592000?floor($diff/86400).' days ago':date('d M Y',$ts))));
      ?>
      <div class="cm-card">
        <div class="cm-card-top">
          <div class="cm-avatar"><?=hx($ini)?></div>
          <div><div class="cm-author-name"><?=hx($cm['name'])?></div><div class="cm-date"><?=hx($timeAgo)?></div></div>
        </div>
        <div class="cm-text"><?=nl2br(hx($cm['comment']))?></div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div class="cm-empty"><i class="far fa-comment-dots"></i>No comments yet. Be the first to share your thoughts!</div>
    <?php endif; ?>
  </div>

  <!-- ADD COMMENT: gated by $userHasRated (session OR IP check) -->
  <div class="cm-section" id="cmFormSection">
    <div class="cm-head"><i class="fas fa-pen"></i> Leave a Comment</div>

    <?php if($userHasRated): ?>
    <!-- ✅ RATED — show form -->
    <form id="cmForm" onsubmit="submitComment(event)">
      <input type="hidden" name="submission_id" value="<?=(int)$sid?>">
      <div class="cmf-group">
        <label class="cmf-label">Your Name <span class="cmf-required">*</span></label>
        <input type="text" name="name" id="cmNameInput" class="cmf-input" placeholder="Full name" required maxlength="120">
      </div>
      <div class="cmf-group">
        <label class="cmf-label">Comment <span class="cmf-required">*</span></label>
        <textarea name="comment" id="cmCommentBox" class="cmf-textarea" placeholder="Share your thoughts about this article…" required minlength="10" maxlength="3000"></textarea>
        <div style="font-size:11px;color:#94a3b8;text-align:right;margin-top:3px"><span id="cmCharCount">0</span> / 3000</div>
      </div>
      <div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-top:6px">
        <button type="submit" class="cmf-submit" id="cmSubmitBtn"><i class="fas fa-paper-plane"></i> Submit Comment</button>
        <span style="font-size:11.5px;color:#94a3b8"><i class="fas fa-shield-alt" style="color:#22c55e"></i> Comments are reviewed before publishing</span>
      </div>
      <div class="cmf-msg" id="cmMsg"></div>
    </form>

    <?php else: ?>
    <!-- 🔒 NOT RATED — show nudge -->
    <div class="cm-rate-nudge">
      <i class="fas fa-star nudge-icon"></i>
      <div class="cm-rate-nudge-text">
        <div class="cm-rate-nudge-title">Rate this article to add a comment</div>
        <div class="cm-rate-nudge-sub">Submit your SIQ rating first — it only takes a moment.</div>
      </div>
      <button class="cm-rate-nudge-btn" onclick="siqOpen()"><i class="fas fa-star"></i> Rate Article</button>
    </div>
    <?php endif; ?>
  </div>

</div>
<?php endif; ?>

<script async src="https://badge.dimensions.ai/badge.js" charset="utf-8"></script>
<script type="text/javascript" src="//cdn.plu.mx/widget-popup.js"></script>
<script>
const cites={apa:<?=json_encode(buildCite($article,$authors,'apa',$jName))?>,mla:<?=json_encode(buildCite($article,$authors,'mla',$jName))?>,harvard:<?=json_encode(buildCite($article,$authors,'harvard',$jName))?>};
function updateCitation(){document.getElementById('citeText').textContent=cites[document.getElementById('citeFmt').value];}
function copyCite(){const t=document.getElementById('citeText').textContent;navigator.clipboard&&navigator.clipboard.writeText(t).then(()=>{const b=document.querySelector('.cite-copy');b.innerHTML='<i class="fas fa-check"></i> Done';setTimeout(()=>b.innerHTML='<i class="fas fa-copy"></i> Copy',2000);});}
function apShowCite(t){document.getElementById('apCT').textContent=t;document.getElementById('apModal').classList.add('open');}
function apCC(){document.getElementById('apModal').classList.remove('open');}
function apCM(){const t=document.getElementById('apCT').textContent;navigator.clipboard&&navigator.clipboard.writeText(t).then(()=>{const b=document.querySelector('#apModal .b-blue');b.innerHTML='<i class="fas fa-check"></i> Copied!';setTimeout(()=>b.innerHTML='<i class="fas fa-copy"></i> Copy',2000);});}
function openPopup(id,type){document.getElementById('pop_sid').value=id;document.getElementById('pop_type').value=type;document.getElementById('popupTitle').textContent=type==='certificate'?'Verify to Download Certificate':'Verify to Download Acceptance Letter';document.getElementById('popError').style.display='none';document.getElementById('popupForm').reset();document.getElementById('dlPopup').classList.add('open');}
function closePopup(){document.getElementById('dlPopup').classList.remove('open');}
function submitPopup(e){e.preventDefault();const fd=new FormData(e.target);fetch('/journals/verify_author.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.status==='success'){const t=fd.get('doc_type'),id=d.id;if(t==='certificate')window.open('/journals/generate_certificate.php?id='+id,'_blank');else window.open('/journals/acceptance-letter.php?id='+id,'_blank');closePopup();}else{const er=document.getElementById('popError');er.textContent=d.message||'Verification failed.';er.style.display='block';}}).catch(()=>{const er=document.getElementById('popError');er.textContent='Network error.';er.style.display='block';});}
const TRACK_URL='/journals/article_track.php';
const ARTICLE_ID=<?=(int)$sid?>;
function trackEvent(ev){return fetch(TRACK_URL,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+ARTICLE_ID+'&event='+ev}).then(r=>{if(!r.ok)throw new Error();return r.json();}).catch(()=>null);}
function applyStats(d){const v=(d&&d.views)?d.views:0,dl=(d&&d.downloads)?d.downloads:0;const sv=document.getElementById('sideViews'),sd=document.getElementById('sideDl');if(sv)sv.textContent=v.toLocaleString();if(sd)sd.textContent=dl.toLocaleString();if(metricsChart){metricsChart.data.datasets[0].data=[v,dl];metricsChart.update();}}
function trackDownload(t){trackEvent(t==='xml'?'xml_download':'pdf_download').then(applyStats);}
var metricsChart=null;
function initChart(v,dl){const ctx=document.getElementById('metricsChart');if(!ctx)return;metricsChart=new Chart(ctx,{type:'bar',data:{labels:['Views','Downloads'],datasets:[{label:'Count',data:[v,dl],backgroundColor:['rgba(26,86,219,.15)','rgba(10,102,64,.15)'],borderColor:['rgba(26,86,219,1)','rgba(10,102,64,1)'],borderWidth:2,borderRadius:5}]},options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{font:{size:11},stepSize:1},suggestedMax:5}}}});}
document.addEventListener('DOMContentLoaded',function(){
  const sv=document.getElementById('sideViews'),sd=document.getElementById('sideDl');
  if(sv)sv.textContent='0';if(sd)sd.textContent='0';initChart(0,0);trackEvent('view').then(applyStats);
  document.querySelectorAll('a[href]').forEach(a=>{if(a.getAttribute('onclick'))return;const h=a.getAttribute('href')||'';if(h&&(h.endsWith('.pdf')||h.includes('/uploads/')||h.includes('author/'))){a.addEventListener('click',()=>trackDownload('pdf'));}});
});
document.getElementById('cmCommentBox')?.addEventListener('input',function(){document.getElementById('cmCharCount').textContent=this.value.length;});
function submitComment(e){
  e.preventDefault();
  const btn=document.getElementById('cmSubmitBtn'),msg=document.getElementById('cmMsg');
  btn.disabled=true;btn.innerHTML='<i class="fas fa-spinner fa-spin"></i> Submitting…';msg.style.display='none';
  fetch('/journals/article_comment_submit.php',{method:'POST',body:new FormData(document.getElementById('cmForm'))})
    .then(r=>r.json()).then(d=>{
      if(d.status==='success'){showCmMsg('success',d.message||'Comment submitted!');document.getElementById('cmForm').reset();document.getElementById('cmCharCount').textContent='0';}
      else showCmMsg('error',d.message||'Something went wrong.');
    }).catch(()=>showCmMsg('error','Network error. Please try again.'))
    .finally(()=>{btn.disabled=false;btn.innerHTML='<i class="fas fa-paper-plane"></i> Submit Comment';});
}
function showCmMsg(t,text){const el=document.getElementById('cmMsg');el.className='cmf-msg '+t;el.textContent=text;el.style.display='block';el.scrollIntoView({behavior:'smooth',block:'nearest'});}
/* SIQ */
const SIQ_CRITERIA=[{key:'clarity',label:'Clarity of background and rationale'},{key:'clinical',label:'Clinical importance'},{key:'study',label:'Study design and methods'},{key:'data',label:'Data analysis'},{key:'novelty',label:'Novelty of conclusions'},{key:'presentation',label:'Quality of presentation'}];
function siqBuildSliders(){const wrap=document.getElementById('siqSlidersWrap');if(!wrap||wrap.dataset.built)return;wrap.dataset.built='1';let html='';SIQ_CRITERIA.forEach(c=>{html+=`<div class="siq-row"><div class="siq-row-lbl">${c.label}</div><div class="siq-sw"><div class="siq-tick-row">${[...Array(10)].map((_,i)=>`<span class="siq-tick${i===0?' on':''}" data-v="${i+1}">${i+1}</span>`).join('')}</div><input type="range" min="1" max="10" value="1" class="siq-range" id="siq_${c.key}" oninput="siqSlide(this)"></div></div>`;});wrap.innerHTML=html;}
function siqSlide(el){const val=parseInt(el.value),pct=((val-1)/9*100).toFixed(1);el.style.background=`linear-gradient(to right,var(--teal) ${pct}%,#dde9ec ${pct}%)`;const sw=el.closest('.siq-sw')||el.parentElement;sw.querySelectorAll('.siq-tick').forEach(t=>t.classList.toggle('on',parseInt(t.dataset.v)<=val));}
function siqCalcAvg(){let s=0;SIQ_CRITERIA.forEach(c=>{const el=document.getElementById('siq_'+c.key);s+=el?parseInt(el.value):1;});return(s/SIQ_CRITERIA.length).toFixed(1);}
function siqOpen(){siqBuildSliders();['siqStep1','siqStep2','siqStep3'].forEach((id,i)=>document.getElementById(id).style.display=i===0?'':'none');document.getElementById('siqOverlay').classList.add('open');SIQ_CRITERIA.forEach(c=>{const el=document.getElementById('siq_'+c.key);if(el)siqSlide(el);});}
function siqClose(){document.getElementById('siqOverlay').classList.remove('open');}
function siqGoStep2(){const avg=siqCalcAvg();document.getElementById('siqScoreDisplay').textContent=avg;document.getElementById('siqPopScore').textContent=avg;document.getElementById('siqStep1').style.display='none';document.getElementById('siqStep2').style.display='';}
function siqGoStep1(){document.getElementById('siqStep2').style.display='none';document.getElementById('siqStep1').style.display='';}
function siqToggleCOI(){const yes=document.querySelector('input[name="siqCOI"][value="yes"]');document.getElementById('siqCOIText').style.display=yes&&yes.checked?'':'none';}
function siqSubmit(){
  const btn=document.getElementById('siqSubmitBtn');
  btn.disabled=true;btn.textContent='Submitting…';
  const fd=new FormData();
  fd.append('submission_id','<?=(int)$sid?>');
  SIQ_CRITERIA.forEach(c=>{const el=document.getElementById('siq_'+c.key);fd.append(c.key,el?el.value:'1');});
  const coi=document.querySelector('input[name="siqCOI"]:checked');
  fd.append('conflict',coi?coi.value:'no');
  fd.append('conflict_detail',document.getElementById('siqCOIText').value||'');
  fetch('/journals/article_siq_submit.php',{method:'POST',body:fd})
    .then(r=>r.json()).then(d=>{
      if(d.siq_score){['siqBadgeScore','siqSideScore','siqPopScore'].forEach(id=>{const el=document.getElementById(id);if(el)el.textContent=d.siq_score;});}
      document.getElementById('siqThanksMsg').innerHTML=d.message||'Thank you for rating!';
      document.getElementById('siqStep2').style.display='none';
      document.getElementById('siqStep3').style.display='';
      /* Always reload so comment form appears */
      setTimeout(()=>window.location.reload(),2200);
    })
    .catch(()=>{
      document.getElementById('siqThanksMsg').innerHTML='Thank you for rating!';
      document.getElementById('siqStep2').style.display='none';
      document.getElementById('siqStep3').style.display='';
      setTimeout(()=>window.location.reload(),2200);
    })
    .finally(()=>{btn.disabled=false;btn.textContent='SUBMIT';});
}
function siqGoComment(){
  siqClose();
  const sec=document.getElementById('cmFormSection');
  if(sec){setTimeout(()=>{sec.scrollIntoView({behavior:'smooth',block:'center'});const ni=document.getElementById('cmNameInput');if(ni)setTimeout(()=>ni.focus(),500);},260);}
}
</script>
<?php include __DIR__ . '/../include/footer.php'; ?>