<?php
/**
 * FILE: public_html/journals/generate_certificate.php
 * Generates a simple publication certificate for download.
 * Requires verified submission_id via GET param.
 */
session_start();
ini_set('display_errors', 0);

$configPaths = [
    __DIR__ . '/../config/db_new.php',
    __DIR__ . '/../config/db.php',
];
foreach ($configPaths as $cp) {
    if (file_exists($cp)) { include_once $cp; break; }
}

$sid = (int)($_GET['id'] ?? 0);

if (!$sid || !isset($pdo)) {
    http_response_code(400); echo 'Invalid request.'; exit;
}

// Load article + authors
$article = null; $authors = []; $journal = null;
try {
    $s = $pdo->prepare("
        SELECT s.submission_id, s.tracking_code, mi.article_title, pf.doi,
               pf.publication_date, pf.page_no, pf.volume_id,
               jv.volume AS vol_num, jv.issue AS vol_iss, jv.year AS vol_year,
               j.name AS journal_name
        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
    ");
    $s->execute([$sid]); $article = $s->fetch(PDO::FETCH_ASSOC);

    $s2 = $pdo->prepare("SELECT * FROM submission_authors WHERE submission_id = ? ORDER BY author_order");
    $s2->execute([$sid]); $authors = $s2->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    http_response_code(500); echo 'Error loading article.'; exit;
}

if (!$article) { http_response_code(404); echo 'Article not found.'; exit; }

$title = $article['article_title'] ?? 'Untitled';
$jName = $article['journal_name']  ?? 'Communeglobal International Journal of Social Sciences (CIJSS)';
$doi   = $article['doi']           ?? '';
$pubD  = $article['publication_date'] ? date('d F Y', strtotime($article['publication_date'])) : date('d F Y');
$vol   = $article['vol_num'] ? 'Volume '.$article['vol_num'].', Issue '.$article['vol_iss'] : '';
$pg    = $article['page_no'] ?? '';
$authorNames = implode(', ', array_map(fn($a) =>
    trim(($a['title']?$a['title'].' ':'').$a['first_name'].' '.($a['middle_name']?$a['middle_name'].' ':'').$a['last_name'])
, $authors));

function hx($v):string{return htmlspecialchars($v??'',ENT_QUOTES,'UTF-8');}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Certificate of Publication — <?= hx($title) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600;700&family=Lato:wght@300;400;700&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#f0f0f0;display:flex;align-items:center;justify-content:center;min-height:100vh;font-family:'Lato',sans-serif;padding:20px}
.cert{width:800px;background:#fff;padding:60px 70px;border:2px solid #c8a96a;position:relative;box-shadow:0 8px 40px rgba(0,0,0,.15)}
.cert::before{content:'';position:absolute;inset:10px;border:1px solid #e8d5a3;pointer-events:none}
.cert-logo{text-align:center;margin-bottom:28px}
.cert-logo span{font-family:'Cormorant Garamond',serif;font-size:26px;font-weight:700;color:#1e3a5f;letter-spacing:1px}
.cert-logo small{display:block;font-size:11px;color:#6b7280;letter-spacing:2px;text-transform:uppercase;margin-top:3px}
.cert-divider{border:none;border-top:1.5px solid #c8a96a;margin:18px auto;width:80px}
.cert-heading{font-family:'Cormorant Garamond',serif;font-size:34px;font-weight:600;color:#1e3a5f;text-align:center;margin-bottom:8px;letter-spacing:.5px}
.cert-sub{font-size:13px;color:#9ca3af;text-align:center;text-transform:uppercase;letter-spacing:2px;margin-bottom:32px}
.cert-body{font-size:14.5px;color:#374151;line-height:1.85;text-align:center;margin-bottom:28px}
.cert-body .authors{font-weight:700;color:#1e3a5f;font-size:16px;margin:8px 0}
.cert-body .art-title{font-style:italic;color:#1e3a5f;font-size:15px;margin:8px 0 14px}
.cert-meta{background:#f8f5ef;border-radius:8px;padding:16px 24px;margin:24px 0;display:grid;grid-template-columns:1fr 1fr;gap:10px}
.cert-meta-row{font-size:13px;color:#374151}
.cert-meta-row span{font-weight:700;color:#1e3a5f}
.cert-footer{display:flex;align-items:flex-end;justify-content:space-between;margin-top:40px}
.cert-sig{text-align:center}
.cert-sig-line{width:160px;border-top:1px solid #374151;margin:0 auto 5px}
.cert-sig-name{font-weight:700;font-size:13px;color:#1e3a5f}
.cert-sig-role{font-size:11.5px;color:#6b7280}
.cert-stamp{width:80px;height:80px;border-radius:50%;background:#1e3a5f;display:flex;align-items:center;justify-content:center;color:#c8a96a;font-size:28px}
.cert-date-issued{font-size:12px;color:#6b7280;text-align:center;margin-top:20px}
@media print{body{background:#fff}.cert{box-shadow:none;border:2px solid #c8a96a}}
</style>
</head>
<body>
<div class="cert">
  <div class="cert-logo">
    <span>COMMUNEGLOBAL</span>
    <small>International Publishing</small>
  </div>
  <hr class="cert-divider">
  <div class="cert-heading">Certificate of Publication</div>
  <div class="cert-sub">Open Access Research</div>

  <div class="cert-body">
    <p>This is to certify that the research paper submitted by</p>
    <p class="authors"><?= hx($authorNames) ?></p>
    <p>titled</p>
    <p class="art-title">"<?= hx($title) ?>"</p>
    <p>has been successfully peer-reviewed and published in the</p>
    <p style="font-weight:700;color:#1e3a5f;margin-top:6px"><?= hx($jName) ?></p>
  </div>

  <div class="cert-meta">
    <?php if($doi):?><div class="cert-meta-row"><span>DOI:</span> <?= hx($doi) ?></div><?php endif;?>
    <?php if($vol):?><div class="cert-meta-row"><span>Volume/Issue:</span> <?= hx($vol) ?></div><?php endif;?>
    <?php if($pg):?><div class="cert-meta-row"><span>Pages:</span> <?= hx($pg) ?></div><?php endif;?>
    <div class="cert-meta-row"><span>Published:</span> <?= hx($pubD) ?></div>
  </div>

  <div class="cert-footer">
    <div class="cert-sig">
      <div class="cert-sig-line"></div>
      <div class="cert-sig-name">Editorial Office</div>
      <div class="cert-sig-role"><?= hx($jName) ?></div>
    </div>
    <div class="cert-stamp"><i>✦</i></div>
    <div class="cert-sig">
      <div class="cert-sig-line"></div>
      <div class="cert-sig-name">Managing Editor</div>
      <div class="cert-sig-role">Communeglobal Publishing</div>
    </div>
  </div>

  <div class="cert-date-issued">Certificate issued on <?= date('d F Y') ?> · communeglobal.com</div>
</div>
<script>
window.onload = function() {
  // Auto trigger print dialog so user can save as PDF
  setTimeout(function() { window.print(); }, 600);
};
</script>
</body>
</html>