<?php
// ============================================================
// submit.php  —  Single-page accordion submission hub
// ============================================================
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set("display_errors", 0);
require_once __DIR__ . '/config/db.php';
startSession();

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

// ── 1. SUBMISSION ─────────────────────────────────────────────
try {
    $q = db()->prepare(
        "SELECT s.*, j.name AS journal_name, j.description AS journal_desc,
                j.cover_image_url,
                at.name AS article_type_name, at.preliminary_fee_chf,
                at.summary_length, at.figures_tables_limit,
                at.description AS at_desc,
                sp.name AS specialty_name, sp.description AS specialty_desc
         FROM submissions s
         LEFT JOIN journals j ON j.journal_id=s.journal_id
         LEFT JOIN article_types at ON at.article_type_id=s.article_type_id
         LEFT JOIN specialties sp ON sp.specialty_id=s.specialty_id
         WHERE s.submission_id=? AND s.user_id=?"
    );
    $q->execute([$sid, $user_id]);
    $sub = $q->fetch(PDO::FETCH_ASSOC) ?: [];
} catch(Exception $e){ $sub = []; }
$submission    = $sub;
$submission_id = $sid;
$score         = 0;

// ── 2. MANUSCRIPT ─────────────────────────────────────────────
try {
    $q = db()->prepare("SELECT * FROM manuscript_info WHERE submission_id=?");
    $q->execute([$sid]); $minfo = $q->fetch(PDO::FETCH_ASSOC) ?: [];
} catch(Exception $e){ $minfo = []; }
try {
    $q = db()->prepare("SELECT k.name FROM submission_keywords sk JOIN keywords k ON k.keyword_id=sk.keyword_id WHERE sk.submission_id=?");
    $q->execute([$sid]); $kwList = array_column($q->fetchAll(), 'name');
} catch(Exception $e){ $kwList = []; }
$titleFilled    = !empty($minfo['article_title']);
$abstractFilled = !empty($minfo['abstract']);
$kwCount        = count($kwList);
$kwValid        = ($kwCount >= 5 && $kwCount <= 8);

// ── 3. AUTHORS ────────────────────────────────────────────────
try {
    $q = db()->prepare(
        "SELECT sa.*, a.name AS affil_name, a.city AS affil_city, a.country AS affil_country
         FROM submission_authors sa
         LEFT JOIN affiliations a ON a.affiliation_id=sa.affiliation_id
         WHERE sa.submission_id=? ORDER BY sa.is_corresponding DESC, sa.author_order ASC"
    );
    $q->execute([$sid]); $authors = $q->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e){ $authors = []; }
$contributions = [];
if ($authors) {
    try {
        $ids  = implode(',', array_column($authors, 'author_id'));
        $rows = db()->query("SELECT * FROM author_contributions WHERE author_id IN ($ids)")->fetchAll();
        foreach ($rows as $r) $contributions[$r['author_id']] = $r;
    } catch(Exception $e){}
}
$corrAuthor = null;
foreach ($authors as $a) { if ($a['is_corresponding']) { $corrAuthor = $a; break; } }
if (!$corrAuthor && $authors) $corrAuthor = $authors[0];
$authorCount = count($authors);
$hasCorr     = (int)!!$corrAuthor;

// ── 4. EDITORIAL ──────────────────────────────────────────────
try {
    $q = db()->prepare("SELECT * FROM submission_editorial WHERE submission_id=?");
    $q->execute([$sid]); $editorial = $q->fetch(PDO::FETCH_ASSOC) ?: [];
} catch(Exception $e){ $editorial = []; }
try {
    $q = db()->prepare("SELECT * FROM suggested_reviewers WHERE submission_id=? ORDER BY reviewer_type,created_at ASC");
    $q->execute([$sid]); $reviewers = $q->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e){ $reviewers = []; }
try {
    $q = db()->query("SELECT * FROM editors WHERE is_active=1 ORDER BY is_editorial_board DESC,name ASC");
    $editorsList = $q->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e){ $editorsList = []; }

// ── 5. STATEMENTS ─────────────────────────────────────────────
try {
    $q = db()->prepare("SELECT * FROM submission_statements WHERE submission_id=?");
    $q->execute([$sid]); $ss = $q->fetch(PDO::FETCH_ASSOC) ?: [];
} catch(Exception $e){ $ss = []; }
$funders = json_decode($ss['funder_data'] ?? '[]', true) ?: [];

// ── 6. PAYMENT ────────────────────────────────────────────────
try {
    $q = db()->prepare("SELECT * FROM submission_payment WHERE submission_id=?");
    $q->execute([$sid]); $pay = $q->fetch(PDO::FETCH_ASSOC) ?: [];
} catch(Exception $e){ $pay = []; }
$discountCodes   = json_decode($pay['discount_codes'] ?? '[]', true) ?: [];
$invoiceType     = $pay['invoice_type']         ?? 'author';
$invoiceAuthorId = (int)($pay['invoice_author_id'] ?? $corrAuthor['author_id'] ?? 0);
$payAffil        = $pay['affiliation']           ?? $corrAuthor['affil_name'] ?? '';
$billingEmail    = $pay['billing_email']         ?? $corrAuthor['email']      ?? '';
$phoneCode       = $pay['phone_country_code']    ?? '+91';
$phoneNum        = $pay['phone_number']          ?? '';
$payAddress      = $pay['address']               ?? '';
$payCity         = $pay['city']                  ?? '';
$payZip          = $pay['zip_code']              ?? '';
$payCountry      = $pay['country_region']        ?? '';
$billingRef      = $pay['billing_reference']     ?? '';
$payerType       = $pay['payer_type']            ?? 'individual_' . ($corrAuthor['author_id'] ?? '');
$feeAgreed       = (int)($pay['fee_agreed']      ?? 0);
$otherFirst      = $pay['other_first_name']      ?? '';
$otherMiddle     = $pay['other_middle_name']     ?? '';
$otherLast       = $pay['other_last_name']       ?? '';
$otherTitle      = $pay['other_title']           ?? '';
$otherEmail      = $pay['other_email']           ?? '';

$countries = ['Afghanistan','Albania','Algeria','Andorra','Angola','Argentina','Armenia','Australia','Austria','Azerbaijan','Bahrain','Bangladesh','Belarus','Belgium','Belize','Bolivia','Bosnia and Herzegovina','Brazil','Bulgaria','Cambodia','Cameroon','Canada','Chile','China','Colombia','Costa Rica','Croatia','Cuba','Cyprus','Czech Republic','Denmark','Ecuador','Egypt','Estonia','Ethiopia','Finland','France','Georgia','Germany','Ghana','Greece','Guatemala','Hungary','India','Indonesia','Iran','Iraq','Ireland','Israel','Italy','Jamaica','Japan','Jordan','Kazakhstan','Kenya','Kuwait','Latvia','Lebanon','Lithuania','Luxembourg','Malaysia','Mexico','Mongolia','Morocco','Nepal','Netherlands','New Zealand','Nigeria','Norway','Oman','Pakistan','Palestine','Panama','Peru','Philippines','Poland','Portugal','Qatar','Romania','Russia','Rwanda','Saudi Arabia','Senegal','Serbia','Singapore','Slovakia','Slovenia','South Africa','South Korea','Spain','Sri Lanka','Sudan','Sweden','Switzerland','Syria','Taiwan','Thailand','Tunisia','Turkey','Uganda','Ukraine','United Arab Emirates','United Kingdom','United States','Uruguay','Uzbekistan','Venezuela','Vietnam','Yemen','Zambia','Zimbabwe'];
$phoneCodes = ['+1'=>'US','+7'=>'RU','+31'=>'NL','+32'=>'BE','+33'=>'FR','+34'=>'ES','+39'=>'IT','+40'=>'RO','+41'=>'CH','+44'=>'UK','+45'=>'DK','+46'=>'SE','+47'=>'NO','+48'=>'PL','+49'=>'DE','+52'=>'MX','+55'=>'BR','+60'=>'MY','+61'=>'AU','+62'=>'ID','+65'=>'SG','+81'=>'JP','+82'=>'KR','+86'=>'CN','+90'=>'TR','+91'=>'IN','+92'=>'PK','+966'=>'SA','+971'=>'AE','+972'=>'IL'];
$fee    = number_format((float)($sub['preliminary_fee_chf'] ?? 0), 2);
$feeRaw = (float)($sub['preliminary_fee_chf'] ?? 0);

// ── SECTION STATUS ────────────────────────────────────────────
$secDone = [
    'details'    => !empty($sub['journal_id'])          && !empty($sub['article_type_id']),
    'manuscript' => !empty($minfo['article_title'])     && !empty($minfo['abstract']),
    'authors'    => $hasCorr > 0,
    'editorial'  => !empty($editorial['cover_letter']),
    'statements' => !empty($ss['conflict_of_interest']) && !empty($ss['data_availability_statement']),
    'payment'    => !empty($pay['address'])             && !empty($pay['country_region']) && !empty($pay['fee_agreed']),
];
$doneCount = count(array_filter($secDone));
$quality   = round($doneCount / 6 * 100);

// ── HELPERS ──────────────────────────────────────────────────
function sv($a, $k, $d = '') { return $a[$k] ?? $d; }
function ck($a, $k, $v)      { return (($a[$k] ?? '') === $v) ? 'checked' : ''; }
function p($v)                { return htmlspecialchars($v ?? ''); }
function sel($a, $b)          { return $a === $b ? 'selected' : ''; }
function hsc($v)              { return htmlspecialchars($v ?? ''); }

// ── PARTIAL FILE MAP ──────────────────────────────────────────
// section-id  =>  actual filename inside /partials/
$partialMap = [
    'details'    => 'submission.php',   // ← "details" section uses submission.php
    'manuscript' => 'manuscript.php',
    'authors'    => 'authors.php',
    'editorial'  => 'editorial.php',
    'statements' => 'statements.php',
    'payment'    => 'payment.php',
];

// ── CSS source files (same mapping) ──────────────────────────
$cssSourceFiles = [
    'submission',
    'manuscript',
    'authors',
    'editorial',
    'statements',
    'payment',
];

// ── Safe partial include ──────────────────────────────────────
function safeInclude($file) {
    if (!file_exists($file)) {
        echo '<div style="padding:20px;color:#aaa;font-size:13px;font-style:italic;">
                Content not available yet.
              </div>';
        return;
    }
    try {
        ob_start();
        include $file;
        echo ob_get_clean();
    } catch(Throwable $e) {
        ob_end_clean();
        echo '<div style="padding:20px;color:#c00;font-size:13px;">
                Error: ' . htmlspecialchars($e->getMessage()) . '
              </div>';
    }
}

// ── Collect CSS from source files ────────────────────────────
$sectionCss = [];
foreach ($cssSourceFiles as $sf) {
    $path = __DIR__ . "/partials/$sf.php";
    if (!file_exists($path)) continue;
    $content = file_get_contents($path);
    preg_match('/<style[^>]*>(.*?)<\/style>/s', $content, $m);
    if (!empty($m[1])) {
        $css = preg_replace('/<style[^>]*>|<\/style>/', '', $m[1]);
        $css = preg_replace('/\/\* When embedded.*?\*\//s', '', $css);
        $sectionCss[$sf] = trim($css);
    }
}

// ── Sections metadata ─────────────────────────────────────────
$sectionsMeta = [
  ['id'=>'details',    'label'=>'Submission details',       'done'=>$secDone['details'],    'info'=>false],
  ['id'=>'manuscript', 'label'=>'Manuscript information',   'done'=>$secDone['manuscript'], 'info'=>false],
  ['id'=>'authors',    'label'=>'Authors and contributors', 'done'=>$secDone['authors'],    'info'=>true],
  ['id'=>'editorial',  'label'=>'Editorial',                'done'=>$secDone['editorial'],  'info'=>false],
  ['id'=>'statements', 'label'=>'Statements',               'done'=>$secDone['statements'], 'info'=>false],
  ['id'=>'payment',    'label'=>'Payment',                  'done'=>$secDone['payment'],    'info'=>false],
];

// First incomplete opens by default
$firstOpen = 'details';
foreach ($sectionsMeta as $s) { if (!$s['done']) { $firstOpen = $s['id']; break; } }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Submit Manuscript — CIJSS</title>

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap" rel="stylesheet">

<style>
:root {
  --red:    #C0392B;
  --green:  #27AE60;
  --teal:   #1A7F8E;
  --teal-dk:#136070;
  --teal-lt:#E0F4F7;
  --primary:#E05A2B;
  --blue:   #1B3F6E;
  --text:   #2C2C2C;
  --muted:  #888;
  --border: #E0E0E0;
  --bg:     #F5F5F5;
  --white:  #FFFFFF;
  --font:   'Open Sans', sans-serif;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: var(--font); background: var(--bg); color: var(--text); font-size: 14px; line-height: 1.5; padding-bottom: 80px; }
a { color: var(--teal); text-decoration: none; }
button, input, select, textarea { font-family: var(--font); }

/* TOPBAR */
.topbar { background: var(--white); border-bottom: 3px solid var(--primary); height: 56px; display: flex; align-items: center; justify-content: space-between; padding: 0 32px; position: sticky; top: 0; z-index: 999; box-shadow: 0 1px 6px rgba(0,0,0,.08); }
.logo-text { font-size: 22px; font-weight: 700; color: var(--primary); letter-spacing: -0.5px; }
.logo-text span { color: var(--blue); }
.topbar-nav { display: flex; gap: 32px; }
.topbar-nav a { font-size: 11.5px; text-transform: uppercase; font-weight: 700; color: var(--text); letter-spacing: 0.6px; }
.topbar-nav a:hover { color: var(--primary); }
.topbar-right { display: flex; align-items: center; gap: 10px; font-size: 12px; font-weight: 700; color: var(--muted); text-transform: uppercase; }
.avatar { width: 32px; height: 32px; border-radius: 50%; background: #E5E7EB; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; color: #555; }

/* PAGE WRAP */
.page-wrap { max-width: 1160px; margin: 0 auto; }

/* ACCORDION ITEM */
.acc-item { background: var(--white); border-left: 6px solid var(--red); border-bottom: 1px solid var(--border); transition: border-left-color .2s; }
.acc-item.done { border-left-color: var(--green); }

/* HEADER BUTTON */
.acc-header { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 18px 24px 18px 20px; background: var(--white); border: none; cursor: pointer; text-align: left; gap: 12px; -webkit-appearance: none; appearance: none; }
.acc-header:focus { outline: none; }
.acc-header:hover { background: #FAFAFA; }

.acc-title-wrap { flex: 1; display: flex; flex-direction: column; gap: 5px; }
.acc-title { font-size: 15px; font-weight: 700; color: var(--text); display: flex; align-items: center; gap: 6px; }

.acc-status { display: flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 600; }
.acc-status.inc { color: var(--red); }
.acc-status.cmp { color: var(--green); }
.status-icon { display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; border-radius: 50%; font-size: 11px; font-weight: 700; flex-shrink: 0; line-height: 1; }
.inc .status-icon { background: var(--red); color: #fff; }
.cmp .status-icon { background: var(--green); color: #fff; }

/* CHEVRON */
.acc-chevron { flex-shrink: 0; width: 22px; height: 22px; color: #999; transition: transform .25s ease; }
.acc-item.open .acc-chevron { transform: rotate(180deg); }

/* PANEL — max-height animation, no JS needed for animation */
.acc-panel { max-height: 0; overflow: hidden; transition: max-height 0.4s ease; background: #FAFAFA; }
.acc-item.open .acc-panel { max-height: 9999px; border-top: 1px solid #EEEEEE; }
.acc-panel-inner { background: var(--white); }

/* INFO BADGE */
.iico { display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; border-radius: 50%; background: #D6EAF8; color: #2874A6; font-size: 10px; font-weight: 700; cursor: default; flex-shrink: 0; }

/* BOTTOM BAR */
.btmbar { position: fixed; bottom: 0; left: 0; right: 0; background: var(--white); border-top: 1px solid #DDD; height: 68px; padding: 0 32px; display: flex; align-items: center; justify-content: space-between; z-index: 998; box-shadow: 0 -2px 10px rgba(0,0,0,.07); }
.btm-fee { line-height: 1.4; }
.btm-fee strong { font-size: 15px; font-weight: 700; color: var(--text); }
.btm-fee span { font-size: 12px; color: var(--muted); }
.btm-quality { font-size: 13px; color: var(--text); }
.btm-quality strong { font-size: 15px; }
.btm-quality small { display: block; font-size: 11px; color: var(--muted); margin-top: 2px; }
.btm-actions { display: flex; gap: 10px; }
.btn-preview { background: var(--white); border: 1.5px solid #CCC; color: var(--text); padding: 8px 22px; border-radius: 4px; font-size: 13px; font-weight: 600; cursor: pointer; }
.btn-preview:hover { border-color: #999; }
.btn-submit { background: var(--teal); color: #fff; border: none; padding: 8px 22px; border-radius: 4px; font-size: 13px; font-weight: 700; cursor: pointer; display: flex; align-items: center; gap: 7px; }
.btn-submit:hover:not(:disabled) { background: var(--teal-dk); }
.btn-submit:disabled { opacity: .45; cursor: not-allowed; }
.btn-submit svg { width: 15px; height: 15px; fill: currentColor; }

/* TOAST */
.toast-wrap { position: fixed; bottom: 78px; right: 18px; display: flex; flex-direction: column; gap: 8px; z-index: 9999; pointer-events: none; }
.toast-item { padding: 10px 16px; border-radius: 5px; font-size: 13px; font-weight: 500; color: #fff; box-shadow: 0 4px 16px rgba(0,0,0,.18); display: flex; align-items: center; gap: 8px; animation: tfin .2s ease; pointer-events: auto; }
.toast-s { background: #1D8A5E; } .toast-e { background: var(--red); } .toast-i { background: var(--teal); }
@keyframes tfin { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)} }
</style>

<!-- Section CSS -->
<?php foreach ($sectionCss as $sf => $css): ?>
<style id="css-<?= $sf ?>">/* === <?= $sf ?> === */
<?= $css ?>
</style>
<?php endforeach; ?>

<!-- ════ ACCORDION JS — in <head> so it loads before any click ════ -->
<script>
function accToggle(secId) {
  var all = document.querySelectorAll('.acc-item');
  for (var i = 0; i < all.length; i++) {
    if (all[i].id === 'item_' + secId) {
      all[i].classList.toggle('open');
    } else {
      all[i].classList.remove('open');
    }
  }
}

function accOpen(secId) {
  var all = document.querySelectorAll('.acc-item');
  for (var i = 0; i < all.length; i++) {
    all[i].classList.toggle('open', all[i].id === 'item_' + secId);
  }
}

function showToast(msg, t) {
  t = t || 'i';
  var w = document.getElementById('toastWrap');
  if (!w) return;
  var d = document.createElement('div');
  d.className = 'toast-item toast-' + t;
  var icons = { s:'✅', e:'❌', i:'ℹ️' };
  d.innerHTML = (icons[t]||'') + ' ' + String(msg).replace(/</g,'&lt;');
  w.appendChild(d);
  setTimeout(function(){ if(d.parentNode) d.parentNode.removeChild(d); }, 3500);
}
window.toast = showToast;

function markDone(secId, done) {
  var item = document.getElementById('item_' + secId);
  var st   = document.getElementById('accst_' + secId);
  if (item) item.classList.toggle('done', !!done);
  if (st) {
    st.className = 'acc-status ' + (done ? 'cmp' : 'inc');
    st.innerHTML = '<span class="status-icon">' + (done?'✓':'✕') + '</span> ' + (done?'Complete':'Incomplete');
  }
  var total = document.querySelectorAll('.acc-item.done').length;
  var qEl   = document.getElementById('qRemain');
  var sbEl  = document.getElementById('submitBtn');
  if (qEl)  qEl.textContent = (6 - total) + ' section(s) remaining';
  if (sbEl) sbEl.disabled   = total < 6;
}

function openNextSection(currentId) {
  var order = ['details','manuscript','authors','editorial','statements','payment'];
  var idx = order.indexOf(currentId);
  for (var i = idx + 1; i < order.length; i++) {
    var item = document.getElementById('item_' + order[i]);
    if (item && !item.classList.contains('done')) {
      accOpen(order[i]);
      setTimeout(function(){ item.scrollIntoView({behavior:'smooth',block:'start'}); }, 50);
      return;
    }
  }
}
</script>
</head>
<body>

<!-- TOPBAR -->
<header class="topbar">
  <div class="logo-text">CIJSS</div>
  <nav class="topbar-nav">
    <a href="#">About</a>
    <a href="#">Journals</a>
    <a href="#">Research Topics</a>
    <a href="#">Articles</a>
  </nav>
  <div class="topbar-right">
    MY CIJSS
    <div class="avatar"><?= strtoupper(substr($user['first_name'] ?? 'U', 0, 1)) ?></div>
  </div>
</header>

<!-- ACCORDION -->
<div class="page-wrap">
<div id="mainAccordion">

<?php foreach ($sectionsMeta as $sec):
  $isOpen  = ($sec['id'] === $firstOpen);
  $isDone  = $sec['done'];
  $partial = __DIR__ . '/partials/' . ($partialMap[$sec['id']] ?? $sec['id'] . '.php');
?>

<div class="acc-item <?= $isDone ? 'done' : '' ?> <?= $isOpen ? 'open' : '' ?>"
     id="item_<?= $sec['id'] ?>">

  <button type="button"
          class="acc-header"
          onclick="accToggle('<?= $sec['id'] ?>')">
    <div class="acc-title-wrap">
      <div class="acc-title">
        <?= p($sec['label']) ?>
        <?php if ($sec['info']): ?>
          <span class="iico" title="More info">i</span>
        <?php endif; ?>
      </div>
      <div class="acc-status <?= $isDone ? 'cmp' : 'inc' ?>"
           id="accst_<?= $sec['id'] ?>">
        <span class="status-icon"><?= $isDone ? '✓' : '✕' ?></span>
        <?= $isDone ? 'Complete' : 'Incomplete' ?>
      </div>
    </div>
    <svg class="acc-chevron" viewBox="0 0 24 24" fill="none"
         stroke="currentColor" stroke-width="2.5"
         stroke-linecap="round" stroke-linejoin="round">
      <polyline points="6 9 12 15 18 9"></polyline>
    </svg>
  </button>

  <div class="acc-panel" id="panel_<?= $sec['id'] ?>">
    <div class="acc-panel-inner" id="sw_<?= $sec['id'] ?>">
      <?php safeInclude($partial); ?>
    </div>
  </div>

</div>
<?php endforeach; ?>

</div><!-- /#mainAccordion -->
</div><!-- /.page-wrap -->


<!-- BOTTOM BAR -->
<div class="btmbar">
  <div class="btm-fee">
    <strong><?= $fee ?> CHF</strong><br>
    <span>Preliminary fees &bull; Payment after acceptance</span>
  </div>
  <div class="btm-quality">
    <strong>Submission quality: <?= $quality ?>%</strong>
    <small id="qRemain"><?= 6 - $doneCount ?> section(s) remaining</small>
  </div>
  <div class="btm-actions">
    <button class="btn-preview" onclick="window.print()">Preview</button>
    <button class="btn-submit" id="submitBtn" <?= $doneCount < 6 ? 'disabled' : '' ?>>
      <svg viewBox="0 0 24 24"><path d="M22 2L11 13M22 2L15 22 11 13 2 9l20-7z"/></svg>
      Submit
    </button>
  </div>
</div>

<div class="toast-wrap" id="toastWrap"></div>

<script>
var SID           = <?= (int)$sid ?>;
var ALL_COUNTRIES = <?= json_encode($countries) ?>;
</script>

<?php
// ── Per-section JS from partials ─────────────────────────────
$nsMap = [
  'submission' => 'SUB',
  'manuscript' => 'MAN',
  'authors'    => 'AUT',
  'editorial'  => 'EDT',
  'statements' => 'STM',
  'payment'    => 'PAY',
];
foreach ($cssSourceFiles as $sf):
    $path = __DIR__ . "/partials/$sf.php";
    if (!file_exists($path)) continue;
    $content = file_get_contents($path);
    preg_match_all('/<script(?!\s+src)[^>]*>(.*?)<\/script>/s', $content, $m);
    $jsBlocks = array_filter(
        $m[1],
        fn($b) => strlen(trim($b)) > 200
               && strpos($b, 'embed-js')          === false
               && strpos($b, 'Detect if running') === false
    );
    if (!$jsBlocks) continue;
    $js = implode("\n\n", $jsBlocks);
    $ns = $nsMap[$sf] ?? strtoupper($sf);
?>
<script>
/* ════ <?= strtoupper($sf) ?> ════ */
(function () {
  'use strict';
  var _SECID = '<?= $sf === 'submission' ? 'details' : $sf ?>';
  try {
    <?= $js ?>
  } catch (err) {
    console.error('[<?= strtoupper($sf) ?>] JS error:', err);
  }
  window['NS_<?= $ns ?>'] = { _section: _SECID };
})();
</script>
<?php endforeach; ?>

</body>
</html>