<?php
// ============================================================
//  track_paper.php  —  Author: Track Your Paper
// ============================================================
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'];
$pageTitle  = 'Track Your Paper';
$activePage = 'track_paper';

// Fetch all submissions for this author
try {
    $stmt = db()->prepare("
        SELECT 
            s.submission_id,
            s.user_id,
            s.submission_status,
            s.tracking_code,
            s.submitted_at,
            s.created_at,
            s.updated_at,
            j.name AS journal_name,
            mi.article_title,
            (SELECT ed.due_date 
             FROM editorial_decisions ed 
             WHERE ed.submission_id = s.submission_id 
             ORDER BY ed.created_at DESC LIMIT 1) AS latest_due_date,
            (SELECT sf.stored_path 
             FROM submission_files sf 
             WHERE sf.submission_id = s.submission_id 
             AND sf.file_type IN ('manuscript','manuscript_pdf')
             ORDER BY sf.uploaded_at DESC LIMIT 1) AS file_url
        FROM submissions s
        LEFT JOIN journals j ON s.journal_id = j.journal_id
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        WHERE s.user_id = ?
          AND s.submission_status != 'draft'
        ORDER BY s.created_at DESC
    ");
    $stmt->execute([$user_id]);
    $submissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $submissions = [];
}

// Status config: [bg color, text color, label]
function statusStyle($status) {
    $map = [
        'submitted'              => ['#EFF6FF', '#1D4ED8', 'Submitted'],
        'under_review'           => ['#FFFBEB', '#D97706', 'Under Review'],
        'accepted'               => ['#F0FDF4', '#16A34A', 'Accepted'],
        'accepted_with_changes'  => ['#ECFDF5', '#065F46', 'Accepted w/ Changes'],
        'rejected'               => ['#FEF2F2', '#DC2626', 'Rejected'],
        'published'              => ['#F0FDF4', '#15803D', 'Published'],
        'resubmit'               => ['#FEF3C7', '#92400E', 'Revision Required'],
    ];
    return $map[$status] ?? ['#F3F4F6', '#6B7280', ucfirst(str_replace('_', ' ', $status))];
}

// Compute stat counts
$statCounts = ['total' => 0, 'under_review' => 0, 'accepted' => 0, 'published' => 0, 'revision' => 0];
foreach ($submissions as $s) {
    $statCounts['total']++;
    $st = $s['submission_status'];
    if (in_array($st, ['under_review','submitted']))        $statCounts['under_review']++;
    if (in_array($st, ['accepted','accepted_with_changes'])) $statCounts['accepted']++;
    if ($st === 'published')  $statCounts['published']++;
    if ($st === 'resubmit')   $statCounts['revision']++;
}

// Timeline steps per status
function getTimelineSteps($status) {
    $steps = [
        ['label' => 'Submitted',    'key' => 'submitted'],
        ['label' => 'Under Review', 'key' => 'under_review'],
        ['label' => 'Decision',     'key' => 'decision'],
        ['label' => 'Accepted',     'key' => 'accepted'],
        ['label' => 'Published',    'key' => 'published'],
    ];
    $order = [
        'submitted'             => 0,
        'under_review'          => 1,
        'resubmit'              => 2,
        'accepted'              => 3,
        'accepted_with_changes' => 3,
        'published'             => 4,
        'rejected'              => 2,
    ];
    $cur = $order[$status] ?? 0;
    return array_map(function($s, $i) use ($cur) {
        $s['state'] = $i < $cur ? 'done' : ($i === $cur ? 'current' : 'pending');
        return $s;
    }, $steps, array_keys($steps));
}

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

<style>
.tp-wrap { padding: 24px 28px 60px; }

.tp-page-header {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 6px; flex-wrap: wrap; gap: 12px;
}
.tp-page-title { font-size: 18px; font-weight: 700; color: var(--text); }
.tp-page-sub   { font-size: 13px; color: var(--muted); margin-bottom: 22px; }

/* Stats */
.tp-stats { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 22px; }
.tp-stat {
  flex: 1; min-width: 110px;
  background: var(--white); border: 1px solid var(--border);
  border-radius: 10px; padding: 14px 16px; text-align: center;
}
.tp-stat-num   { font-size: 22px; font-weight: 700; color: var(--text); }
.tp-stat-label { font-size: 11.5px; color: var(--muted); margin-top: 3px; }

/* Filters */
.tp-filters { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 18px; }
.tp-filter {
  padding: 6px 14px; border-radius: 20px; font-size: 12.5px; font-weight: 600;
  cursor: pointer; border: 1.5px solid var(--border);
  background: var(--white); color: var(--muted);
  transition: all .15s; font-family: var(--font);
}
.tp-filter:hover  { border-color: var(--blue); color: var(--blue); }
.tp-filter.active { background: var(--blue); color: #fff; border-color: var(--blue); }

/* Cards */
.tp-list { display: flex; flex-direction: column; gap: 14px; }
.tp-card {
  background: var(--white); border: 1px solid var(--border);
  border-radius: 12px; overflow: hidden;
  transition: box-shadow .2s, transform .2s;
}
.tp-card:hover { box-shadow: 0 6px 24px rgba(27,63,110,.1); transform: translateY(-2px); }

/* Band */
.tp-card-band {
  display: flex; align-items: center; justify-content: space-between;
  padding: 14px 20px; gap: 12px; flex-wrap: wrap;
  background: linear-gradient(135deg, var(--blue) 0%, #1E3A5F 100%);
}
.tp-card-code    { font-size: 11px; color: rgba(255,255,255,.7); text-transform: uppercase; letter-spacing: .5px; margin-bottom: 2px; }
.tp-card-tracking{ font-size: 15px; font-weight: 700; color: #fff; font-family: monospace; }
.tp-status-pill  {
  display: inline-flex; align-items: center;
  padding: 4px 12px; border-radius: 20px;
  font-size: 12px; font-weight: 700; white-space: nowrap;
}

/* Timeline */
.tp-timeline {
  display: flex; align-items: center;
  padding: 14px 20px 4px; overflow-x: auto;
}
.tp-step {
  display: flex; flex-direction: column; align-items: center;
  flex: 1; min-width: 70px; position: relative;
}
.tp-step:not(:last-child)::after {
  content: ''; position: absolute; top: 12px; left: 50%;
  width: 100%; height: 2px; background: var(--border); z-index: 0;
}
.tp-step.done:not(:last-child)::after { background: var(--blue); }
.tp-step-dot {
  width: 24px; height: 24px; border-radius: 50%;
  border: 2px solid var(--border); background: var(--white);
  display: flex; align-items: center; justify-content: center;
  font-size: 10px; z-index: 1; position: relative;
}
.tp-step.done    .tp-step-dot { background: var(--blue); border-color: var(--blue); color: #fff; }
.tp-step.current .tp-step-dot { border-color: var(--blue); color: var(--blue); box-shadow: 0 0 0 3px rgba(27,63,110,.15); }
.tp-step-label { font-size: 10px; color: var(--muted); margin-top: 5px; text-align: center; line-height: 1.3; }
.tp-step.done    .tp-step-label { color: var(--blue); font-weight: 600; }
.tp-step.current .tp-step-label { color: var(--text); font-weight: 700; }

.tp-card-divider { height: 1px; background: var(--border); margin: 0 20px 0; }

/* Body */
.tp-card-body   { padding: 16px 20px 4px; }
.tp-paper-title { font-size: 14.5px; font-weight: 700; color: var(--text); margin-bottom: 5px; line-height: 1.4; }
.tp-paper-meta  {
  display: flex; align-items: center; gap: 14px;
  font-size: 12.5px; color: var(--muted); flex-wrap: wrap;
}

/* Actions */
.tp-actions { padding: 14px 20px 18px; display: flex; flex-wrap: wrap; gap: 8px; }
.tp-btn {
  display: inline-flex; align-items: center; gap: 7px;
  padding: 8px 15px; border-radius: 8px;
  font-family: var(--font); font-size: 12.5px; font-weight: 600;
  cursor: pointer; border: none; text-decoration: none;
  transition: all .15s; white-space: nowrap;
}
.tp-btn:hover { transform: translateY(-1px); box-shadow: 0 3px 10px rgba(0,0,0,.1); }
.tp-btn i { font-size: 13px; }

.tp-btn-blue         { background: #EFF6FF; color: #1D4ED8; }
.tp-btn-blue:hover   { background: #DBEAFE; }
.tp-btn-gray         { background: #F3F4F6; color: #374151; }
.tp-btn-gray:hover   { background: #E5E7EB; }
.tp-btn-orange       { background: #FFF7ED; color: #C2410C; }
.tp-btn-orange:hover { background: #FFEDD5; }
.tp-btn-green        { background: #F0FDF4; color: #15803D; }
.tp-btn-green:hover  { background: #DCFCE7; }
.tp-btn-teal         { background: #F0FDFA; color: #0F766E; }
.tp-btn-teal:hover   { background: #CCFBF1; }
.tp-btn-solid-blue        { background: var(--blue); color: #fff; }
.tp-btn-solid-blue:hover  { background: #132B50; }
.tp-btn-solid-purple      { background: #7C3AED; color: #fff; }
.tp-btn-solid-purple:hover{ background: #6D28D9; }
.tp-btn-solid-green       { background: #16A34A; color: #fff; }
.tp-btn-solid-green:hover { background: #15803D; }

/* Empty */
.tp-empty {
  text-align: center; padding: 60px 20px;
  background: var(--white); border: 1px solid var(--border);
  border-radius: 12px;
}
.tp-empty-icon  { font-size: 48px; margin-bottom: 14px; }
.tp-empty-title { font-size: 16px; font-weight: 700; color: var(--text); margin-bottom: 6px; }
.tp-empty-sub   { font-size: 13px; color: var(--muted); margin-bottom: 20px; }

@media (max-width: 600px) {
  .tp-wrap { padding: 16px 14px 48px; }
  .tp-card-band { flex-direction: column; align-items: flex-start; gap: 8px; }
  .tp-stats { flex-direction: column; }
}
</style>

<div class="tp-wrap">

  <div class="tp-page-header">
    <div class="tp-page-title">Track Your Paper</div>
  </div>
  <div class="tp-page-sub">Real-time status of all your manuscript submissions</div>

  <!-- Stats -->
  <div class="tp-stats">
    <div class="tp-stat">
      <div class="tp-stat-num"><?= $statCounts['total'] ?></div>
      <div class="tp-stat-label">Total Submissions</div>
    </div>
    <div class="tp-stat">
      <div class="tp-stat-num" style="color:#D97706"><?= $statCounts['under_review'] ?></div>
      <div class="tp-stat-label">Under Review</div>
    </div>
    <div class="tp-stat">
      <div class="tp-stat-num" style="color:#D97706"><?= $statCounts['revision'] ?></div>
      <div class="tp-stat-label">Revision Pending</div>
    </div>
    <div class="tp-stat">
      <div class="tp-stat-num" style="color:#16A34A"><?= $statCounts['accepted'] ?></div>
      <div class="tp-stat-label">Accepted</div>
    </div>
    <div class="tp-stat">
      <div class="tp-stat-num" style="color:#15803D"><?= $statCounts['published'] ?></div>
      <div class="tp-stat-label">Published</div>
    </div>
  </div>

  <!-- Filters -->
  <div class="tp-filters">
    <button class="tp-filter active" onclick="filterCards(this,'all')">All <span style="opacity:.65">(<?= $statCounts['total'] ?>)</span></button>
    <button class="tp-filter" onclick="filterCards(this,'under_review')">Under Review</button>
    <button class="tp-filter" onclick="filterCards(this,'resubmit')">Revision Required</button>
    <button class="tp-filter" onclick="filterCards(this,'accepted')">Accepted</button>
    <button class="tp-filter" onclick="filterCards(this,'published')">Published</button>
  </div>

  <?php if (empty($submissions)): ?>
  <div class="tp-empty">
    <div class="tp-empty-icon">📭</div>
    <div class="tp-empty-title">No submissions yet</div>
    <div class="tp-empty-sub">Start your publication journey by submitting your first manuscript.</div>
    <a href="submission.php" class="tp-btn tp-btn-solid-blue">
      <i class="fas fa-plus"></i> Submit New Manuscript
    </a>
  </div>

  <?php else: ?>
  <div class="tp-list" id="cardList">
    <?php foreach ($submissions as $sub):
      $status = $sub['submission_status'];
      [$sbg, $scolor, $slabel] = statusStyle($status);
      $is_review    = in_array($status, ['submitted','under_review']);
      $is_revision  = $status === 'resubmit';
      $is_accepted  = in_array($status, ['accepted','accepted_with_changes']);
      $is_published = $status === 'published';
      $sid          = $sub['submission_id'];
      $steps        = getTimelineSteps($status);
      $title        = !empty($sub['article_title']) ? $sub['article_title'] : 'Untitled Manuscript';
      $tracking     = !empty($sub['tracking_code']) ? $sub['tracking_code'] : 'CIJSS-' . str_pad($sid, 6, '0', STR_PAD_LEFT);
    ?>
    <div class="tp-card" data-status="<?= htmlspecialchars($status) ?>">

      <!-- Band -->
      <div class="tp-card-band">
        <div>
          <div class="tp-card-code">Tracking Code</div>
          <div class="tp-card-tracking"><?= htmlspecialchars($tracking) ?></div>
        </div>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
          <span class="tp-status-pill" style="background:<?= $sbg ?>;color:<?= $scolor ?>">
            <?= $slabel ?>
          </span>
          <span style="font-size:11.5px;color:rgba(255,255,255,.65)">
            <?= $sub['submitted_at'] ? date('d M Y', strtotime($sub['submitted_at'])) : date('d M Y', strtotime($sub['created_at'])) ?>
          </span>
        </div>
      </div>

      <!-- Timeline -->
      <div style="padding:14px 20px 4px;">
        <div class="tp-timeline">
          <?php foreach ($steps as $step): ?>
          <div class="tp-step <?= $step['state'] ?>">
            <div class="tp-step-dot">
              <?php if ($step['state'] === 'done'): ?>✓
              <?php elseif ($step['state'] === 'current'): ?>●
              <?php else: ?>○<?php endif; ?>
            </div>
            <div class="tp-step-label"><?= $step['label'] ?></div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="tp-card-divider"></div>

      <!-- Body -->
      <div class="tp-card-body">
        <div class="tp-paper-title"><?= htmlspecialchars($title) ?></div>
        <div class="tp-paper-meta">
          <?php if (!empty($sub['journal_name'])): ?>
          <span>📰 <?= htmlspecialchars($sub['journal_name']) ?></span>
          <?php endif; ?>
          <?php if (!empty($sub['latest_due_date'])): ?>
          <span>📅 Due: <?= date('d M Y', strtotime($sub['latest_due_date'])) ?></span>
          <?php endif; ?>
          <span>🕐 <?= date('d M Y', strtotime($sub['submitted_at'] ?? $sub['created_at'])) ?></span>
        </div>
      </div>

      <!-- Actions -->
      <div class="tp-actions">

        <a href="project_detail.php?id=<?= $sid ?>" class="tp-btn tp-btn-blue">
          <i class="fas fa-eye"></i> View Details
        </a>

        <?php if ($is_review): ?>
          <?php if (!empty($sub['file_url'])): ?>
          <a href="/<?= htmlspecialchars($sub['file_url']) ?>" target="_blank" class="tp-btn tp-btn-gray">
            <i class="fas fa-download"></i> Download MS
          </a>
          <?php endif; ?>
          <a href="my_tickets.php?submission_id=<?= $sid ?>" class="tp-btn tp-btn-blue">
            <i class="fas fa-envelope"></i> Contact Editor
          </a>
        <?php endif; ?>

        <?php if ($is_revision): ?>
          <a href="project_detail.php?id=<?= $sid ?>&tab=comments" class="tp-btn tp-btn-orange">
            <i class="fas fa-comment-dots"></i> View Comments
          </a>
          <a href="submission.php?resubmit=<?= $sid ?>" class="tp-btn tp-btn-solid-purple">
            <i class="fas fa-redo"></i> Resubmit
          </a>
        <?php endif; ?>

        <?php if ($is_accepted): ?>
          <a href="project_detail.php?id=<?= $sid ?>&tab=acceptance" class="tp-btn tp-btn-green">
            <i class="fas fa-file-contract"></i> Acceptance Letter
          </a>
          <a href="https://communeglobal.com/author/paypalpay.php?tracking_code=<?= urlencode($tracking) ?>"
             target="_blank" class="tp-btn tp-btn-solid-blue">
            <i class="fab fa-paypal"></i> Pay APC
          </a>
          <a href="final_submission.php?id=<?= $sid ?>" class="tp-btn tp-btn-solid-purple">
            <i class="fas fa-paper-plane"></i> Final Submission
          </a>
        <?php endif; ?>

        <?php if ($is_published): ?>
          <a href="https://communeglobal.com/author/<?= strtolower(str_replace(' ', '', $sub['journal_name'] ?? '')) ?>/article/<?= $tracking ?>"
             target="_blank" class="tp-btn tp-btn-solid-green">
            <i class="fas fa-external-link-alt"></i> View Paper
          </a>
          <a href="project_detail.php?id=<?= $sid ?>&tab=certificates" class="tp-btn tp-btn-teal">
            <i class="fas fa-certificate"></i> Certificates
          </a>
        <?php endif; ?>

      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

</div>

<script>
function filterCards(btn, status) {
  document.querySelectorAll('.tp-filter').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  document.querySelectorAll('.tp-card').forEach(card => {
    const s = card.dataset.status;
    const show = status === 'all'
      || status === s
      || (status === 'under_review' && ['submitted','under_review'].includes(s))
      || (status === 'accepted'     && ['accepted','accepted_with_changes'].includes(s));
    card.style.display = show ? '' : 'none';
  });
}
</script>

<?php layoutEnd(); ?>