<?php
// projects.php — My current projects
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
startSession();
$user    = getCurrentUser();
$user_id = $user['user_id'];

$pageTitle  = 'My Projects';
$activePage = 'projects';

try {
    $q = db()->prepare(
        "SELECT s.submission_id, s.created_at, s.updated_at,
                COALESCE(s.submission_status,'draft') AS submission_status,
                s.tracking_code,
                j.name AS journal_name, sp.name AS specialty_name,
                at.name AS article_type_name,
                mi.article_title,
                ed.decision        AS latest_decision,
                ed.created_at      AS decision_date,
                ed.due_date        AS revision_due,
                ed.id              AS decision_id
         FROM submissions s
         LEFT JOIN journals j        ON j.journal_id        = s.journal_id
         LEFT JOIN specialties sp    ON sp.specialty_id     = s.specialty_id
         LEFT JOIN article_types at  ON at.article_type_id  = s.article_type_id
         LEFT JOIN manuscript_info mi ON mi.submission_id   = s.submission_id
         LEFT JOIN editorial_decisions ed
               ON ed.id = (
                   SELECT id FROM editorial_decisions
                   WHERE submission_id = s.submission_id
                   ORDER BY created_at DESC LIMIT 1
               )
         WHERE s.user_id = ?
         ORDER BY s.updated_at DESC"
    );
    $q->execute([$user_id]);
    $submissions = $q->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e){ $submissions = []; }

$finalFiles = [];
try {
    $fq = db()->prepare(
        "SELECT submission_id, file_type, stored_path, original_name
         FROM submission_files
         WHERE submission_id IN (
             SELECT submission_id FROM submissions WHERE user_id = ?
         )
         AND file_type IN ('payment_receipt','declaration_form','final_manuscript_revised','resubmission')"
    );
    $fq->execute([$user_id]);
    foreach ($fq->fetchAll(PDO::FETCH_ASSOC) as $f) {
        $finalFiles[$f['submission_id']][$f['file_type']] = $f;
    }
} catch(PDOException $e){ $finalFiles = []; }

// Fetch completed gateway payments per submission
$gatewayPaid = [];
try {
    $gq = db()->prepare(
        "SELECT submission_id FROM payments
         WHERE submission_id IN (SELECT submission_id FROM submissions WHERE user_id = ?)
         AND status = 'COMPLETED'"
    );
    $gq->execute([$user_id]);
    foreach ($gq->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $gatewayPaid[$row['submission_id']] = true;
    }
} catch(PDOException $e){ $gatewayPaid = []; }

$total           = count($submissions);
$cntDraft        = count(array_filter($submissions, fn($s) => ($s['submission_status']??'draft') === 'draft'));
$cntSubmitted    = count(array_filter($submissions, fn($s) => in_array($s['submission_status']??'draft', ['submitted','under_review'])));
$cntEditorReview = count(array_filter($submissions, fn($s) => in_array($s['submission_status']??'draft', ['accepted','rejected']) || !empty($s['latest_decision'])));
$filterTab       = $_GET['filter'] ?? 'all';

$filtered = $submissions;
if ($filterTab === 'draft')
    $filtered = array_values(array_filter($submissions, fn($s) => ($s['submission_status']??'draft') === 'draft'));
if ($filterTab === 'submitted')
    $filtered = array_values(array_filter($submissions, fn($s) => in_array($s['submission_status']??'draft', ['submitted','under_review'])));
if ($filterTab === 'editor_review')
    $filtered = array_values(array_filter($submissions, fn($s) => in_array($s['submission_status']??'draft', ['accepted','rejected']) || !empty($s['latest_decision'])));

$fullName = trim(($user['first_name']??'').' '.($user['last_name']??''));

function p($v){ return htmlspecialchars($v??''); }

function decisionLabel($d) {
    $map = [
        'accepted'              => ['✓ Accepted',              '#0d7a4f', '#dcfce7'],
        'accepted_with_changes' => ['✓ Accepted with Changes', '#b45309', '#fef3c7'],
        'resubmit'              => ['↻ Resubmit Required',     '#6d28d9', '#ede9fe'],
        'rejected'              => ['✗ Rejected',              '#be123c', '#fee2e2'],
    ];
    return $map[$d] ?? ['Under Review', '#1d4ed8', '#eff6ff'];
}

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

<style>
/* ═══════════════════════════════════════════════════════════ */
/* projects.php                                                */
/* ═══════════════════════════════════════════════════════════ */

/* ── Page header ── */
.page-hdr {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 22px; gap: 12px; flex-wrap: wrap;
}
.page-title { font-size: 22px; font-weight: 700; color: var(--text); }
.btn-new {
  display: inline-flex; align-items: center; gap: 6px; padding: 9px 20px;
  background: var(--teal); color: #fff; border-radius: 6px; font-size: 13.5px;
  font-weight: 700; cursor: pointer; border: none; font-family: var(--font);
  transition: all .15s; text-decoration: none; white-space: nowrap;
}
.btn-new:hover { background: var(--teal-dk); color: #fff; }

/* ── Filter tabs ── */
.filter-tabs {
  display: flex; gap: 0;
  border-bottom: 2px solid var(--border);
  margin-bottom: 24px;
  overflow-x: auto;          /* scroll on narrow screens */
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;     /* hide scrollbar on Firefox */
}
.filter-tabs::-webkit-scrollbar { display: none; }

.filter-tab {
  padding: 8px 16px; font-size: 13.5px; font-weight: 600;
  text-decoration: none; border-bottom: 2.5px solid transparent;
  margin-bottom: -2px; transition: all .15s;
  color: var(--muted); display: inline-flex; align-items: center; gap: 0;
  white-space: nowrap; flex-shrink: 0;
}
.filter-tab.active { border-bottom-color: var(--teal); color: var(--teal); }
.filter-tab:hover:not(.active) { color: var(--text); }
.tab-count {
  font-size: 11px; font-weight: 700; padding: 1px 7px;
  border-radius: 10px; margin-left: 5px;
}

/* ── Cards grid ── */
.sub-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}
@media (max-width: 1100px) { .sub-cards { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 700px)  { .sub-cards { grid-template-columns: 1fr; } }

/* ── Individual card ── */
.sub-card {
  border: 1.5px solid var(--border); border-radius: 10px;
  padding: 16px; background: var(--white);
  display: flex; flex-direction: column; gap: 0;
  transition: all .18s; cursor: pointer; position: relative;
}
.sub-card:hover { border-color: #CBD5E1; box-shadow: 0 3px 14px rgba(0,0,0,.08); }
.sub-card.is-submitted { border-color: #BFDBFE; background: #FAFEFF; }
.sub-card.is-reviewed  { border-color: #C4B5FD; background: #FDFAFF; }
.sub-card.is-reviewed:hover { border-color: #A78BFA; }
.sub-card.is-accepted  { border-color: #86EFAC; background: #F0FDF4; }
.sub-card.is-accepted:hover { border-color: #4ADE80; }
.sub-card.is-resubmit  { border-color: #FCA5A5; background: #FFF5F5; }

.sub-card-del {
  position: absolute; top: 10px; right: 10px;
  background: none; border: none; cursor: pointer;
  color: #CBD5E1; padding: 3px; opacity: 0; transition: opacity .15s;
}
/* always visible on touch — can't hover on mobile */
@media (hover: none) { .sub-card-del { opacity: 1; } }
.sub-card:hover .sub-card-del { opacity: 1; }
.sub-card-del:hover { color: #EF4444; }

.sub-card-journal  { font-size: 11.5px; color: var(--muted); margin-bottom: 4px; line-height: 1.4; }
.sub-card-title    { font-size: 13.5px; font-weight: 700; margin-bottom: 6px; line-height: 1.4; color: var(--text); }

.card-decision-badge {
  display: inline-flex; align-items: center; gap: 5px;
  font-size: 11.5px; font-weight: 700;
  padding: 4px 10px; border-radius: 20px;
  margin: 8px 0 4px; width: fit-content;
}

.revision-due {
  font-size: 11px; font-weight: 600;
  color: #b45309; background: #fef3c7;
  border-radius: 4px; padding: 2px 8px;
  display: inline-flex; align-items: center; gap: 4px;
  margin-bottom: 8px; width: fit-content;
}
.revision-due.overdue { color: #be123c; background: #fee2e2; }

.card-actions {
  border-top: 1px solid var(--border); padding-top: 12px; margin-top: 12px;
  display: flex; flex-direction: column; gap: 8px;
}
.action-section-label {
  font-size: 10.5px; font-weight: 700; text-transform: uppercase;
  letter-spacing: .6px; color: var(--muted); margin-bottom: 2px;
}

.card-btn {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 8px 14px; border-radius: 6px;
  font-size: 13px; font-weight: 700;
  cursor: pointer; border: none; font-family: var(--font);
  text-decoration: none; transition: all .15s; width: 100%;
  justify-content: center; text-align: center;
  /* bigger tap target on mobile */
  min-height: 42px;
}
.card-btn:hover { filter: brightness(.93); }
.card-btn-primary  { background: #0d7a4f; color: #fff; }
.card-btn-payment  { background: #1d4ed8; color: #fff; }
.card-btn-warning  { background: #f59e0b; color: #fff; }
.card-btn-purple   { background: #6d28d9; color: #fff; }
.card-btn-bank     { background: #0f766e; color: #fff; }
.card-btn-outline  {
  background: transparent; color: var(--teal);
  border: 1.5px solid var(--teal);
}

/* Payment split UI */
.payment-split { display: flex; flex-direction: column; gap: 6px; }
.payment-or-divider {
  display: flex; align-items: center; gap: 8px;
  font-size: 10px; font-weight: 700; text-transform: uppercase;
  letter-spacing: .5px; color: var(--muted);
}
.payment-or-divider::before,
.payment-or-divider::after { content:''; flex:1; height:1px; background:var(--border); }
.payment-pending-notice {
  font-size: 11px; color: #92400e; background: #fef3c7;
  border: 1px solid #fde68a; border-radius: 5px;
  padding: 5px 9px; line-height: 1.5;
}

.file-done {
  display: flex; align-items: center; gap: 6px;
  font-size: 11.5px; color: #0d7a4f; font-weight: 600;
  padding: 5px 10px; background: #dcfce7; border-radius: 5px;
}
.file-done a { color: #0d7a4f; text-decoration: underline; font-size: 11px; margin-left: auto; }

.rejected-notice {
  background: #FFF1F2; border: 1px solid #FECDD3; border-radius: 6px;
  padding: 10px 12px; margin-top: 10px;
  font-size: 12px; color: #9F1239; line-height: 1.5;
}

.sub-card-footer {
  display: flex; align-items: center; justify-content: space-between;
  border-top: 1px solid var(--border); padding-top: 10px; margin-top: auto;
  gap: 6px; flex-wrap: wrap;
}
.sub-card-continue {
  font-size: 12.5px; font-weight: 700; color: var(--teal);
  white-space: nowrap; text-decoration: none;
}
.sub-card-continue:hover { text-decoration: underline; }

/* Status badges */
.sb {
  display: inline-flex; align-items: center; gap: 4px;
  font-size: 11px; font-weight: 700; padding: 3px 9px; border-radius: 20px;
}
.sb::before { content:''; width:6px; height:6px; border-radius:50%; flex-shrink:0; }
.sb-draft                { background:#F3F4F6; color:#6B7280;  } .sb-draft::before                { background:#9CA3AF; }
.sb-submitted            { background:#EFF6FF; color:#1D4ED8;  } .sb-submitted::before            { background:#3B82F6; }
.sb-under_review         { background:#FEF3C7; color:#D97706;  } .sb-under_review::before         { background:#F59E0B; }
.sb-accepted             { background:#DCFCE7; color:#15803D;  } .sb-accepted::before             { background:#22C55E; }
.sb-rejected             { background:#FEE2E2; color:#DC2626;  } .sb-rejected::before             { background:#EF4444; }
.sb-accepted_with_changes{ background:#FEF3C7; color:#B45309;  } .sb-accepted_with_changes::before{ background:#F59E0B; }
.sb-resubmit             { background:#EDE9FE; color:#6D28D9;  } .sb-resubmit::before             { background:#8B5CF6; }

.tracking-badge {
  font-family: monospace; font-size: 11px; font-weight: 800;
  color: #1E40AF; background: #EFF6FF; border: 1px solid #BFDBFE;
  border-radius: 4px; padding: 2px 7px;
}

/* Empty state */
.empty { text-align: center; padding: 60px 20px; color: var(--muted); }
.empty-icon  { font-size: 48px; margin-bottom: 16px; }
.empty-title { font-size: 18px; font-weight: 700; color: var(--text); margin-bottom: 8px; }
.empty p     { font-size: 13.5px; }

/* ── Modals ── */
.modal-bg {
  position: fixed; inset: 0; background: rgba(0,0,0,.45);
  z-index: 600; display: none; align-items: center; justify-content: center;
  padding: 16px;          /* prevent modal from touching screen edges */
}
.modal-bg.open { display: flex; }

.modal {
  background: var(--white); border-radius: 10px; padding: 24px;
  width: 460px; max-width: 100%;   /* full-width on small phones */
  max-height: 90vh;                /* don't overflow viewport height */
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0,0,0,.22);
}
.modal-title { font-size: 16px; font-weight: 700; margin-bottom: 8px; }
.modal-desc  { font-size: 13px; color: var(--muted); margin-bottom: 18px; line-height: 1.6; }
.modal-actions {
  display: flex; gap: 10px; justify-content: flex-end;
  flex-wrap: wrap;          /* stack on very narrow screens */
}
.btn-cancel {
  padding: 8px 18px; border: 1.5px solid var(--border); border-radius: 4px;
  background: var(--white); font-family: var(--font); font-size: 13px;
  font-weight: 600; cursor: pointer;
}
.btn-danger {
  padding: 8px 18px; border: none; border-radius: 4px; background: #EF4444;
  color: #fff; font-family: var(--font); font-size: 13px; font-weight: 700; cursor: pointer;
}

.upload-modal { width: 520px; }
.upload-section { margin-bottom: 14px; }
.upload-section label {
  font-size: 12.5px; font-weight: 700; display: block;
  margin-bottom: 5px; color: var(--text);
}
.upload-section input[type=file],
.upload-section input[type=text] {
  width: 100%; padding: 7px 10px; border: 1.5px solid var(--border);
  border-radius: 6px; font-size: 12.5px;
  background: #F9FAFB; font-family: var(--font); box-sizing: border-box;
}
.upload-section input[type=file] { border-style: dashed; cursor: pointer; }
.upload-section input[type=file]:hover,
.upload-section input[type=text]:focus { border-color: var(--teal); outline: none; }
.upload-note { font-size: 11px; color: var(--muted); margin-top: 3px; }

.resubmit-modal { width: 480px; }
.notice-box {
  padding: 10px 14px; border-radius: 6px; font-size: 12.5px;
  line-height: 1.6; margin-bottom: 14px;
}
.notice-box.warn  { background: #FEF3C7; color: #92400E; border: 1px solid #FDE68A; }
.notice-box.info  { background: #EFF6FF; color: #1E40AF; border: 1px solid #BFDBFE; }
.notice-box.teal  { background: #F0FDFA; color: #0f766e; border: 1px solid #99f6e4; }
.notice-box.error { background: #FEE2E2; color: #991B1B; border: 1px solid #FECACA; }

/* ── Toast ── */
.toast-wrap {
  position: fixed; bottom: 20px; right: 20px; z-index: 999;
  display: flex; flex-direction: column; gap: 6px;
  /* keep toasts inside viewport on mobile */
  left: 20px; align-items: flex-end;
}
.toast {
  padding: 10px 16px; color: #fff; border-radius: 4px;
  font-size: 13px; font-weight: 500;
  box-shadow: 0 4px 12px rgba(0,0,0,.2);
  animation: tup .2s ease;
  max-width: calc(100vw - 40px);
}
@keyframes tup { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:translateY(0)} }

/* ── Mobile-specific overrides ── */
@media (max-width: 480px) {
  .page-title { font-size: 18px; }
  .btn-new    { font-size: 13px; padding: 8px 14px; }

  .filter-tab { font-size: 12.5px; padding: 8px 12px; }

  .sub-card         { padding: 14px; }
  .sub-card-title   { font-size: 13px; }

  .modal { padding: 18px; }
  .modal-title { font-size: 15px; }
  /* stack modal action buttons vertically */
  .modal-actions { flex-direction: column-reverse; }
  .modal-actions .btn-cancel,
  .modal-actions .btn-danger,
  .modal-actions .card-btn { width: 100%; justify-content: center; }
}
</style>

<!-- ── PAGE HEADER ── -->
<div class="page-hdr">
  <h1 class="page-title">My current projects</h1>
  <a href="submission.php" class="btn-new">＋ New submission</a>
</div>

<!-- ── FILTER TABS ── -->
<div class="filter-tabs">
  <a href="?filter=all" class="filter-tab <?= $filterTab==='all' ? 'active' : '' ?>">
    All
    <span class="tab-count" style="background:#E5E7EB;color:#374151"><?= $total ?></span>
  </a>
  <?php if ($cntDraft > 0): ?>
  <a href="?filter=draft" class="filter-tab <?= $filterTab==='draft' ? 'active' : '' ?>">
    Draft
    <span class="tab-count" style="background:#F3F4F6;color:#6B7280"><?= $cntDraft ?></span>
  </a>
  <?php endif; ?>
  <?php if ($cntSubmitted > 0): ?>
  <a href="?filter=submitted" class="filter-tab <?= $filterTab==='submitted' ? 'active' : '' ?>">
    Submitted
    <span class="tab-count" style="background:#EFF6FF;color:#1D4ED8"><?= $cntSubmitted ?></span>
  </a>
  <?php endif; ?>
  <?php if ($cntEditorReview > 0): ?>
  <a href="?filter=editor_review" class="filter-tab <?= $filterTab==='editor_review' ? 'active' : '' ?>"
     style="<?= $filterTab==='editor_review' ? 'border-bottom-color:#6d28d9;color:#6d28d9' : '' ?>">
    ✏ Editor Review
    <span class="tab-count" style="background:#EDE9FE;color:#6D28D9"><?= $cntEditorReview ?></span>
  </a>
  <?php endif; ?>
</div>

<!-- ── CARDS ── -->
<?php if ($filtered): ?>
<div class="sub-cards">
  <?php foreach ($filtered as $s):
    $sid         = $s['submission_id'];
    $sStatus     = $s['submission_status'] ?? 'draft';
    $sTracking   = $s['tracking_code'] ?? '';
    $sSubmitted  = in_array($sStatus, ['submitted','under_review','accepted','rejected','accepted_with_changes','resubmit']);
    $hasDecision = !empty($s['latest_decision']);
    $decision    = $s['latest_decision'] ?? '';
    $isAccepted  = in_array($decision, ['accepted','accepted_with_changes']);
    $isResubmit  = $decision === 'resubmit';
    $isRejected  = $decision === 'rejected';
    $isReviewed  = $hasDecision;
    $isOverdue   = !empty($s['revision_due']) && strtotime($s['revision_due']) < time();
    $decInfo     = $hasDecision ? decisionLabel($decision) : null;
    $title       = $s['article_title'] ?: '<<untitled>>';
    $journal     = $s['journal_name'] ? 'CIJSS – '.$s['journal_name'] : ($s['specialty_name'] ? 'CIJSS – '.$s['specialty_name'] : null);
    $sLabel      = ucfirst(str_replace('_',' ', $sStatus));

    $sf = $finalFiles[$sid] ?? [];
    $hasPayment      = isset($sf['payment_receipt']);
    $hasDeclaration  = isset($sf['declaration_form']);
    $hasFinalMs      = isset($sf['final_manuscript_revised']);
    $hasResubmission = isset($sf['resubmission']);
    $allFinalDone    = $hasPayment && $hasDeclaration && $hasFinalMs;

    $paidViaGateway  = !empty($gatewayPaid[$sid]);
    $paymentResolved = $paidViaGateway || $hasPayment;

    $cardClass = '';
    if ($isAccepted) $cardClass = 'is-accepted';
    elseif ($isResubmit) $cardClass = 'is-resubmit';
    elseif ($isRejected) $cardClass = 'is-reviewed';
    elseif ($sSubmitted) $cardClass = 'is-submitted';

    $cardHref = $isReviewed ? "editor_review.php?id=$sid"
              : ($sSubmitted ? "project_detail.php?id=$sid&tab=preview"
              : "submission.php?id=$sid");
  ?>
  <div class="sub-card <?= $cardClass ?>"
       onclick="window.location='<?= $cardHref ?>'">

    <?php if (!$sSubmitted): ?>
    <button class="sub-card-del"
            onclick="event.stopPropagation();confirmDelete(<?= $sid ?>)"
            title="Delete draft">✕</button>
    <?php endif; ?>

    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:10px;flex-wrap:wrap;gap:5px">
      <span class="sb sb-<?= $sStatus ?>"><?= $sLabel ?></span>
      <?php if ($sTracking): ?>
      <span class="tracking-badge"><?= p($sTracking) ?></span>
      <?php endif; ?>
    </div>

    <?php if ($journal): ?>
    <div class="sub-card-journal"><?= p($journal) ?></div>
    <?php endif; ?>

    <div class="sub-card-title"><?= p($title) ?></div>

    <?php if ($hasDecision && $decInfo): ?>
    <div class="card-decision-badge"
         style="color:<?= $decInfo[1] ?>;background:<?= $decInfo[2] ?>;border:1px solid <?= $decInfo[1] ?>44">
      <?= $decInfo[0] ?>
    </div>
    <?php if (!empty($s['revision_due'])): ?>
    <div class="revision-due <?= $isOverdue ? 'overdue' : '' ?>">
      <?= $isOverdue ? '⚠ Overdue —' : '⏰ Due' ?>
      <?= date('M j, Y', strtotime($s['revision_due'])) ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>

    <!-- ═══ ACTION AREA ═══ -->

    <?php if ($isAccepted && !$allFinalDone): ?>
    <div class="card-actions" onclick="event.stopPropagation()">
      <div class="action-section-label">📋 Next Steps Required</div>

      <?php if ($paymentResolved): ?>
        <?php if ($paidViaGateway && !$hasPayment): ?>
        <div class="file-done">✅ Payment confirmed online</div>
        <?php else: ?>
        <div class="file-done">
          ✅ Payment slip uploaded — pending verification
          <a href="<?= p($sf['payment_receipt']['stored_path']) ?>" target="_blank" onclick="event.stopPropagation()">View</a>
        </div>
        <?php endif; ?>
      <?php else: ?>
        <div class="payment-split">
          <a href="pay.php?tracking_code=<?= p($sTracking) ?>"
             class="card-btn card-btn-payment"
             onclick="event.stopPropagation()">
            💳 Pay Online (Card / UPI)
          </a>
          <div class="payment-or-divider">or</div>
          <button class="card-btn card-btn-bank"
                  onclick="event.stopPropagation();openPaymentSlipModal(<?= $sid ?>)">
            🏦 Upload Bank Transfer Slip
          </button>
          <div class="payment-pending-notice">
            ⏳ Already transferred via bank? Upload your payment slip for verification.
          </div>
        </div>
      <?php endif; ?>

      <?php if (!$hasDeclaration): ?>
      <button class="card-btn card-btn-outline"
              onclick="event.stopPropagation();openUploadModal(<?= $sid ?>,'declaration')">
        📄 Upload Declaration Form
      </button>
      <?php else: ?>
      <div class="file-done">
        ✅ Declaration submitted
        <a href="<?= p($sf['declaration_form']['stored_path']) ?>" target="_blank" onclick="event.stopPropagation()">View</a>
      </div>
      <?php endif; ?>

      <?php if (!$hasFinalMs): ?>
      <button class="card-btn card-btn-primary"
              onclick="event.stopPropagation();openUploadModal(<?= $sid ?>,'final_manuscript')">
        📤 Upload Final Manuscript
      </button>
      <?php else: ?>
      <div class="file-done">
        ✅ Final manuscript uploaded
        <a href="<?= p($sf['final_manuscript_revised']['stored_path']) ?>" target="_blank" onclick="event.stopPropagation()">View</a>
      </div>
      <?php endif; ?>
    </div>

    <?php elseif ($isAccepted && $allFinalDone): ?>
    <div class="card-actions" onclick="event.stopPropagation()">
      <div class="file-done" style="background:#bbf7d0;color:#065f46;font-size:12.5px;padding:8px 12px">
        🎉 All files submitted — awaiting publication
      </div>
    </div>

    <?php elseif ($isResubmit): ?>
    <div class="card-actions" onclick="event.stopPropagation()">
      <div class="action-section-label">✏ Revision Required</div>
      <?php if (!$hasResubmission): ?>
      <button class="card-btn card-btn-warning"
              onclick="event.stopPropagation();openResubmitModal(<?= $sid ?>)">
        🔄 Submit Revised Manuscript
      </button>
      <?php else: ?>
      <div class="file-done">
        ✅ Revised manuscript submitted
        <a href="<?= p($sf['resubmission']['stored_path']) ?>" target="_blank" onclick="event.stopPropagation()">View</a>
      </div>
      <div style="font-size:11.5px;color:var(--muted);margin-top:2px">Awaiting re-review</div>
      <?php endif; ?>
    </div>

    <?php elseif ($isRejected): ?>
    <div class="rejected-notice" onclick="event.stopPropagation()">
      <strong>Manuscript not accepted.</strong><br>
      Please review the editor's feedback and consider submitting to another journal.
    </div>

    <?php elseif ($isReviewed): ?>
    <div class="sub-card-footer">
      <div style="font-size:12px;color:#6d28d9;font-weight:600">✏ Decision issued</div>
      <a href="editor_review.php?id=<?= $sid ?>" class="sub-card-continue" onclick="event.stopPropagation()">View review →</a>
    </div>

    <?php elseif ($sSubmitted): ?>
    <div class="sub-card-footer">
      <div style="font-size:12px;color:#3B82F6;font-weight:600">📄 Under review</div>
      <a href="project_detail.php?id=<?= $sid ?>&tab=preview"
         class="sub-card-continue" onclick="event.stopPropagation()">Preview →</a>
    </div>

    <?php else: ?>
    <div class="sub-card-footer">
      <div style="font-size:12px;color:var(--muted)">In preparation</div>
      <a href="submission.php?id=<?= $sid ?>"
         class="sub-card-continue" onclick="event.stopPropagation()">Continue →</a>
    </div>
    <?php endif; ?>

    <?php if ($hasDecision): ?>
    <div style="margin-top:8px;text-align:right" onclick="event.stopPropagation()">
      <a href="editor_review.php?id=<?= $sid ?>"
         style="font-size:11.5px;color:#6d28d9;font-weight:600;text-decoration:none">
        📋 View full review →
      </a>
    </div>
    <?php endif; ?>

  </div><!-- .sub-card -->
  <?php endforeach; ?>
</div>

<?php else: ?>
<div class="empty">
  <div class="empty-icon">
    <?php
    if ($filterTab === 'editor_review') echo '✏';
    elseif ($filterTab === 'submitted') echo '📄';
    elseif ($filterTab === 'draft') echo '📝';
    else echo '📂';
    ?>
  </div>
  <div class="empty-title">
    <?php
    if ($filterTab === 'editor_review')    echo 'No editor reviews yet';
    elseif ($filterTab === 'submitted')    echo 'No submitted manuscripts';
    elseif ($filterTab === 'draft')        echo 'No drafts';
    else echo 'No submissions yet';
    ?>
  </div>
  <p><?= $filterTab === 'all' ? 'Start your first manuscript submission.' : 'Switch to "All" to see everything.' ?></p>
  <?php if ($filterTab === 'all'): ?>
  <a href="submission.php" class="btn-new" style="margin-top:16px;display:inline-flex">＋ New submission</a>
  <?php endif; ?>
</div>
<?php endif; ?>


<!-- ═══════════════════════════════════════════════════════════
     MODALS
════════════════════════════════════════════════════════════ -->

<!-- Delete Modal -->
<div class="modal-bg" id="delModal">
  <div class="modal">
    <div class="modal-title">Remove this draft?</div>
    <div class="modal-desc">This will permanently delete this draft. This cannot be undone.</div>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="closeModal('delModal')">Cancel</button>
      <button class="btn-danger" id="delBtn">Remove draft</button>
    </div>
  </div>
</div>

<!-- Upload Modal (Declaration / Final Manuscript) -->
<div class="modal-bg" id="uploadModal">
  <div class="modal upload-modal" onclick="event.stopPropagation()">
    <div class="modal-title" id="uploadModalTitle">Upload File</div>
    <div class="modal-desc" id="uploadModalDesc">Select the file to upload.</div>

    <div id="decl-section" class="upload-section" style="display:none">
      <div class="notice-box info">
        📋 Please download the declaration form, sign it, and upload the scanned copy as a Word document.
        <br><a href="declaration-form.docx" target="_blank" style="font-weight:700;color:#1d4ed8">
          ⬇ Download Declaration Form
        </a>
      </div>
      <label>Declaration Form (DOC/DOCX) <span style="color:#ef4444">*</span></label>
      <input type="file" id="declFile" accept=".doc,.docx">
      <div class="upload-note">Max 5MB — DOC or DOCX only</div>
    </div>

    <div id="final-section" class="upload-section" style="display:none">
      <div class="notice-box info">
        📄 Upload your final corrected manuscript incorporating all reviewer suggestions.
      </div>
      <label>Final Manuscript (DOC/DOCX) <span style="color:#ef4444">*</span></label>
      <input type="file" id="finalFile" accept=".doc,.docx">
      <div class="upload-note">Max 10MB — DOC or DOCX only</div>
    </div>

    <div id="uploadMsg"></div>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="closeModal('uploadModal')">Cancel</button>
      <button class="card-btn card-btn-primary" style="width:auto;padding:8px 20px" id="uploadSubmitBtn"
              onclick="submitUpload()">Upload</button>
    </div>
  </div>
</div>

<!-- Payment Slip Modal (Bank Transfer) -->
<div class="modal-bg" id="paymentSlipModal">
  <div class="modal upload-modal" onclick="event.stopPropagation()">
    <div class="modal-title">Upload Bank Transfer Payment Slip</div>

    <div class="notice-box teal">
      🏦 Upload your bank transfer / wire transfer receipt so our team can verify your payment.
      Once verified, your submission will proceed to the next step.
    </div>

    <div class="upload-section">
      <label>Payment Slip / Receipt <span style="color:#ef4444">*</span></label>
      <input type="file" id="paySlipFile" accept=".jpg,.jpeg,.png,.pdf,.doc,.docx">
      <div class="upload-note">Max 5MB — JPG, PNG, PDF, DOC or DOCX accepted</div>
    </div>

    <div class="upload-section">
      <label>Transaction / Reference Number <span style="color:#ef4444">*</span></label>
      <input type="text" id="paySlipRef" placeholder="e.g. TXN1234567890">
      <div class="upload-note">Enter the transaction ID or reference number shown on your bank receipt</div>
    </div>

    <div id="paySlipMsg"></div>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="closeModal('paymentSlipModal')">Cancel</button>
      <button class="card-btn card-btn-bank" style="width:auto;padding:8px 20px" id="paySlipSubmitBtn"
              onclick="submitPaymentSlip()">Submit Slip</button>
    </div>
  </div>
</div>

<!-- Resubmit Modal -->
<div class="modal-bg" id="resubmitModal">
  <div class="modal resubmit-modal" onclick="event.stopPropagation()">
    <div class="modal-title">Submit Revised Manuscript</div>
    <div class="notice-box warn">
      ⚠ Please carefully address <strong>all reviewer comments</strong> before resubmitting.
      Your revised file will replace the original for re-review.
    </div>
    <div class="upload-section">
      <label>Revised Manuscript (DOC/DOCX) <span style="color:#ef4444">*</span></label>
      <input type="file" id="resubFile" accept=".doc,.docx">
      <div class="upload-note">Max 10MB — DOC or DOCX only</div>
    </div>
    <div id="resubMsg"></div>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="closeModal('resubmitModal')">Cancel</button>
      <button class="card-btn card-btn-warning" style="width:auto;padding:8px 20px" id="resubSubmitBtn"
              onclick="submitResubmit()">Submit Revision</button>
    </div>
  </div>
</div>

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


<script>
let _activeSid  = null;
let _uploadType = null;

function closeModal(id) {
  document.getElementById(id).classList.remove('open');
}
function toast(msg, t = 's') {
  const d = document.createElement('div');
  d.className = 'toast';
  d.style.background = t === 'e' ? '#EF4444' : '#1D8A5E';
  d.textContent = msg;
  document.getElementById('toastWrap').appendChild(d);
  setTimeout(() => d.remove(), 3500);
}
function setMsg(el, msg, ok) {
  el.innerHTML = `<div style="padding:7px 10px;border-radius:5px;font-size:12.5px;font-weight:600;
    background:${ok?'#dcfce7':'#fee2e2'};color:${ok?'#0d7a4f':'#991b1b'};margin-top:8px">${msg}</div>`;
}

/* ── Delete Draft ── */
function confirmDelete(id) {
  document.getElementById('delModal').classList.add('open');
  document.getElementById('delBtn').onclick = () => doDelete(id);
}
function doDelete(id) {
  fetch('ajax/delete_submission.php', {
    method: 'POST', body: new URLSearchParams({ submission_id: id })
  })
  .then(r => r.json())
  .then(d => {
    closeModal('delModal');
    if (d.success) { toast('Draft removed'); setTimeout(() => location.reload(), 800); }
    else toast('Error: ' + (d.message || 'failed'), 'e');
  })
  .catch(() => { closeModal('delModal'); toast('Network error','e'); });
}

/* ── Upload Modal (Declaration / Final Manuscript) ── */
function openUploadModal(sid, type) {
  _activeSid  = sid;
  _uploadType = type;
  document.getElementById('uploadMsg').innerHTML = '';

  const declSec  = document.getElementById('decl-section');
  const finalSec = document.getElementById('final-section');
  const title    = document.getElementById('uploadModalTitle');
  const desc     = document.getElementById('uploadModalDesc');

  if (type === 'declaration') {
    declSec.style.display  = '';
    finalSec.style.display = 'none';
    title.textContent = 'Upload Declaration Form';
    desc.textContent  = 'Upload the signed author declaration form for submission ID ' + sid + '.';
  } else {
    declSec.style.display  = 'none';
    finalSec.style.display = '';
    title.textContent = 'Upload Final Manuscript';
    desc.textContent  = 'Upload the final, corrected version of your manuscript.';
  }
  document.getElementById('uploadModal').classList.add('open');
}

function submitUpload() {
  const fileInput = _uploadType === 'declaration'
    ? document.getElementById('declFile')
    : document.getElementById('finalFile');

  if (!fileInput.files.length) {
    setMsg(document.getElementById('uploadMsg'), 'Please select a file.', false);
    return;
  }
  const file = fileInput.files[0];
  const ext  = file.name.split('.').pop().toLowerCase();
  if (!['doc','docx'].includes(ext)) {
    setMsg(document.getElementById('uploadMsg'), '❌ Only DOC or DOCX files are allowed.', false);
    return;
  }

  const btn = document.getElementById('uploadSubmitBtn');
  btn.textContent = 'Uploading…'; btn.disabled = true;

  const fd = new FormData();
  fd.append('submission_id', _activeSid);
  fd.append('file_type', _uploadType === 'declaration' ? 'declaration_form' : 'final_manuscript_revised');
  fd.append('file', file);

  fetch('ajax/upload_final_file.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(d => {
      btn.textContent = 'Upload'; btn.disabled = false;
      if (d.success) {
        setMsg(document.getElementById('uploadMsg'), '✅ ' + (d.message || 'Uploaded successfully!'), true);
        toast('File uploaded successfully');
        setTimeout(() => { closeModal('uploadModal'); location.reload(); }, 1200);
      } else {
        setMsg(document.getElementById('uploadMsg'), '❌ ' + (d.message || 'Upload failed'), false);
      }
    })
    .catch(() => {
      btn.textContent = 'Upload'; btn.disabled = false;
      setMsg(document.getElementById('uploadMsg'), '❌ Network error', false);
    });
}

/* ── Payment Slip Modal (Bank Transfer) ── */
function openPaymentSlipModal(sid) {
  _activeSid = sid;
  document.getElementById('paySlipMsg').innerHTML = '';
  document.getElementById('paySlipFile').value = '';
  document.getElementById('paySlipRef').value  = '';
  document.getElementById('paymentSlipModal').classList.add('open');
}

function submitPaymentSlip() {
  const fileInput = document.getElementById('paySlipFile');
  const refInput  = document.getElementById('paySlipRef');
  const msgEl     = document.getElementById('paySlipMsg');

  if (!fileInput.files.length) {
    setMsg(msgEl, 'Please select your payment slip file.', false);
    return;
  }
  if (!refInput.value.trim()) {
    setMsg(msgEl, 'Please enter your transaction / reference number.', false);
    return;
  }

  const file    = fileInput.files[0];
  const ext     = file.name.split('.').pop().toLowerCase();
  const allowed = ['jpg','jpeg','png','pdf','doc','docx'];
  if (!allowed.includes(ext)) {
    setMsg(msgEl, '❌ Allowed formats: JPG, PNG, PDF, DOC, DOCX.', false);
    return;
  }

  const btn = document.getElementById('paySlipSubmitBtn');
  btn.textContent = 'Submitting…'; btn.disabled = true;

  const fd = new FormData();
  fd.append('submission_id', _activeSid);
  fd.append('file_type',     'payment_receipt');
  fd.append('reference_no',  refInput.value.trim());
  fd.append('file',          file);

  fetch('ajax/upload_final_file.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(d => {
      btn.textContent = 'Submit Slip'; btn.disabled = false;
      if (d.success) {
        setMsg(msgEl, '✅ Payment slip submitted! Our team will verify it shortly.', true);
        toast('Payment slip uploaded — pending verification');
        setTimeout(() => { closeModal('paymentSlipModal'); location.reload(); }, 1400);
      } else {
        setMsg(msgEl, '❌ ' + (d.message || 'Upload failed'), false);
      }
    })
    .catch(() => {
      btn.textContent = 'Submit Slip'; btn.disabled = false;
      setMsg(msgEl, '❌ Network error', false);
    });
}

/* ── Resubmit Modal ── */
function openResubmitModal(sid) {
  _activeSid = sid;
  document.getElementById('resubMsg').innerHTML = '';
  document.getElementById('resubFile').value = '';
  document.getElementById('resubmitModal').classList.add('open');
}

function submitResubmit() {
  const fileInput = document.getElementById('resubFile');
  if (!fileInput.files.length) {
    setMsg(document.getElementById('resubMsg'), 'Please select your revised manuscript.', false);
    return;
  }
  const file = fileInput.files[0];
  const ext  = file.name.split('.').pop().toLowerCase();
  if (!['doc','docx'].includes(ext)) {
    setMsg(document.getElementById('resubMsg'), '❌ Only DOC or DOCX files are allowed.', false);
    return;
  }

  const btn = document.getElementById('resubSubmitBtn');
  btn.textContent = 'Submitting…'; btn.disabled = true;

  const fd = new FormData();
  fd.append('submission_id', _activeSid);
  fd.append('file_type', 'resubmission');
  fd.append('file', file);

  fetch('ajax/upload_final_file.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(d => {
      btn.textContent = 'Submit Revision'; btn.disabled = false;
      if (d.success) {
        setMsg(document.getElementById('resubMsg'), '✅ Revised manuscript submitted!', true);
        toast('Revision submitted successfully');
        setTimeout(() => { closeModal('resubmitModal'); location.reload(); }, 1200);
      } else {
        setMsg(document.getElementById('resubMsg'), '❌ ' + (d.message || 'Failed'), false);
      }
    })
    .catch(() => {
      btn.textContent = 'Submit Revision'; btn.disabled = false;
      setMsg(document.getElementById('resubMsg'), '❌ Network error', false);
    });
}

/* ── Close modals on backdrop click ── */
['delModal','uploadModal','paymentSlipModal','resubmitModal'].forEach(id => {
  document.getElementById(id).addEventListener('click', function(e) {
    if (e.target === this) closeModal(id);
  });
});
</script>

<?php layoutEnd(); ?>