<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

// Same auth as your other admin pages
include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_role('admin');

// $pdo from db_new.php — same DB

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

// ── Status update ─────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['update_status'])) {
    $valid = ['draft','submitted','under_review','accepted','rejected'];
    if (in_array($_POST['new_status']??'', $valid)) {
        $pdo->prepare("UPDATE submissions SET submission_status=?, updated_at=NOW() WHERE submission_id=?")
           ->execute([$_POST['new_status'], $sid]);
    }
    header("Location: submission_view.php?id=$sid&updated=1"); exit;
}

// ── Load all data ─────────────────────────────────────────────
// 1. Submission + user + journal + article type
$q = $pdo->prepare("
    SELECT s.*, u.first_name, u.last_name, u.email, u.phone_number,
           u.institutional_email,
           j.name AS journal_name, j.description AS journal_desc,
           at.name AS article_type_name, at.preliminary_fee_chf,
           sp.name AS specialty_name
    FROM submissions s
    LEFT JOIN users u ON u.user_id = s.user_id
    LEFT JOIN journals j ON j.journal_id = s.journal_id
    LEFT JOIN article_types at ON at.article_type_id = s.article_type_id
    LEFT JOIN specialties sp ON sp.specialty_id = s.specialty_id
    WHERE s.submission_id = ?
");
$q->execute([$sid]);
$sub = $q->fetch();
if (!$sub) { header('Location: submissions.php'); exit; }

// 2. Manuscript
try {
   // With this — guarantees all keys exist:
    $q2 = $pdo->prepare("SELECT * FROM manuscript_info WHERE submission_id=?");
    $q2->execute([$sid]);
    $minfo = $q2->fetch(PDO::FETCH_ASSOC) ?: [
        'article_title'    => null,
        'running_title'    => null,
        'abstract'         => null,
        'ethical_approval' => null,
    ];
    $q2 = $pdo->prepare("SELECT k.name FROM submission_keywords sk JOIN keywords k ON k.keyword_id=sk.keyword_id WHERE sk.submission_id=?");
    $q2->execute([$sid]); $keywords = array_column($q2->fetchAll(), 'name');
} catch(PDOException $e){ $minfo=[]; $keywords=[]; }

// 3. Authors
try {
    $q3 = $pdo->prepare("
        SELECT sa.*, a.name AS affil_name, a.city, a.country
        FROM submission_authors sa
        LEFT JOIN affiliations a ON a.affiliation_id = sa.affiliation_id
        WHERE sa.submission_id = ? ORDER BY sa.is_corresponding DESC, sa.author_order ASC
    ");
    $q3->execute([$sid]); $authors = $q3->fetchAll();
    // Contributions
    $contributions = [];
    if ($authors) {
        $ids = implode(',', array_map('intval', array_column($authors,'author_id')));
        $rows = $pdo->query("SELECT * FROM author_contributions WHERE author_id IN ($ids)")->fetchAll();
        foreach($rows as $r) $contributions[$r['author_id']] = $r;
    }
} catch(PDOException $e){ $authors=[]; $contributions=[]; }

// 4. Editorial
try {
    $q4 = $pdo->prepare("SELECT * FROM submission_editorial WHERE submission_id=?");
    $q4->execute([$sid]); $editorial = $q4->fetch() ?: [];
    $q4 = $pdo->prepare("SELECT * FROM suggested_reviewers WHERE submission_id=? ORDER BY reviewer_type, created_at");
    $q4->execute([$sid]); $reviewers = $q4->fetchAll();
    $suggested = array_filter($reviewers, fn($r)=>$r['reviewer_type']==='suggested');
    $opposed   = array_filter($reviewers, fn($r)=>$r['reviewer_type']==='opposed');
} catch(PDOException $e){ $editorial=[]; $reviewers=[]; $suggested=[]; $opposed=[]; }

// 5. Statements
try {
    $q5 = $pdo->prepare("SELECT * FROM submission_statements WHERE submission_id=?");
    $q5->execute([$sid]); $ss = $q5->fetch() ?: [];
    $funders = json_decode($ss['funder_data']??'[]', true) ?: [];
} catch(PDOException $e){ $ss=[]; $funders=[]; }

// 6. Payment
try {
    $q6 = $pdo->prepare("SELECT * FROM submission_payment WHERE submission_id=?");
    $q6->execute([$sid]); $pay = $q6->fetch() ?: [];
    $discounts = json_decode($pay['discount_codes']??'[]', true) ?: [];
} catch(PDOException $e){ $pay=[]; $discounts=[]; }

// 7. Files
try {
    $q7 = $pdo->prepare("SELECT * FROM submission_files WHERE submission_id=? ORDER BY created_at");
    $q7->execute([$sid]); $files = $q7->fetchAll();
} catch(PDOException $e){ $files=[]; }

$status = $sub['submission_status'] ?? 'draft';
$fullName = trim(($sub['first_name']??'').' '.($sub['last_name']??''));
$fee = number_format((float)($sub['preliminary_fee_chf']??0),2);

function p($v){ return htmlspecialchars($v??''); }
function sv($a,$k,$d=''){ return $a[$k]??$d; }
function badge($s){
    $map=['draft'=>'bg-gray-100 text-gray-600','submitted'=>'bg-blue-100 text-blue-700',
          'under_review'=>'bg-yellow-100 text-yellow-700','accepted'=>'bg-green-100 text-green-700',
          'rejected'=>'bg-red-100 text-red-700'];
    return $map[$s] ?? 'bg-gray-100 text-gray-600';
}

$active_section = 'submissions';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Submission #<?=$sid?> — Admin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
body{font-family:'Roboto',sans-serif;margin:0;height:100vh;overflow:hidden}
body.dark{background-color:#1a202c;color:#e2e8f0}
.sidebar{width:250px;background:#2d3748;color:white;transition:all .3s;height:100%;position:fixed;top:0;left:0;z-index:10;overflow-y:auto}
.sidebar.collapsed{width:70px}
.sidebar.collapsed .sidebar-title{display:none}
.content{margin-left:250px;transition:margin-left .3s;height:100vh;overflow-y:auto}
.content.collapsed-sidebar{margin-left:70px}
.nav-item{padding:10px 12px;cursor:pointer;transition:background .2s;display:flex;align-items:center}
.nav-item:hover{background:#4a5568}
.nav-item.active{background:#4a5568;border-left:4px solid #4299e1}
body.dark .bg-white{background-color:#2d3748}
body.dark .bg-gray-50{background-color:#374151}
body.dark .border-gray-200,.dark .border-gray-100{border-color:#4a5568}
body.dark .text-gray-800{color:#F3F4F6}
body.dark .text-gray-700{color:#D1D5DB}
body.dark .text-gray-600{color:#9CA3AF}
body.dark .text-gray-500{color:#6B7280}
@media(max-width:768px){.sidebar{transform:translateX(-250px)}.sidebar.mobile-open{transform:translateX(0)}.content{margin-left:0}}
/* Section cards */
.sec-card{background:white;border-radius:12px;border:1px solid #E5E7EB;overflow:hidden;margin-bottom:20px}
.sec-hdr{display:flex;align-items:center;justify-content:space-between;padding:14px 20px;background:#F9FAFB;border-bottom:1px solid #E5E7EB;cursor:pointer}
.sec-hdr-left{display:flex;align-items:center;gap:10px}
.sec-icon{width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0}
.sec-title{font-size:14px;font-weight:600;color:#1F2937}
.sec-body{padding:20px}
.sec-done{display:inline-flex;align-items:center;gap:4px;font-size:11px;font-weight:600;padding:2px 8px;border-radius:20px}
/* Info grid */
.info-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
@media(max-width:640px){.info-grid{grid-template-columns:1fr}}
.info-item{}
.info-label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.5px;color:#9CA3AF;margin-bottom:3px}
.info-value{font-size:13.5px;color:#1F2937;line-height:1.5}
.info-value.empty{color:#9CA3AF;font-style:italic}
/* Status badge */
.status-pill{display:inline-flex;align-items:center;gap:6px;padding:5px 14px;border-radius:20px;font-size:13px;font-weight:600}
.status-pill::before{content:'';width:7px;height:7px;border-radius:50%;flex-shrink:0}
.sp-draft{background:#F3F4F6;color:#6B7280}.sp-draft::before{background:#6B7280}
.sp-submitted{background:#EFF6FF;color:#2563EB}.sp-submitted::before{background:#2563EB}
.sp-under_review{background:#FEF3C7;color:#D97706}.sp-under_review::before{background:#D97706}
.sp-accepted{background:#F0FDF4;color:#059669}.sp-accepted::before{background:#059669}
.sp-rejected{background:#FEF2F2;color:#DC2626}.sp-rejected::before{background:#DC2626}
/* Author card */
.author-card{border:1px solid #E5E7EB;border-radius:8px;padding:14px;background:#FAFAFA}
.corr-badge{display:inline-flex;align-items:center;padding:1px 7px;background:#DCFCE7;color:#166534;font-size:10px;font-weight:700;border-radius:10px;margin-left:6px;vertical-align:middle}
/* Keyword tag */
.kw-tag{display:inline-flex;align-items:center;padding:3px 10px;background:#EFF6FF;border:1px solid #BFDBFE;border-radius:4px;font-size:12px;color:#2563EB;font-weight:500;margin:2px}
/* File row */
.file-row{display:flex;align-items:center;justify-content:space-between;padding:10px 14px;border:1px solid #E5E7EB;border-radius:8px;background:#FAFAFA;margin-bottom:8px}
/* Timeline */
.tl-item{display:flex;gap:12px;padding-bottom:16px;position:relative}
.tl-item::before{content:'';position:absolute;left:11px;top:24px;width:2px;height:calc(100% - 16px);background:#E5E7EB}
.tl-item:last-child::before{display:none}
.tl-dot{width:24px;height:24px;border-radius:50%;border:2px solid #E5E7EB;background:white;display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:9px}
</style>
</head>
<body class="bg-gray-100">

<button onclick="toggleMobileSidebar()" class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>

<!-- SIDEBAR -->
<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content" id="content">

  <!-- Header -->
  <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
    <div class="flex items-center gap-3">
      <button onclick="toggleSidebar()" class="text-gray-500 hover:text-gray-700 hidden md:block">
        <i class="fas fa-bars text-lg"></i>
      </button>
      <div class="flex items-center gap-3">
        <a href="submissions.php" class="text-gray-400 hover:text-gray-600 transition">
          <i class="fas fa-arrow-left"></i>
        </a>
        <div>
          <h1 class="text-xl font-bold text-gray-800">Submission #<?=$sid?></h1>
          <p class="text-xs text-gray-500 mt-0.5">
            <?=p(($minfo['article_title'] ?? null) ?: '<<untitled>>')?> · <?=p($fullName)?>
          </p>
        </div>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <button id="darkModeToggle" class="text-gray-500 hover:text-gray-700 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center">
        <i class="fas fa-moon"></i>
      </button>
      <?php if(!empty($_GET['updated'])): ?>
      <span class="bg-green-50 text-green-700 border border-green-200 px-3 py-1.5 rounded-lg text-xs font-medium flex items-center gap-1">
        <i class="fas fa-check-circle"></i> Status updated
      </span>
      <?php endif; ?>
      <a href="../submit.php?id=<?=$sid?>" target="_blank"
         class="border border-gray-300 text-gray-600 hover:bg-gray-50 px-3 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition">
        <i class="fas fa-external-link-alt"></i> Open Form
      </a>
    </div>
  </div>

  <main class="p-6">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

      <!-- ── LEFT COLUMN (2/3) ───────────────────────────── -->
      <div class="lg:col-span-2 space-y-5">

        <!-- 1. SUBMISSION DETAILS -->
        <div class="sec-card">
          <div class="sec-hdr" onclick="toggleSec('s1')">
            <div class="sec-hdr-left">
              <div class="sec-icon bg-blue-100"><i class="fas fa-file-alt text-blue-600"></i></div>
              <div>
                <div class="sec-title">1. Submission Details</div>
                <div class="text-xs text-gray-400 mt-0.5">Journal, article type, specialty</div>
              </div>
            </div>
            <?php if($sub['journal_id'] && $sub['article_type_id']): ?>
            <span class="sec-done bg-green-50 text-green-700"><i class="fas fa-check-circle"></i> Complete</span>
            <?php else: ?>
            <span class="sec-done bg-red-50 text-red-500"><i class="fas fa-circle"></i> Incomplete</span>
            <?php endif; ?>
          </div>
          <div class="sec-body" id="s1">
            <div class="info-grid">
              <div class="info-item">
                <div class="info-label">Journal</div>
                <div class="info-value <?=empty($sub['journal_name'])?'empty':''?>">
                  <?=$sub['journal_name'] ? 'Frontiers in '.p($sub['journal_name']) : 'Not selected'?>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">Specialty</div>
                <div class="info-value <?=empty($sub['specialty_name'])?'empty':''?>">
                  <?=p($sub['specialty_name'] ?: 'Not selected')?>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">Article Type</div>
                <div class="info-value <?=empty($sub['article_type_name'])?'empty':''?>">
                  <?=p($sub['article_type_name'] ?: 'Not selected')?>
                </div>
              </div>
              <div class="info-item">
                <div class="info-label">Preliminary Fee</div>
                <div class="info-value"><?=$fee?> CHF</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 2. MANUSCRIPT -->
        <div class="sec-card">
          <div class="sec-hdr" onclick="toggleSec('s2')">
            <div class="sec-hdr-left">
              <div class="sec-icon bg-purple-100"><i class="fas fa-scroll text-purple-600"></i></div>
              <div>
                <div class="sec-title">2. Manuscript Information</div>
                <div class="text-xs text-gray-400 mt-0.5">Title, abstract, keywords, files</div>
              </div>
            </div>
            <?php if(!empty($minfo['article_title'] ?? '') && !empty($minfo['abstract'] ?? '')): ?>
            <span class="sec-done bg-green-50 text-green-700"><i class="fas fa-check-circle"></i> Complete</span>
            <?php else: ?>
            <span class="sec-done bg-red-50 text-red-500"><i class="fas fa-circle"></i> Incomplete</span>
            <?php endif; ?>
          </div>
          <div class="sec-body" id="s2">
            <div class="info-item mb-4">
              <div class="info-label">Article Title</div>
              <div class="info-value text-base font-semibold <?=empty($minfo['article_title'])?'empty':''?>">
                <?=p(($minfo['article_title'] ?? null) ?: 'Not provided')?>
              </div>
            </div>
            <?php if(!empty($minfo['running_title'] ?? '')): ?>
            <div class="info-item mb-4">
              <div class="info-label">Running Title</div>
              <div class="info-value"><?=p($minfo['running_title'])?></div>
            </div>
            <?php endif; ?>
            <div class="info-item mb-4">
              <div class="info-label">Abstract</div>
              <?php if(!empty($minfo['abstract'])): ?>
              <div class="info-value bg-gray-50 rounded-lg p-3 text-sm leading-relaxed border border-gray-100" style="max-height:160px;overflow-y:auto">
                <?=nl2br(p($minfo['abstract']))?>
              </div>
              <?php else: ?>
              <div class="info-value empty">Not provided</div>
              <?php endif; ?>
            </div>
            <?php if(!empty($keywords)): ?>
            <div class="info-item mb-4">
              <div class="info-label">Keywords (<?=count($keywords)?>)</div>
              <div class="flex flex-wrap gap-1 mt-1">
                <?php foreach($keywords as $kw): ?>
                <span class="kw-tag"><?=p($kw)?></span>
                <?php endforeach; ?>
              </div>
            </div>
            <?php endif; ?>
            <?php if(!empty($minfo['ethical_approval'])): ?>
            <div class="info-item mb-2">
              <div class="info-label">Ethical Approval</div>
              <div class="info-value"><?=p($minfo['ethical_approval'])?></div>
            </div>
            <?php endif; ?>
            <!-- Files -->
            <?php if(!empty($files)): ?>
            <div class="info-item mt-4">
              <div class="info-label">Uploaded Files (<?=count($files)?>)</div>
              <div class="mt-2">
                <?php foreach($files as $f): ?>
                <div class="file-row">
                  <div class="flex items-center gap-3">
                    <i class="fas fa-file text-blue-400 text-lg"></i>
                    <div>
                      <div class="text-sm font-medium text-gray-700"><?=p($f['original_name']??$f['file_name']??'file')?></div>
                      <div class="text-xs text-gray-400"><?=p($f['file_type']??'')?> · <?=!empty($f['file_size'])?round($f['file_size']/1024,1).' KB':''?></div>
                    </div>
                  </div>
                  <?php if(!empty($f['file_path'])): ?>
                  <a href="../<?=p($f['file_path'])?>" target="_blank"
                     class="text-xs text-blue-600 hover:underline flex items-center gap-1">
                    <i class="fas fa-download"></i> Download
                  </a>
                  <?php endif; ?>
                </div>
                <?php endforeach; ?>
              </div>
            </div>
            <?php endif; ?>
          </div>
        </div>

        <!-- 3. AUTHORS -->
        <div class="sec-card">
          <div class="sec-hdr" onclick="toggleSec('s3')">
            <div class="sec-hdr-left">
              <div class="sec-icon bg-teal-100"><i class="fas fa-users text-teal-600"></i></div>
              <div>
                <div class="sec-title">3. Authors & Contributors</div>
                <div class="text-xs text-gray-400 mt-0.5"><?=count($authors)?> author<?=count($authors)!==1?'s':''?></div>
              </div>
            </div>
            <?php $hasCorr = !empty(array_filter($authors, fn($a)=>$a['is_corresponding']));?>
            <?php if(count($authors)>0 && $hasCorr): ?>
            <span class="sec-done bg-green-50 text-green-700"><i class="fas fa-check-circle"></i> Complete</span>
            <?php else: ?>
            <span class="sec-done bg-red-50 text-red-500"><i class="fas fa-circle"></i> <?=count($authors)===0?'No authors':'No corresponding'?></span>
            <?php endif; ?>
          </div>
          <div class="sec-body" id="s3">
            <?php if(empty($authors)): ?>
            <div class="text-gray-400 text-sm italic text-center py-4">No authors added</div>
            <?php else: ?>
            <div class="space-y-3">
              <?php foreach($authors as $idx => $a):
                $aName = trim(($a['first_name']??'').' '.($a['last_name']??''));
                $aInit = strtoupper(substr($a['first_name']??'A',0,1).substr($a['last_name']??'',0,1));
                $ac = $contributions[$a['author_id']] ?? [];
              ?>
              <div class="author-card">
                <div class="flex items-start gap-3">
                  <div class="w-9 h-9 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center text-xs font-bold flex-shrink-0">
                    <?=p($aInit)?>
                  </div>
                  <div class="flex-1 min-w-0">
                    <div class="font-semibold text-gray-800 text-sm">
                      <?=p(($a['title']??'').' '.$aName)?>
                      <?php if($a['is_corresponding']): ?>
                      <span class="corr-badge"><i class="fas fa-star text-[8px]"></i> Corresponding</span>
                      <?php endif; ?>
                    </div>
                    <?php if(!empty($a['affil_name'])): ?>
                    <div class="text-xs text-gray-500 mt-0.5">
                      <i class="fas fa-university text-[10px]"></i>
                      <?=p($a['affil_name'])?>
                      <?php if(!empty($a['city'])): ?>, <?=p($a['city'])?><?php endif; ?>
                      <?php if(!empty($a['country'])): ?>, <?=p($a['country'])?><?php endif; ?>
                    </div>
                    <?php endif; ?>
                    <?php if(!empty($a['email'])): ?>
                    <div class="text-xs text-gray-500 mt-0.5">
                      <i class="fas fa-envelope text-[10px]"></i> <?=p($a['email'])?>
                    </div>
                    <?php endif; ?>
                    <?php if(!empty($a['orcid'])): ?>
                    <div class="text-xs text-gray-400 mt-0.5">ORCID: <?=p($a['orcid'])?></div>
                    <?php endif; ?>
                    <!-- Contributions -->
                    <?php if(!empty($ac)): ?>
                    <div class="mt-2 flex flex-wrap gap-1">
                      <?php
                      $contribFields = ['conceptualization','methodology','software','validation',
                        'formal_analysis','investigation','resources','data_curation',
                        'writing_original','writing_review','visualization','supervision',
                        'project_administration','funding_acquisition'];
                      $contribLabels = ['Conceptualization','Methodology','Software','Validation',
                        'Formal Analysis','Investigation','Resources','Data Curation',
                        'Writing (Original Draft)','Writing (Review & Editing)','Visualization',
                        'Supervision','Project Administration','Funding Acquisition'];
                      foreach($contribFields as $ci => $cf):
                        if(!empty($ac[$cf])):
                      ?>
                      <span class="text-xs bg-blue-50 text-blue-600 px-2 py-0.5 rounded"><?=$contribLabels[$ci]?></span>
                      <?php endif; endforeach; ?>
                    </div>
                    <?php endif; ?>
                  </div>
                  <div class="text-xs text-gray-400 font-mono">Author <?=$idx+1?></div>
                </div>
              </div>
              <?php endforeach; ?>
            </div>
            <?php endif; ?>
          </div>
        </div>

        <!-- 4. EDITORIAL -->
        <div class="sec-card">
          <div class="sec-hdr" onclick="toggleSec('s4')">
            <div class="sec-hdr-left">
              <div class="sec-icon bg-orange-100"><i class="fas fa-pen-nib text-orange-600"></i></div>
              <div>
                <div class="sec-title">4. Editorial</div>
                <div class="text-xs text-gray-400 mt-0.5">Cover letter, reviewers, editors</div>
              </div>
            </div>
            <?php if(!empty($editorial['cover_letter'])): ?>
            <span class="sec-done bg-green-50 text-green-700"><i class="fas fa-check-circle"></i> Complete</span>
            <?php else: ?>
            <span class="sec-done bg-red-50 text-red-500"><i class="fas fa-circle"></i> Incomplete</span>
            <?php endif; ?>
          </div>
          <div class="sec-body" id="s4">
            <!-- Cover letter -->
            <div class="info-item mb-4">
              <div class="info-label">Cover Letter</div>
              <?php if(!empty($editorial['cover_letter'])): ?>
              <div class="info-value bg-gray-50 rounded-lg p-3 text-sm leading-relaxed border border-gray-100 mt-1" style="max-height:180px;overflow-y:auto">
                <?=nl2br(p($editorial['cover_letter']))?>
              </div>
              <?php else: ?>
              <div class="info-value empty">Not provided</div>
              <?php endif; ?>
            </div>

            <!-- Reviewers -->
            <?php if(!empty($suggested) || !empty($opposed)): ?>
            <div class="info-grid mb-4">
              <?php if(!empty($suggested)): ?>
              <div>
                <div class="info-label text-green-600">✅ Suggested Reviewers (<?=count($suggested)?>)</div>
                <div class="mt-2 space-y-2">
                  <?php foreach($suggested as $r): ?>
                  <div class="bg-green-50 border border-green-100 rounded-lg p-2.5 text-xs">
                    <div class="font-semibold text-gray-700"><?=p($r['name']??'')?></div>
                    <?php if(!empty($r['email'])): ?><div class="text-gray-500"><?=p($r['email'])?></div><?php endif; ?>
                    <?php if(!empty($r['institution'])): ?><div class="text-gray-400"><?=p($r['institution'])?></div><?php endif; ?>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
              <?php endif; ?>
              <?php if(!empty($opposed)): ?>
              <div>
                <div class="info-label text-red-600">🚫 Opposed Reviewers (<?=count($opposed)?>)</div>
                <div class="mt-2 space-y-2">
                  <?php foreach($opposed as $r): ?>
                  <div class="bg-red-50 border border-red-100 rounded-lg p-2.5 text-xs">
                    <div class="font-semibold text-gray-700"><?=p($r['name']??'')?></div>
                    <?php if(!empty($r['email'])): ?><div class="text-gray-500"><?=p($r['email'])?></div><?php endif; ?>
                    <?php if(!empty($r['reason'])): ?><div class="text-gray-400 italic"><?=p($r['reason'])?></div><?php endif; ?>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
              <?php endif; ?>
            </div>
            <?php endif; ?>

            <!-- Other editorial fields -->
            <div class="info-grid">
              <?php foreach(['study_type'=>'Study Type','research_area'=>'Research Area','additional_comments'=>'Additional Comments'] as $field=>$label): ?>
              <?php if(!empty($editorial[$field])): ?>
              <div class="info-item">
                <div class="info-label"><?=$label?></div>
                <div class="info-value"><?=p($editorial[$field])?></div>
              </div>
              <?php endif; ?>
              <?php endforeach; ?>
            </div>
          </div>
        </div>

        <!-- 5. STATEMENTS -->
        <div class="sec-card">
          <div class="sec-hdr" onclick="toggleSec('s5')">
            <div class="sec-hdr-left">
              <div class="sec-icon bg-indigo-100"><i class="fas fa-shield-alt text-indigo-600"></i></div>
              <div>
                <div class="sec-title">5. Statements</div>
                <div class="text-xs text-gray-400 mt-0.5">Conflicts, funding, data availability</div>
              </div>
            </div>
            <?php if(!empty($ss['conflict_of_interest']) && !empty($ss['data_availability_statement'])): ?>
            <span class="sec-done bg-green-50 text-green-700"><i class="fas fa-check-circle"></i> Complete</span>
            <?php else: ?>
            <span class="sec-done bg-red-50 text-red-500"><i class="fas fa-circle"></i> Incomplete</span>
            <?php endif; ?>
          </div>
          <div class="sec-body" id="s5">
            <div class="space-y-4">
              <?php
              $stmtFields = [
                'conflict_of_interest'       => ['Conflict of Interest',       'fas fa-handshake'],
                'data_availability_statement'=> ['Data Availability',          'fas fa-database'],
                'studies_animals'            => ['Studies involving animals',  'fas fa-paw'],
                'studies_humans'             => ['Studies involving humans',   'fas fa-user'],
                'includes_identifiable_data' => ['Identifiable data',          'fas fa-id-card'],
              ];
              foreach($stmtFields as $f=>[$label,$icon]):
                if(empty($ss[$f])) continue;
              ?>
              <div>
                <div class="info-label flex items-center gap-1.5"><i class="<?=$icon?> text-xs text-gray-400"></i> <?=$label?></div>
                <div class="info-value mt-1 text-sm leading-relaxed">
                  <?=ucfirst(str_replace(['_','none','exists'],['  ','No conflicts declared','Exists'],$ss[$f]))?>
                </div>
                <?php
                $detailMap = ['conflict_of_interest'=>'conflict_details','data_availability_statement'=>'data_details'];
                $dk = $detailMap[$f] ?? '';
                if($dk && !empty($ss[$dk])): ?>
                <div class="bg-gray-50 rounded-lg p-3 mt-1 text-sm text-gray-600 border border-gray-100"><?=nl2br(p($ss[$dk]))?></div>
                <?php endif; ?>
              </div>
              <?php endforeach; ?>

              <!-- Funders -->
              <?php if(!empty($funders)): ?>
              <div>
                <div class="info-label">Funding Sources (<?=count($funders)?>)</div>
                <div class="space-y-2 mt-1">
                  <?php foreach($funders as $f): ?>
                  <div class="bg-yellow-50 border border-yellow-100 rounded-lg p-2.5 text-xs">
                    <div class="font-semibold text-gray-700"><?=p($f['name']??'')?></div>
                    <?php if(!empty($f['awards'])): ?>
                    <div class="text-gray-500 mt-0.5">Award IDs: <?=p(implode(', ',(array)$f['awards']))?></div>
                    <?php endif; ?>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- 6. PAYMENT -->
        <div class="sec-card">
          <div class="sec-hdr" onclick="toggleSec('s6')">
            <div class="sec-hdr-left">
              <div class="sec-icon bg-green-100"><i class="fas fa-credit-card text-green-600"></i></div>
              <div>
                <div class="sec-title">6. Payment</div>
                <div class="text-xs text-gray-400 mt-0.5">Billing details, fees</div>
              </div>
            </div>
            <?php if(!empty($pay['address']) && !empty($pay['fee_agreed'])): ?>
            <span class="sec-done bg-green-50 text-green-700"><i class="fas fa-check-circle"></i> Complete</span>
            <?php else: ?>
            <span class="sec-done bg-red-50 text-red-500"><i class="fas fa-circle"></i> Incomplete</span>
            <?php endif; ?>
          </div>
          <div class="sec-body" id="s6">
            <?php if(empty($pay)): ?>
            <div class="text-gray-400 text-sm italic text-center py-4">Payment not filled</div>
            <?php else: ?>
            <div class="info-grid mb-4">
              <div class="info-item">
                <div class="info-label">Invoice Type</div>
                <div class="info-value"><?=ucfirst(p($pay['invoice_type']??'—'))?></div>
              </div>
              <div class="info-item">
                <div class="info-label">Billing Email</div>
                <div class="info-value"><?=p($pay['billing_email']??'—')?></div>
              </div>
              <div class="info-item">
                <div class="info-label">Address</div>
                <div class="info-value"><?=nl2br(p($pay['address']??'—'))?></div>
              </div>
              <div class="info-item">
                <div class="info-label">City / ZIP / Country</div>
                <div class="info-value">
                  <?=p(implode(', ', array_filter([$pay['city']??null,$pay['zip_code']??null,$pay['country_region']??null])))?>
                </div>
              </div>
              <?php if(!empty($pay['billing_reference'])): ?>
              <div class="info-item">
                <div class="info-label">Billing Reference</div>
                <div class="info-value"><?=p($pay['billing_reference'])?></div>
              </div>
              <?php endif; ?>
              <div class="info-item">
                <div class="info-label">Fee Agreement</div>
                <div class="info-value"><?=$pay['fee_agreed']?'✅ Agreed':'❌ Not agreed'?></div>
              </div>
            </div>
            <?php if(!empty($discounts)): ?>
            <div>
              <div class="info-label">Discount Codes</div>
              <div class="flex flex-wrap gap-2 mt-1">
                <?php foreach($discounts as $d): ?>
                <span class="bg-purple-50 text-purple-700 border border-purple-100 px-2.5 py-1 rounded text-xs font-mono font-semibold">
                  <?=p($d)?>
                </span>
                <?php endforeach; ?>
              </div>
            </div>
            <?php endif; ?>
            <div class="mt-4 bg-teal-50 border border-teal-100 rounded-xl p-4">
              <div class="flex items-center justify-between">
                <span class="text-sm font-semibold text-teal-700">Total Preliminary Fee</span>
                <span class="text-xl font-bold text-teal-700"><?=$fee?> CHF</span>
              </div>
              <div class="text-xs text-teal-500 mt-1">Payment due after acceptance</div>
            </div>
            <?php endif; ?>
          </div>
        </div>

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

      <!-- ── RIGHT COLUMN (sidebar) ─────────────────────── -->
      <div class="space-y-5">

        <!-- Submission meta card -->
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
          <div class="bg-gray-50 px-4 py-3 border-b border-gray-100">
            <div class="text-xs font-semibold text-gray-500 uppercase tracking-wide">Submission Info</div>
          </div>
          <div class="p-4 space-y-3">
            <div>
              <div class="text-xs text-gray-400 font-medium uppercase tracking-wide mb-1">Submission ID</div>
              <div class="font-mono text-sm font-bold text-gray-700">#<?=$sid?></div>
            </div>
            <div>
              <div class="text-xs text-gray-400 font-medium uppercase tracking-wide mb-1">Current Status</div>
              <div class="status-pill sp-<?=str_replace(' ','_',$status)?>">
                <?=ucfirst(str_replace('_',' ',$status))?>
              </div>
            </div>
            <div>
              <div class="text-xs text-gray-400 font-medium uppercase tracking-wide mb-1">Created</div>
              <div class="text-sm text-gray-700 font-medium"><?=date('d M Y, H:i',strtotime($sub['created_at']))?></div>
            </div>
            <div>
              <div class="text-xs text-gray-400 font-medium uppercase tracking-wide mb-1">Last Updated</div>
              <div class="text-sm text-gray-700 font-medium"><?=date('d M Y, H:i',strtotime($sub['updated_at']))?></div>
            </div>
          </div>
        </div>

        <!-- Change Status -->
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
          <div class="bg-gray-50 px-4 py-3 border-b border-gray-100">
            <div class="text-xs font-semibold text-gray-500 uppercase tracking-wide">Change Status</div>
          </div>
          <div class="p-4">
            <form method="POST">
              <select name="new_status"
                      class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 mb-3 focus:outline-none focus:ring-2 focus:ring-blue-500">
                <?php foreach(['draft'=>'Draft','submitted'=>'Submitted','under_review'=>'Under Review','accepted'=>'Accepted','rejected'=>'Rejected'] as $sv=>$sl): ?>
                <option value="<?=$sv?>" <?=$status===$sv?'selected':''?>><?=$sl?></option>
                <?php endforeach; ?>
              </select>
              <button type="submit" name="update_status"
                      class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg text-sm font-semibold transition">
                Update Status
              </button>
            </form>
          </div>
        </div>

        <!-- Submitting author -->
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm overflow:hidden">
          <div class="bg-gray-50 px-4 py-3 border-b border-gray-100">
            <div class="text-xs font-semibold text-gray-500 uppercase tracking-wide">Submitting Author</div>
          </div>
          <div class="p-4">
            <div class="flex items-center gap-3 mb-3">
              <div class="w-10 h-10 rounded-full bg-blue-100 text-blue-700 flex items-center justify-center font-bold text-sm flex-shrink-0">
                <?=strtoupper(substr($sub['first_name']??'M',0,1).substr($sub['last_name']??'A',0,1))?>
              </div>
              <div>
                <div class="font-semibold text-gray-800 text-sm"><?=p($fullName)?></div>
                <div class="text-xs text-gray-400">User ID #<?=$sub['user_id']?></div>
              </div>
            </div>
            <div class="space-y-1.5 text-xs text-gray-500">
              <div><i class="fas fa-envelope text-gray-300 w-4"></i> <?=p($sub['email']??'—')?></div>
              <?php if(!empty($sub['institutional_email'])): ?>
              <div><i class="fas fa-university text-gray-300 w-4"></i> <?=p($sub['institutional_email'])?></div>
              <?php endif; ?>
              <?php if(!empty($sub['phone_number'])): ?>
              <div><i class="fas fa-phone text-gray-300 w-4"></i> <?=p($sub['phone_number'])?></div>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- Quick links -->
        <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-4">
          <div class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">Quick Links</div>
          <div class="space-y-2">
            <a href="../submit.php?id=<?=$sid?>" target="_blank"
               class="flex items-center gap-2 text-sm text-blue-600 hover:text-blue-700 transition">
              <i class="fas fa-external-link-alt text-xs"></i> Open submission form
            </a>
            <a href="submissions.php" class="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 transition">
              <i class="fas fa-list text-xs"></i> All submissions
            </a>
            <?php if(!empty($sub['user_id'])): ?>
            <a href="user_view.php?id=<?=$sub['user_id']?>" class="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 transition">
              <i class="fas fa-user text-xs"></i> View author profile
            </a>
            <?php endif; ?>
          </div>
        </div>

      </div><!-- /right column -->
    </div>
  </main>
</div>

<script>
function toggleMobileSidebar(){ document.getElementById('sidebar')?.classList.toggle('mobile-open'); }
let sc=false;
function toggleSidebar(){
  sc=!sc;
  document.getElementById('sidebar')?.classList.toggle('collapsed',sc);
  document.getElementById('content')?.classList.toggle('collapsed-sidebar',sc);
}
document.getElementById('darkModeToggle').addEventListener('click',function(){
  document.body.classList.toggle('dark');
  this.querySelector('i').classList.toggle('fa-moon');
  this.querySelector('i').classList.toggle('fa-sun');
  localStorage.setItem('darkMode',document.body.classList.contains('dark')?'enabled':'disabled');
});
if(localStorage.getItem('darkMode')==='enabled'){
  document.body.classList.add('dark');
  document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon','fa-sun');
}
function toggleSec(id){
  const el=document.getElementById(id);
  if(!el)return;
  el.style.display=el.style.display==='none'?'':'none';
}
</script>
</body>
</html>