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

// ── Page identity for layout ─────────────────────────────────
$pageTitle  = 'Overview';
$activePage = 'dashboard';

// Load user's affiliation
try {
    $affRow = db()->prepare(
        "SELECT a.name, a.city, a.country
         FROM users u
         LEFT JOIN affiliations a ON a.affiliation_id = u.affiliation_id
         WHERE u.user_id = ? LIMIT 1"
    );
    $affRow->execute([$user_id]);
    $userAffil = $affRow->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e){ $userAffil = null; }

// Latest 3 submissions
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
         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
         WHERE s.user_id = ?
         ORDER BY s.updated_at DESC LIMIT 3"
    );
    $q->execute([$user_id]);
    $latestDrafts = $q->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e){ $latestDrafts = []; }

// Total submissions count
try {
    $q = db()->prepare("SELECT COUNT(*) FROM submissions WHERE user_id=?");
    $q->execute([$user_id]); $totalSubs = (int)$q->fetchColumn();
} catch(PDOException $e){ $totalSubs = 0; }

$fullName     = trim(($user['first_name']??'').' '.($user['last_name']??''));
$initials     = strtoupper(substr($user['first_name']??'A',0,1).substr($user['last_name']??'A',0,1));
$affilName    = $userAffil['name']    ?? '';
$affilCity    = $userAffil['city']    ?? '';
$affilCountry = $userAffil['country'] ?? '';

function p($v){ return htmlspecialchars($v??''); }
function timeAgo($dt){
    if(!$dt) return '';
    $diff = time() - strtotime($dt);
    if($diff < 60)    return 'just now';
    if($diff < 3600)  return round($diff/60).' min ago';
    if($diff < 86400) return round($diff/3600).' hrs ago';
    return date('d M Y', strtotime($dt));
}

// Include shared layout (renders sidebar + topbar + opens .au-main)
require_once __DIR__ . '/_layout.php';
?>

<style>
/* ── Dashboard-specific styles ──────────────────────────── */
.dash-grid { display: grid; grid-template-columns: 1fr 300px; gap: 24px; }
@media(max-width:1100px){ .dash-grid { grid-template-columns: 1fr; } }

/* Welcome box */
.welcome-box { background: var(--white); border-radius: 10px; padding: 22px 26px; margin-bottom: 22px; border: 1px solid var(--border); }
.welcome-sub  { font-size: 13px; color: var(--muted); margin-bottom: 2px; }
.welcome-title{ font-size: 20px; font-weight: 700; }
.welcome-hdr  { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
.link-more    { font-size: 13px; color: var(--teal); font-weight: 700; }
.link-more:hover { text-decoration: underline; }

/* Submission cards */
.sub-cards { display: grid; grid-template-columns: repeat(3,1fr); gap: 14px; }
@media(max-width:900px){ .sub-cards { grid-template-columns: 1fr 1fr; } }
@media(max-width:600px){ .sub-cards { grid-template-columns: 1fr; } }
.sub-card { border: 1.5px solid var(--border); border-radius: 8px; padding: 16px; cursor: pointer; transition: all .18s; position: relative; background: var(--white); }
.sub-card:hover { border-color: #CBD5E1; box-shadow: 0 2px 12px rgba(0,0,0,.08); }
.sub-card-journal { font-size: 12px; color: var(--muted); margin-bottom: 4px; }
.sub-card-title   { font-size: 13.5px; font-weight: 700; margin-bottom: 6px; line-height: 1.4; }
.sub-card-author  { font-size: 12px; color: var(--muted); margin-bottom: 12px; }
.sub-card-footer  { display: flex; align-items: center; justify-content: space-between; border-top: 1px solid var(--border); padding-top: 10px; }
.sub-card-continue{ font-size: 12.5px; font-weight: 700; color: var(--teal); }
.sub-card-continue:hover{ text-decoration: underline; }
.sub-card-del { position: absolute; top: 10px; right: 10px; background: none; border: none; cursor: pointer; color: #CBD5E1; padding: 3px; opacity: 0; transition: opacity .15s; }
.sub-card:hover .sub-card-del{ opacity: 1; }
.sub-card-del:hover{ color: #EF4444; }
.sub-card.is-submitted{ border-color: #BFDBFE; background: #FAFEFF; }

/* Status badge */
.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; }

/* Tracking badge */
.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; letter-spacing: .5px; }

/* Empty state */
.empty-state { text-align: center; padding: 40px 20px; color: var(--muted); }
.empty-state p { margin-bottom: 12px; }
.btn-new { display: inline-flex; align-items: center; gap: 6px; padding: 10px 22px; background: var(--teal); color: #fff; border-radius: 6px; font-size: 13.5px; font-weight: 700; cursor: pointer; border: none; font-family: var(--font); }
.btn-new:hover { background: var(--teal-dk); }

/* News section */
.section-title{ font-size: 18px; font-weight: 700; }
.news-hdr { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
.news-grid{ display: grid; grid-template-columns: repeat(3,1fr); gap: 14px; }
@media(max-width:700px){ .news-grid{ grid-template-columns: 1fr; } }
.news-card { background: var(--white); border-radius: 8px; overflow: hidden; border: 1px solid var(--border); cursor: pointer; transition: box-shadow .18s; }
.news-card:hover { box-shadow: 0 4px 16px rgba(0,0,0,.1); }
.news-img-placeholder { width: 100%; height: 120px; background: linear-gradient(135deg,#EEF2FF,#E0F4F7); display: flex; align-items: center; justify-content: center; font-size: 30px; }
.news-body  { padding: 12px; }
.news-cat   { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .6px; color: var(--muted); margin-bottom: 3px; }
.news-date  { font-size: 11px; color: var(--muted); margin-bottom: 5px; }
.news-title { font-size: 13px; font-weight: 700; line-height: 1.4; }

/* Right sidebar cards */
.r-card { background: var(--white); border-radius: 10px; border: 1px solid var(--border); overflow: hidden; margin-bottom: 16px; }
.profile-card { padding: 18px; }
.profile-av-row { display: flex; align-items: center; gap: 12px; padding-bottom: 14px; border-bottom: 1px solid var(--border); margin-bottom: 12px; }
.profile-av   { width: 46px; height: 46px; border-radius: 50%; background: var(--teal); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 16px; font-weight: 700; flex-shrink: 0; }
.profile-name { font-size: 14px; font-weight: 700; }
.profile-affil{ font-size: 12px; color: var(--muted); line-height: 1.4; margin-top: 2px; }
.profile-stat-row { display: flex; align-items: center; justify-content: space-between; font-size: 13px; padding: 5px 0; }
.profile-stat-label { color: var(--muted); }
.profile-stat-val   { font-weight: 700; }
.invoices-row { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; cursor: pointer; }
.invoices-row:hover { background: #FAFAFA; }
.promo { padding: 18px; background: linear-gradient(135deg,#1B3F6E,#1A5276); color: #fff; }
.promo-title { font-size: 14px; font-weight: 700; margin-bottom: 6px; }
.promo-desc  { font-size: 12px; line-height: 1.6; opacity: .9; margin-bottom: 12px; }
.promo-btn   { display: inline-block; padding: 7px 16px; background: var(--teal); color: #fff; border-radius: 4px; font-size: 12.5px; font-weight: 700; cursor: pointer; border: none; font-family: var(--font); }
.fee-support { padding: 16px; }
.fee-title   { font-size: 13.5px; font-weight: 700; margin-bottom: 6px; }
.fee-desc    { font-size: 12px; color: var(--muted); line-height: 1.6; margin-bottom: 8px; }
.fee-link    { font-size: 13px; font-weight: 700; color: var(--teal); }

/* Modal */
.modal-bg { position: fixed; inset: 0; background: rgba(0,0,0,.4); z-index: 500; display: none; align-items: center; justify-content: center; }
.modal-bg.open { display: flex; }
.modal { background: var(--white); border-radius: 10px; padding: 26px; width: 400px; max-width: 90vw; }
.modal-title { font-size: 15px; 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; }
.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; }
.btn-danger:hover { background: #DC2626; }

/* Toast */
.toast-wrap { position: fixed; bottom: 20px; right: 20px; z-index: 999; }
.toast { padding: 10px 16px; border-radius: 4px; font-size: 13px; font-weight: 500; color: #fff; box-shadow: 0 4px 12px rgba(0,0,0,.2); animation: tup .2s ease; margin-top: 6px; }
@keyframes tup { from{opacity:0;transform:translateY(6px)} to{opacity:1;transform:translateY(0)} }
</style>

<!-- ── PAGE CONTENT ────────────────────────────────────────── -->
<div class="dash-grid">

  <!-- LEFT -->
  <div>

    <!-- Welcome + Submissions -->
    <div class="welcome-box">
      <div class="welcome-hdr">
        <div>
          <div class="welcome-sub">Welcome back, <?= p($fullName) ?></div>
          <div class="welcome-title">You're on track</div>
        </div>
        <a href="projects.php" class="link-more">My projects ›</a>
      </div>

      <?php if ($latestDrafts): ?>
      <div class="sub-cards">
        <?php foreach ($latestDrafts as $d):
          $journal = $d['journal_name'] ? 'Communeglobal '.$d['journal_name'] : null;
          $specialty = $d['specialty_name'] ?? null;
          $journalDisplay = $journal ? ($specialty ? "$journal | $specialty" : $journal) : null;
          $title   = $d['article_title'] ?: '<<untitled>>';
          $dStatus = $d['submission_status'] ?? 'draft';
          $dTracking = $d['tracking_code'] ?? '';
          $isSubmittedCard = in_array($dStatus, ['submitted','under_review','accepted','rejected']);
          $statusLabel = ucfirst(str_replace('_',' ', $dStatus));
        ?>
        <div class="sub-card <?= $isSubmittedCard ? 'is-submitted' : '' ?>"
             onclick="window.location='project_detail.php?id=<?= $d['submission_id'] ?>'">

          <?php if (!$isSubmittedCard): ?>
          <button class="sub-card-del"
                  onclick="event.stopPropagation();confirmDelete(<?= $d['submission_id'] ?>)"
                  title="Delete">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="3 6 5 6 21 6"/>
              <path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/>
            </svg>
          </button>
          <?php endif; ?>

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

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

          <div class="sub-card-footer">
            <?php if ($isSubmittedCard): ?>
            <div style="font-size:12px;color:#3B82F6;font-weight:600">
              <?= $dTracking ? '🔖 '.$dTracking : '✅ '.$statusLabel ?>
            </div>
            <a href="project_detail.php?id=<?= $d['submission_id'] ?>&tab=preview"
               class="sub-card-continue" onclick="event.stopPropagation()">
              👁 Preview
            </a>
            <?php else: ?>
            <div style="font-size:12px;color:var(--muted)">In preparation</div>
            <a href="submission.php?id=<?= $d['submission_id'] ?>"
               class="sub-card-continue" onclick="event.stopPropagation()">
              Continue submission
            </a>
            <?php endif; ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>

      <!-- New submission CTA if less than 3 drafts -->
      <?php if (count($latestDrafts) < 3): ?>
      <div style="margin-top:14px;text-align:center">
        <a href="submission.php" class="btn-new">＋ New submission</a>
      </div>
      <?php endif; ?>

      <?php else: ?>
      <div class="empty-state">
        <p>No submissions yet. Start your first manuscript submission.</p>
        <a href="submission.php" class="btn-new">＋ New submission</a>
      </div>
      <?php endif; ?>
    </div>

    <!-- News -->
    <div>
      <div class="news-hdr">
        <div class="section-title">News</div>
        <a href="#" class="link-more">View all ›</a>
      </div>
      <div class="news-grid">
        <?php
        $newsItems = [
          ['cat'=>'COMMUNEGLOBAL UPDATES','date'=>'5 Mar 2026','title'=>'How do you know you can trust the science you read?','emoji'=>'🔬'],
          ['cat'=>'FEATURED NEWS',        'date'=>'4 Mar 2026','title'=>"Chimps' love for crystals could help us understand our own",'emoji'=>'🦧'],
          ['cat'=>'FEATURED NEWS',        'date'=>'3 Mar 2026','title'=>'Modern twist on wildfire management methods found','emoji'=>'🌲'],
        ];
        foreach ($newsItems as $n): ?>
        <div class="news-card">
          <div class="news-img-placeholder"><?= $n['emoji'] ?></div>
          <div class="news-body">
            <div class="news-cat"><?= $n['cat'] ?></div>
            <div class="news-date"><?= $n['date'] ?></div>
            <div class="news-title"><?= $n['title'] ?></div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>

  </div><!-- /left -->

  <!-- RIGHT -->
  <div>

    <!-- Profile card -->
    <div class="r-card">
      <div class="profile-card">
        <div class="profile-av-row">
          <div class="profile-av"><?= p($initials) ?></div>
          <div>
            <div class="profile-name"><?= p($fullName) ?></div>
            <?php if ($affilName): ?>
            <div class="profile-affil"><?= p($affilName) ?><?= $affilCity ? ', '.p($affilCity) : '' ?><?= $affilCountry ? ', '.p($affilCountry) : '' ?></div>
            <?php endif; ?>
          </div>
        </div>
        <div class="profile-stat-row">
          <span class="profile-stat-label">Total submissions</span>
          <span class="profile-stat-val"><?= $totalSubs ?></span>
        </div>
        <div class="profile-stat-row">
          <span class="profile-stat-label">In preparation</span>
          <span class="profile-stat-val"><?= count(array_filter($latestDrafts, fn($d) => ($d['submission_status']??'draft')==='draft')) ?></span>
        </div>
      </div>
    </div>

    <!-- My invoices -->
    <div class="r-card">
      <div class="invoices-row" onclick="window.location='#'">
        <div style="display:flex;align-items:center;gap:10px;font-size:13.5px;font-weight:600">
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#777" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
          My invoices
        </div>
        <span style="color:var(--muted)">›</span>
      </div>
    </div>

    <!-- Promo -->
    <div class="r-card">
      <div class="promo">
        <div class="promo-title">Guardians of scientific integrity</div>
        <div class="promo-desc">Our research integrity team leads the rigorous process that protects every publication.</div>
        <button class="promo-btn">Discover how</button>
      </div>
    </div>

    <!-- Fee support -->
    <div class="r-card">
      <div class="fee-support">
        <div class="fee-title">Eligible for fee support?</div>
        <div class="fee-desc">If your institution is partnered with us you can benefit from full or partial support for article processing charges.</div>
        <a href="#" class="fee-link">Find out more ›</a>
      </div>
    </div>

  </div><!-- /right -->

</div><!-- /dash-grid -->

<!-- Delete confirm 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 submission. This action cannot be undone.</div>
    <div class="modal-actions">
      <button class="btn-cancel" onclick="closeModal()">Cancel</button>
      <button class="btn-danger" id="delConfirmBtn">Remove draft</button>
    </div>
  </div>
</div>
<div class="toast-wrap" id="toastWrap"></div>

<script>
let _delId = null;
function confirmDelete(id) {
  _delId = id;
  document.getElementById('delModal').classList.add('open');
  document.getElementById('delConfirmBtn').onclick = () => doDelete(id);
}
function closeModal() {
  document.getElementById('delModal').classList.remove('open');
}
function doDelete(id) {
  fetch('ajax/delete_submission.php', {
    method: 'POST',
    body: new URLSearchParams({ submission_id: id })
  })
  .then(r => r.json())
  .then(d => {
    closeModal();
    if (d.success) { showToast('Draft removed'); setTimeout(() => location.reload(), 800); }
    else showToast('Error: ' + (d.message || 'failed'), 'e');
  })
  .catch(() => { closeModal(); showToast('Network error', 'e'); });
}
function showToast(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(), 3000);
}
</script>

<?php layoutEnd(); ?>