<?php
// payment.php — Final Step: Billing Details + Submit
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'];

// ── Shared layout identity ────────────────────────────────────
$pageTitle  = 'Billing & Submit';
$activePage = 'submission';

$sid = (int)($_GET['id'] ?? 0);
if (!$sid) { header('Location: submission.php'); exit; }

// Auto-create table
try {
    db()->exec("CREATE TABLE IF NOT EXISTS submission_payment (
        payment_id         INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        submission_id      INT UNSIGNED NOT NULL UNIQUE,
        billing_email      VARCHAR(200) NULL,
        phone_country_code VARCHAR(10)  DEFAULT '+91',
        phone_number       VARCHAR(30)  NULL,
        address            TEXT         NULL,
        city               VARCHAR(100) NULL,
        zip_code           VARCHAR(30)  NULL,
        country_region     VARCHAR(100) NULL,
        billing_reference  TEXT         NULL,
        fee_agreed         TINYINT(1)   DEFAULT 0,
        updated_at         DATETIME     DEFAULT NOW() ON UPDATE NOW()
    )");
} catch(PDOException $e) {}

try {
    db()->exec("ALTER TABLE submissions ADD COLUMN IF NOT EXISTS submission_status
        ENUM('draft','submitted','under_review','accepted','rejected') NOT NULL DEFAULT 'draft'");
} catch(PDOException $e) {}

// Load submission
$q = db()->prepare(
    "SELECT s.*, j.name AS journal_name,
            at.name AS article_type_name, at.preliminary_fee_chf,
            s.tracking_code, s.submitted_at
     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
     WHERE s.submission_id=? AND s.user_id=?"
);
$q->execute([$sid, $user_id]);
$sub = $q->fetch();
if (!$sub) { header('Location: submission.php'); exit; }

// Load saved payment
try {
    $q2 = db()->prepare("SELECT * FROM submission_payment WHERE submission_id=?");
    $q2->execute([$sid]);
    $pay = $q2->fetch(PDO::FETCH_ASSOC) ?: [];
} catch(PDOException $e) { $pay = []; }

// Corresponding author defaults
try {
    $q3 = db()->prepare(
        "SELECT sa.*, a.name AS affil_name
         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 LIMIT 1"
    );
    $q3->execute([$sid]);
    $corrAuthor = $q3->fetch(PDO::FETCH_ASSOC) ?: [];
} catch(PDOException $e) { $corrAuthor = []; }

$billingEmail = $pay['billing_email']      ?? $corrAuthor['email'] ?? '';
$phoneCode    = $pay['phone_country_code'] ?? '+91';
$phoneNum     = $pay['phone_number']       ?? '';
$address      = $pay['address']            ?? '';
$city         = $pay['city']               ?? '';
$zip          = $pay['zip_code']           ?? '';
$country      = $pay['country_region']     ?? '';
$billingRef   = $pay['billing_reference']  ?? '';
$feeAgreed    = (int)($pay['fee_agreed']   ?? 0);
$fee          = '35.00'; // Fixed fee USD
$subStatus    = $sub['submission_status'] ?? 'draft';
$trackingCode = $sub['tracking_code']     ?? '';
$submittedAt  = $sub['submitted_at']      ?? '';
$isSubmitted  = in_array($subStatus, ['submitted','under_review','accepted','rejected']);

$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','+20'=>'EG','+27'=>'ZA','+30'=>'GR','+31'=>'NL','+32'=>'BE','+33'=>'FR','+34'=>'ES','+36'=>'HU','+39'=>'IT','+40'=>'RO','+41'=>'CH','+43'=>'AT','+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','+94'=>'LK','+98'=>'IR','+212'=>'MA','+234'=>'NG','+254'=>'KE','+966'=>'SA','+971'=>'AE','+972'=>'IL'];

function p($v)    { return htmlspecialchars($v ?? ''); }
function sel($a,$b){ return $a === $b ? 'selected' : ''; }

require_once __DIR__ . '/_layout.php';
?>

<style>
/* ── page overrides ──────────────────────────────────────── */
.au-main { padding: 0 0 100px 0; }

:root {
  --teal: #1A7F8E; --teal-dk: #136070; --teal-lt: #E0F4F7;
  --primary: #E05A2B; --blue: #1B3F6E;
  --error: #D32F2F; --success: #2E7D32;
  --r: 3px;
}

.page-wrap { max-width: 980px; margin: 0 auto; padding: 20px 22px; }
.breadcrumb { display: flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--muted); margin-bottom: 16px; }
.breadcrumb a { color: var(--primary); text-decoration: none; font-weight: 500; }
.breadcrumb a:hover { text-decoration: underline; }

/* Tile */
.tile { background: var(--white); border-left: 5px solid var(--error); }
.tile-hdr { display: flex; align-items: center; justify-content: space-between; padding: 14px 22px; cursor: pointer; user-select: none; border-bottom: 1px solid #EBEBEB; }
.tile-hdr:hover { background: #FAFAFA; }
.tile-name   { font-size: 15px; font-weight: 700; }
.tile-status { font-size: 12.5px; font-weight: 600; margin-top: 2px; }
.tile-inner  { padding: 0 0 24px; }
.pay-wrap    { max-width: 740px; margin: 0 auto; padding: 26px 22px 0; }

/* Section */
.sec-title { font-size: 16px; font-weight: 700; margin-bottom: 6px; }
.sec-desc  { font-size: 13px; color: var(--muted); line-height: 1.7; margin-bottom: 18px; }

/* Form fields */
.fg { margin-bottom: 14px; }
.fl { font-size: 13px; font-weight: 600; margin-bottom: 5px; color: var(--text); display: block; }
.fl.req::after { content: ' *'; color: var(--error); font-size: 11px; }
.fi { width: 100%; padding: 8px 12px; border: 1.5px solid var(--border); border-radius: var(--r); font-family: var(--font); font-size: 13.5px; color: var(--text); outline: none; transition: border-color .15s; background: var(--white); }
.fi:focus { border-color: var(--teal); box-shadow: 0 0 0 3px rgba(26,127,142,.1); }
.fi.err { border-color: var(--error) !important; }
.fi::placeholder { color: #9CA3AF; }
.fi-ta { resize: vertical; min-height: 78px; line-height: 1.6; }
.grid3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; }
@media(max-width:640px) { .grid3 { grid-template-columns: 1fr 1fr; } }
.phone-row { display: grid; grid-template-columns: 130px 1fr; gap: 8px; }

/* Country dropdown */
.country-dd   { position: relative; }
.country-list { position: absolute; top: calc(100% + 2px); left: 0; right: 0; background: var(--white); border: 1.5px solid var(--teal); border-radius: var(--r); z-index: 100; box-shadow: 0 4px 16px rgba(0,0,0,.12); display: none; flex-direction: column; max-height: 220px; overflow: hidden; }
.country-list.open { display: flex; }
.country-search { padding: 7px 10px; border: none; border-bottom: 1px solid var(--border); font-family: var(--font); font-size: 13px; outline: none; width: 100%; }
.country-opts  { overflow-y: auto; max-height: 172px; }
.country-opt   { padding: 7px 12px; font-size: 13.5px; cursor: pointer; transition: background .1s; }
.country-opt:hover, .country-opt.active { background: var(--teal-lt); color: var(--teal); }
.country-opt.selected { font-weight: 600; color: var(--teal); }

.merr { display: none; align-items: center; gap: 6px; font-size: 13px; color: var(--error); margin: 2px 0 12px; font-weight: 500; }
.merr.show { display: flex; }

/* Fee table */
.fee-table { width: 100%; border: 1px solid var(--border); border-radius: 4px; overflow: hidden; margin-top: 10px; }
.fee-row { display: flex; justify-content: space-between; padding: 10px 16px; font-size: 13.5px; border-bottom: 1px solid var(--border); }
.fee-row:last-child { border-bottom: none; }
.fee-row.subtotal { background: #FAFAFA; }
.fee-row.total { background: var(--teal-lt); border-top: 2px solid var(--teal); }
.fee-row.total span:first-child { color: var(--teal); font-weight: 700; font-size: 14px; }
.fee-row.total span:last-child  { color: var(--teal); font-weight: 700; font-size: 14px; }
.fee-lbl { font-weight: 600; }

/* Agreement */
.agree-row { display: flex; align-items: flex-start; gap: 10px; margin-top: 16px; font-size: 13.5px; line-height: 1.6; cursor: pointer; }
.agree-row input[type=checkbox] { width: 15px; height: 15px; flex-shrink: 0; margin-top: 2px; accent-color: var(--teal); cursor: pointer; }
.agree-err { display: none; align-items: center; gap: 6px; font-size: 13px; color: var(--error); margin-top: 6px; font-weight: 500; }
.agree-err.show { display: flex; }

/* Submit confirmation box */
.submit-confirm { background: #F0FDF4; border: 1.5px solid #86EFAC; border-radius: 8px; padding: 20px 22px; margin-top: 20px; display: none; }
.submit-confirm.show { display: block; }
.submit-confirm h3 { font-size: 15px; font-weight: 700; color: #166534; margin-bottom: 8px; display: flex; align-items: center; gap: 7px; }
.submit-confirm p  { font-size: 13px; color: #166534; line-height: 1.7; margin-bottom: 14px; }

/* Already submitted */
.submitted-notice { background: #EFF6FF; border: 1.5px solid #BFDBFE; border-radius: 8px; padding: 18px 20px; margin-top: 20px; display: flex; align-items: flex-start; gap: 12px; }
.submitted-notice-icon { font-size: 22px; flex-shrink: 0; }
.submitted-notice h3 { font-size: 14px; font-weight: 700; color: #1E40AF; margin-bottom: 4px; }
.submitted-notice p  { font-size: 13px; color: #3B82F6; line-height: 1.6; }

/* Tile Nav */
.tile-nav { display: flex; align-items: center; justify-content: space-between; padding: 14px 22px; border-top: 1px solid #EBEBEB; background: var(--white); margin-top: 16px; }
.btn { display: inline-flex; align-items: center; gap: 5px; padding: 8px 22px; border-radius: var(--r); font-family: var(--font); font-size: 13px; font-weight: 600; cursor: pointer; border: none; transition: all .15s; text-decoration: none; }
.btn-outline { background: var(--white); border: 1.5px solid var(--teal); color: var(--teal); }
.btn-outline:hover { background: var(--teal-lt); }
.btn-fill { background: var(--teal); color: #fff; }
.btn-fill:hover { background: var(--teal-dk); }
.btn-submit-final { background: #059669; color: #fff; border: none; padding: 11px 30px; border-radius: var(--r); font-family: var(--font); font-size: 14px; font-weight: 700; cursor: pointer; transition: all .15s; display: inline-flex; align-items: center; gap: 7px; }
.btn-submit-final:hover { background: #047857; }
.btn-submit-final:disabled { opacity: .5; cursor: not-allowed; }
button.btn { font-family: var(--font); }

/* Bottom bar */
.bottom-bar { position: fixed; bottom: 0; left: var(--sidebar-w, 240px); right: 0; background: var(--white); border-top: 1px solid var(--border); padding: 10px 26px; display: flex; align-items: center; justify-content: space-between; z-index: 300; box-shadow: 0 -2px 6px rgba(0,0,0,.07); flex-wrap: wrap; gap: 10px; }
.btm-fee { font-size: 13px; color: var(--muted); }
.btm-fee strong { color: var(--text); font-weight: 700; }

hr.sd { border: none; border-top: 1px solid #EBEBEB; margin: 20px 0; }

/* Toast */
.toast-wrap { position: fixed; bottom: 70px; right: 18px; display: flex; flex-direction: column; gap: 7px; z-index: 9999; }
.toast { padding: 10px 15px; border-radius: var(--r); font-size: 13px; font-weight: 500; color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.18); display: flex; align-items: center; gap: 7px; animation: su .2s ease; }
.ts { background: #1D8A5E; } .te { background: var(--error); } .ti { background: var(--teal); }
@keyframes su { from{transform:translateY(10px);opacity:0} to{transform:translateY(0);opacity:1} }
.spin { display: inline-block; width: 12px; height: 12px; border: 2px solid rgba(255,255,255,.3); border-top-color: #fff; border-radius: 50%; animation: sp .6s linear infinite; }
@keyframes sp { to{transform:rotate(360deg)} }
</style>

<!-- ════ PAGE CONTENT ══════════════════════════════════════════ -->
<div class="page-wrap">

  <!-- Breadcrumb -->
  <div class="breadcrumb">
    <a href="dashboard.php">Overview</a>
    <span>›</span>
    <a href="submission.php?id=<?= $sid ?>">Submission Details</a>
    <span>›</span>
    <a href="statements.php?id=<?= $sid ?>">Statements</a>
    <span>›</span>
    <span>Billing &amp; Submit</span>
  </div>

  <div class="tile" id="payTile"
       style="border-left-color:<?= ($feeAgreed && $address && $city && $country) ? 'var(--success)' : 'var(--error)' ?>">

    <div class="tile-hdr" onclick="toggleTile()">
      <div>
        <div class="tile-name">Billing Details &amp; Submit</div>
        <div class="tile-status"
             style="color:<?= ($feeAgreed && $address && $city && $country) ? 'var(--success)' : 'var(--error)' ?>"
             id="tileStatus">
          <?= ($feeAgreed && $address && $city && $country)
              ? ($isSubmitted ? '✓ Submitted' : '✓ Complete — Ready to Submit')
              : '⊗ Incomplete' ?>
        </div>
      </div>
      <span style="font-size:16px;color:#888" id="tileChev">∧</span>
    </div>

    <div id="tileContent">
    <div class="tile-inner">
    <div class="pay-wrap">

      <?php if ($isSubmitted): ?>
      <div class="submitted-notice">
        <div class="submitted-notice-icon">✅</div>
        <div>
          <h3>Manuscript Submitted!</h3>
          <p>
            Your submission has been received and is currently
            <strong><?= ucfirst(str_replace('_',' ',$subStatus)) ?></strong>.
            Our editorial team will be in touch soon.
          </p>
          <?php if ($trackingCode): ?>
          <div style="margin-top:10px;background:#fff;border:1.5px solid #93C5FD;border-radius:6px;padding:10px 14px;display:inline-flex;align-items:center;gap:10px">
            <div>
              <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:#3B82F6;margin-bottom:2px">Tracking ID</div>
              <div style="font-size:18px;font-weight:800;color:#1E40AF;letter-spacing:1px;font-family:monospace"><?= p($trackingCode) ?></div>
              <div style="font-size:11px;color:#93C5FD;margin-top:2px">Use this ID to track your submission status</div>
            </div>
            <button type="button" onclick="copyCode('<?= p($trackingCode) ?>')"
                    style="background:#EFF6FF;border:1px solid #BFDBFE;border-radius:5px;padding:6px 12px;font-size:12px;font-weight:700;color:#1D4ED8;cursor:pointer">
              📋 Copy
            </button>
          </div>
          <?php endif; ?>
        </div>
      </div>
      <?php endif; ?>

      <!-- BILLING DETAILS -->
      <div class="sec-title" style="margin-top:<?= $isSubmitted?'20px':'0' ?>">Billing Details</div>
      <div class="sec-desc">
        Please fill in your billing information. These details will be used for the article processing charges (APCs)
        invoice if the manuscript is accepted for publication.
      </div>

      <div class="fg">
        <label class="fl req" for="billingEmail">Billing Email</label>
        <input type="email" class="fi" id="billingEmail" placeholder="billing@email.com"
               value="<?= p($billingEmail) ?>" oninput="dirty();clearErr(this)"
               <?= $isSubmitted?'readonly':'' ?>>
      </div>

      <div class="fg">
        <label class="fl req" for="phoneNum">Phone Number</label>
        <div class="phone-row">
          <select class="fi" id="phoneCode" onchange="dirty()" <?= $isSubmitted?'disabled':'' ?>>
            <option value="">Country</option>
            <?php foreach ($phoneCodes as $code => $label): ?>
            <option value="<?= $code ?>" <?= sel($phoneCode,$code) ?>><?= $code ?> <?= $label ?></option>
            <?php endforeach; ?>
          </select>
          <input type="tel" class="fi" id="phoneNum" placeholder="Phone number"
                 value="<?= p($phoneNum) ?>" oninput="dirty();clearErr(this)"
                 <?= $isSubmitted?'readonly':'' ?>>
        </div>
      </div>

      <div class="fg">
        <label class="fl req" for="address">Address</label>
        <textarea class="fi fi-ta" id="address" placeholder="Street address, building, floor..."
                  oninput="dirty();clearErr(this)" <?= $isSubmitted?'readonly':'' ?>><?= p($address) ?></textarea>
      </div>

      <div class="grid3">
        <div class="fg">
          <label class="fl req" for="city">City</label>
          <input type="text" class="fi" id="city" placeholder="City"
                 value="<?= p($city) ?>" oninput="dirty();clearErr(this)"
                 <?= $isSubmitted?'readonly':'' ?>>
        </div>
        <div class="fg">
          <label class="fl req" for="zip">Zip / Postal code</label>
          <input type="text" class="fi" id="zip" placeholder="Zip/Postal code"
                 value="<?= p($zip) ?>" oninput="dirty();clearErr(this)"
                 <?= $isSubmitted?'readonly':'' ?>>
        </div>
        <div class="fg">
          <label class="fl req" for="countryDisplay">Country / Region</label>
          <div class="country-dd" id="countryDd">
            <input type="text" class="fi" id="countryDisplay" placeholder="Select country"
                   value="<?= p($country) ?>" readonly
                   <?= $isSubmitted ? '' : 'onclick="toggleCountryList()"' ?>
                   style="<?= $isSubmitted ? 'cursor:default;background:#F9FAFB' : 'cursor:pointer' ?>">
            <input type="hidden" id="countryVal" value="<?= p($country) ?>">
            <?php if (!$isSubmitted): ?>
            <div class="country-list" id="countryList">
              <input type="text" class="country-search" id="countrySearch"
                     placeholder="Search country..." oninput="filterCountries(this.value)">
              <div class="country-opts" id="countryOpts"></div>
            </div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <div class="merr" id="mandatoryErr">&#x2297; Please fill all mandatory fields</div>

      <div class="fg">
        <label class="fl" for="billingRef">Billing reference <span style="font-weight:400;color:var(--muted);font-size:12px">(optional)</span></label>
        <textarea class="fi fi-ta" id="billingRef" placeholder="VAT number, purchase order, etc."
                  oninput="dirty()" <?= $isSubmitted?'readonly':'' ?>><?= p($billingRef) ?></textarea>
      </div>

      <hr class="sd">

      <!-- PRELIMINARY FEES -->
      <div class="sec-title" style="margin-bottom:4px">Preliminary Fees</div>
      <div class="sec-desc">Fees are charged only upon acceptance of the manuscript.</div>
      <div class="fee-table">
        <div class="fee-row">
          <span class="fee-lbl">Article Processing Fee</span>
          <span>USD $<?= $fee ?></span>
        </div>
        <div class="fee-row subtotal">
          <span class="fee-lbl">Sub total</span>
          <div style="text-align:right">
            <div>USD $<?= $fee ?></div>
            <div style="font-size:12px;color:var(--muted)">VAT 0.00% &nbsp; $0.00</div>
          </div>
        </div>
        <div class="fee-row total">
          <span>TOTAL DUE <span style="font-weight:400;font-size:12px">(after acceptance)</span></span>
          <span>USD $<?= $fee ?></span>
        </div>
      </div>

      <label class="agree-row">
        <input type="checkbox" id="feeAgree"
               <?= $feeAgreed?'checked':'' ?>
               <?= $isSubmitted?'disabled':'' ?>
               onchange="dirty();document.getElementById('agreeErr').classList.remove('show');checkReadyToSubmit()">
        <span>I and my fellow co-authors are fully aware of and agree with the payment of the listed
          article processing fee should the manuscript be accepted for publication.</span>
      </label>
      <div class="agree-err" id="agreeErr">&#x2297; Please mark this checkbox to continue</div>

      <?php if (!$isSubmitted): ?>
      <hr class="sd">
      <div class="sec-title">Submit Manuscript</div>
      <div class="sec-desc">
        Once you click "Submit Manuscript", your submission will be sent to our editorial team for review.
        Please ensure all sections are complete before submitting.
      </div>

      <div class="submit-confirm" id="submitConfirm">
        <h3>🟢 Ready to Submit</h3>
        <p>
          Your billing details are complete and you have agreed to the fee policy.<br>
          Click the button below to officially submit your manuscript.
        </p>
        <button type="button" class="btn-submit-final" id="submitFinalBtn" onclick="submitManuscript()">
          🚀 Submit Manuscript
        </button>
      </div>

      <div id="notReadyHint" style="display:none;margin-top:12px;padding:12px 16px;background:#FFFBEB;border:1px solid #FDE68A;border-radius:6px;font-size:13px;color:#92400E">
        ⚠️ Please fill all required billing fields and agree to the fee policy to enable submission.
      </div>
      <?php endif; ?>

      <!-- Author guidelines -->
      <div style="text-align:right;padding:8px 0 4px">
        <a href="https://communeglobal.com/journals/social-science/author-style-guidelines"
           target="_blank" rel="noopener" style="font-size:12.5px;color:var(--teal)">
          ℹ Author guidelines ↗
        </a>
      </div>

    </div><!-- /pay-wrap -->

    <div class="tile-nav">
      <a href="statements.php?id=<?= $sid ?>" class="btn btn-outline">← Previous</a>
      <?php if (!$isSubmitted): ?>
      <button type="button" class="btn btn-fill" id="saveBtn" onclick="doSave(false)">💾 Save</button>
      <?php else: ?>
      <a href="dashboard.php" class="btn btn-fill">Go to Dashboard →</a>
      <?php endif; ?>
    </div>

    </div>
    </div>
  </div><!-- /tile -->

</div><!-- /page-wrap -->

<!-- Bottom bar -->
<div class="bottom-bar">
  <div class="btm-fee">
    Preliminary fee: <strong>USD $<?= $fee ?></strong><br>
    <span style="font-size:11px">Payment after acceptance</span>
  </div>
  <div style="font-size:13px;font-weight:600;color:<?= $isSubmitted?'var(--success)':'var(--muted)' ?>">
    <?php if ($isSubmitted): ?>
    ✅ Manuscript <?= ucfirst(str_replace('_',' ',$subStatus)) ?>
    <?php else: ?>
    📝 Status: Draft
    <?php endif; ?>
  </div>
</div>

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

<script>
const SID = <?= $sid ?>;
const IS_SUBMITTED = <?= $isSubmitted ? 'true' : 'false' ?>;
let isDirty = false, autoTimer = null;
let countryListOpen = false;
const ALL_COUNTRIES = <?= json_encode($countries) ?>;

/* ── Tile toggle ────────────────────────────────────────── */
function toggleTile(){
    const c=document.getElementById('tileContent'); const o=c.style.display!=='none';
    c.style.display=o?'none':''; document.getElementById('tileChev').textContent=o?'∨':'∧';
}

function xe(s){ return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

/* ── Country dropdown ───────────────────────────────────── */
function renderCountryOpts(filter){
    const opts=document.getElementById('countryOpts'); if(!opts)return;
    const val=document.getElementById('countryVal').value;
    const f=(filter||'').trim().toLowerCase();
    const list=f?ALL_COUNTRIES.filter(c=>c.toLowerCase().includes(f)):ALL_COUNTRIES;
    opts.innerHTML=list.map(c=>`<div class="country-opt${c===val?' selected':''}" onclick="selectCountry('${xe(c)}')">${xe(c)}</div>`).join('');
}
function toggleCountryList(){
    if(IS_SUBMITTED)return;
    const list=document.getElementById('countryList'); countryListOpen=!countryListOpen;
    list.classList.toggle('open',countryListOpen);
    if(countryListOpen){
        document.getElementById('countrySearch').value=''; renderCountryOpts('');
        document.getElementById('countrySearch').focus();
        setTimeout(()=>{const sel=document.querySelector('.country-opt.selected');if(sel)sel.scrollIntoView({block:'nearest'});},50);
    }
}
function filterCountries(val){ renderCountryOpts(val); }
function selectCountry(name){
    document.getElementById('countryDisplay').value=name; document.getElementById('countryVal').value=name;
    document.getElementById('countryDisplay').classList.remove('err');
    document.getElementById('countryList').classList.remove('open'); countryListOpen=false;
    dirty(); checkReadyToSubmit();
}
document.addEventListener('click',e=>{
    const dd=document.getElementById('countryDd');
    if(countryListOpen&&dd&&!dd.contains(e.target)){
        document.getElementById('countryList')?.classList.remove('open'); countryListOpen=false;
    }
});

/* ── Check ready to submit ──────────────────────────────── */
function checkReadyToSubmit(){
    if(IS_SUBMITTED)return;
    const email  =document.getElementById('billingEmail').value.trim();
    const phone  =document.getElementById('phoneNum').value.trim();
    const addr   =document.getElementById('address').value.trim();
    const city   =document.getElementById('city').value.trim();
    const zip    =document.getElementById('zip').value.trim();
    const cntry  =document.getElementById('countryVal').value;
    const agreed =document.getElementById('feeAgree').checked;
    const ready  =email&&phone&&addr&&city&&zip&&cntry&&agreed;
    const confirmBox=document.getElementById('submitConfirm');
    const notReady  =document.getElementById('notReadyHint');
    if(confirmBox)confirmBox.classList.toggle('show',!!ready);
    if(notReady)notReady.style.display=ready?'none':'block';
}

/* ── Validate ───────────────────────────────────────────── */
function validate(){
    let ok=true, anyEmpty=false;
    ['billingEmail','phoneNum','address','city','zip'].forEach(id=>{
        const el=document.getElementById(id);
        if(!el||!el.value.trim()){if(el)el.classList.add('err');anyEmpty=true;ok=false;}
        else el.classList.remove('err');
    });
    if(!document.getElementById('countryVal').value){document.getElementById('countryDisplay').classList.add('err');anyEmpty=true;ok=false;}
    else document.getElementById('countryDisplay').classList.remove('err');
    if(!document.getElementById('feeAgree').checked){document.getElementById('agreeErr').classList.add('show');ok=false;}
    else document.getElementById('agreeErr').classList.remove('show');
    document.getElementById('mandatoryErr').classList.toggle('show',anyEmpty);
    return ok;
}
function clearErr(el){ el.classList.remove('err'); checkReadyToSubmit(); }

/* ── Collect ────────────────────────────────────────────── */
function collect(){
    return {
        billing_email:      document.getElementById('billingEmail').value.trim(),
        phone_country_code: document.getElementById('phoneCode').value,
        phone_number:       document.getElementById('phoneNum').value.trim(),
        address:            document.getElementById('address').value.trim(),
        city:               document.getElementById('city').value.trim(),
        zip_code:           document.getElementById('zip').value.trim(),
        country_region:     document.getElementById('countryVal').value,
        billing_reference:  document.getElementById('billingRef').value.trim(),
        fee_agreed:         document.getElementById('feeAgree').checked?1:0,
    };
}

/* ── Save ───────────────────────────────────────────────── */
function doSave(silent=false, callback=null){
    if(!silent&&!validate()) toast('Some required fields are missing. Saved as draft.','e');
    const btn=document.getElementById('saveBtn');
    if(!silent&&btn){btn.disabled=true;btn.innerHTML='<span class="spin"></span>';}
    const fd=new FormData(); fd.append('submission_id',SID); fd.append('data',JSON.stringify(collect()));
    fetch('ajax/save_payment.php',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(d=>{
        isDirty=false;
        if(!silent&&btn){btn.disabled=false;btn.innerHTML='💾 Save';}
        if(d.success){
            if(!silent)toast('Saved!','s');
            checkReadyToSubmit();
            if(callback)callback();
        } else if(!silent) toast(d.message||'Save failed','e');
    })
    .catch(()=>{
        if(!silent&&btn){btn.disabled=false;btn.innerHTML='💾 Save';}
        if(!silent)toast('Network error','e');
    });
}

/* ── Final Submit ───────────────────────────────────────── */
function submitManuscript(){
    if(!validate()){
        toast('Please fill all required billing fields and agree to the fee policy','e');
        document.querySelector('.fi.err,.merr.show,.agree-err.show')?.scrollIntoView({behavior:'smooth',block:'center'});
        return;
    }
    const btn=document.getElementById('submitFinalBtn');
    if(btn){btn.disabled=true;btn.innerHTML='<span class="spin"></span> Submitting...';}
    const fd=new FormData(); fd.append('submission_id',SID); fd.append('data',JSON.stringify(collect()));
    fetch('ajax/save_payment.php',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(d=>{
        if(!d.success){if(btn){btn.disabled=false;btn.innerHTML='🚀 Submit Manuscript';}toast('Failed to save billing details','e');return;}
        const fd2=new FormData(); fd2.append('submission_id',SID); fd2.append('status','submitted');
        return fetch('ajax/update_submission_status.php',{method:'POST',body:fd2});
    })
    .then(r=>r&&r.json())
    .then(d=>{
        if(d&&d.success){
            isDirty=false;
            const code=d.tracking_code||'';
            toast(code?`🎉 Submitted! Tracking ID: ${code}`:'🎉 Manuscript submitted successfully!','s');
            setTimeout(()=>location.reload(),2500);
        } else {if(btn){btn.disabled=false;btn.innerHTML='🚀 Submit Manuscript';}toast('Submission failed','e');}
    })
    .catch(()=>{if(btn){btn.disabled=false;btn.innerHTML='🚀 Submit Manuscript';}toast('Network error','e');});
}

/* ── Dirty / autosave ───────────────────────────────────── */
function dirty(){
    if(IS_SUBMITTED)return;
    isDirty=true; clearTimeout(autoTimer);
    autoTimer=setTimeout(()=>doSave(true),2000);
}

function toast(msg,t='i'){
    const w=document.getElementById('toastWrap'); const d=document.createElement('div');
    d.className='toast t'+t; d.innerHTML=(t==='s'?'✅':t==='e'?'❌':'ℹ️')+' '+xe(msg);
    w.appendChild(d); setTimeout(()=>d.remove(),3500);
}

function copyCode(code){
    navigator.clipboard.writeText(code).then(()=>toast('✅ Tracking ID copied: '+code,'s'))
    .catch(()=>{
        const el=document.createElement('textarea'); el.value=code;
        document.body.appendChild(el); el.select(); document.execCommand('copy');
        document.body.removeChild(el); toast('✅ Copied: '+code,'s');
    });
}

window.addEventListener('beforeunload',e=>{if(isDirty){e.preventDefault();e.returnValue='';}});

// Init
checkReadyToSubmit();
<?php if (!$isSubmitted): ?>
renderCountryOpts('');
<?php endif; ?>
</script>

<?php layoutEnd(); ?>