<?php
/**
 * FILE: public_html/journals/acceptance-letter.php
 * Generates an acceptance letter for verified authors.
 */
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; }

$article = null; $authors = [];
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, 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
    ");
    $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.'; exit; }

if (!$article) { http_response_code(404); echo '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'] ?? '';
$corr    = null;
foreach ($authors as $a) { if ($a['is_corresponding']) { $corr = $a; break; } }
if (!$corr && !empty($authors)) $corr = $authors[0];
$corrName = $corr ? trim(($corr['title']?$corr['title'].' ':'').$corr['first_name'].' '.($corr['middle_name']?$corr['middle_name'].' ':'').$corr['last_name']) : 'Author';
$allAuthors = 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>Acceptance Letter — <?= hx($title) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700&family=Playfair+Display:wght@600;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}
.letter{width:760px;background:#fff;padding:0;box-shadow:0 8px 40px rgba(0,0,0,.15)}
.letter-header{background:#1e3a5f;padding:28px 48px;display:flex;align-items:center;justify-content:space-between}
.lh-logo{color:#fff}
.lh-logo h1{font-family:'Playfair Display',serif;font-size:22px;font-weight:700;letter-spacing:.5px}
.lh-logo p{font-size:10.5px;opacity:.75;letter-spacing:1.5px;text-transform:uppercase;margin-top:3px}
.lh-date{color:rgba(255,255,255,.75);font-size:12px;text-align:right}
.letter-body{padding:44px 48px}
.lb-ref{font-size:12px;color:#6b7280;margin-bottom:24px}
.lb-ref span{font-weight:700;color:#374151}
.lb-salute{font-size:15px;color:#1e3a5f;font-weight:700;margin-bottom:16px}
.lb-para{font-size:13.5px;color:#374151;line-height:1.8;margin-bottom:14px}
.lb-title{background:#f0f5ff;border-left:4px solid #1e3a5f;padding:12px 16px;font-style:italic;font-size:14px;color:#1e3a5f;margin:16px 0;font-weight:600;line-height:1.4}
.lb-meta{background:#f9fafb;border-radius:8px;padding:16px 20px;margin:20px 0;font-size:13px;color:#374151}
.lb-meta-row{display:flex;gap:10px;margin-bottom:7px}
.lb-meta-row:last-child{margin-bottom:0}
.lb-meta-key{font-weight:700;color:#1e3a5f;min-width:130px}
.lb-closing{font-size:13.5px;color:#374151;line-height:1.8;margin-top:24px}
.lb-sig{margin-top:36px}
.lb-sig-line{width:140px;border-top:1px solid #374151;margin-bottom:6px}
.lb-sig-name{font-weight:700;font-size:13.5px;color:#1e3a5f}
.lb-sig-role{font-size:12px;color:#6b7280;margin-top:2px}
.letter-footer{background:#f8f8f8;border-top:1px solid #e5e7eb;padding:14px 48px;text-align:center;font-size:11px;color:#9ca3af}
@media print{body{background:#fff}.letter{box-shadow:none}}
</style>
</head>
<body>
<div class="letter">
  <div class="letter-header">
    <div class="lh-logo">
      <h1>COMMUNEGLOBAL</h1>
      <p>International Academic Publishing</p>
    </div>
    <div class="lh-date">
      Date: <?= date('d F Y') ?><br>
      <?php if($article['tracking_code']??false):?>
      Ref: <?= hx($article['tracking_code']) ?>
      <?php endif;?>
    </div>
  </div>

  <div class="letter-body">
    <div class="lb-ref">
      <span>To:</span> <?= hx($corrName) ?><?php if($corr&&$corr['email']??false):?> &lt;<?= hx($corr['email']) ?>&gt;<?php endif;?>
    </div>

    <div class="lb-salute">Dear <?= hx($corrName) ?>,</div>

    <p class="lb-para">
      We are pleased to inform you that your manuscript submitted to the <strong><?= hx($jName) ?></strong> has been accepted for publication following a rigorous peer-review process.
    </p>

    <div class="lb-title"><?= hx($title) ?></div>
    <p class="lb-para" style="font-size:13px;color:#6b7280;margin-top:-8px">
      Authors: <?= hx($allAuthors) ?>
    </p>

    <p class="lb-para">
      We are happy to confirm that your article has been reviewed and accepted. Below are the publication details:
    </p>

    <div class="lb-meta">
      <?php if($doi):?>
      <div class="lb-meta-row"><span class="lb-meta-key">DOI</span><span><?= hx($doi) ?></span></div>
      <?php endif;?>
      <?php if($vol):?>
      <div class="lb-meta-row"><span class="lb-meta-key">Volume / Issue</span><span><?= hx($vol) ?></span></div>
      <?php endif;?>
      <?php if($pg):?>
      <div class="lb-meta-row"><span class="lb-meta-key">Page Numbers</span><span><?= hx($pg) ?></span></div>
      <?php endif;?>
      <div class="lb-meta-row"><span class="lb-meta-key">Published On</span><span><?= hx($pubD) ?></span></div>
      <div class="lb-meta-row"><span class="lb-meta-key">Access Type</span><span>Open Access (CC BY 4.0)</span></div>
    </div>

    <p class="lb-para">
      The article is now available online and freely accessible to readers worldwide. You may access it at any time through our journal portal.
    </p>

    <p class="lb-para">
      On behalf of the editorial board, we congratulate you on this achievement and thank you for choosing <strong><?= hx($jName) ?></strong> for publishing your research.
    </p>

    <div class="lb-closing">
      <p>Yours sincerely,</p>
    </div>

    <div class="lb-sig">
      <div class="lb-sig-line"></div>
      <div class="lb-sig-name">Editorial Office</div>
      <div class="lb-sig-role"><?= hx($jName) ?></div>
      <div class="lb-sig-role" style="margin-top:3px">Communeglobal Publishing · editorialoffice@communeglobal.com</div>
    </div>
  </div>

  <div class="letter-footer">
    This is a system-generated letter. For queries, contact editorialoffice@communeglobal.com · communeglobal.com
  </div>
</div>
<script>
window.onload = function() {
  setTimeout(function() { window.print(); }, 600);
};
</script>
</body>
</html>