<?php
// reviewer/view_article.php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

$config_paths = array(
    __DIR__ . '/config/db.php',
    __DIR__ . '/../config/db.php',
    __DIR__ . '/../../common/db.php',
    __DIR__ . '/../../common/journal_config_new.php',
);
foreach ($config_paths as $path) {
    if (file_exists($path)) { require_once $path; break; }
}

if (function_exists('startSession')) {
    startSession();
} elseif (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (function_exists('db')) $pdo = db();
if (!isset($pdo) || !($pdo instanceof PDO)) {
    die('<div style="color:red;padding:20px">Database connection error.</div>');
}

// ── Auth guard ────────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    header('Location: /reviewer/login.php?redirect=reviewer/view_article.php');
    exit;
}

$user_id = (int)$_SESSION['user_id'];

if (function_exists('getCurrentUser')) {
    $user = getCurrentUser();
} else {
    $_u = $pdo->prepare("SELECT * FROM users WHERE user_id = ? LIMIT 1");
    $_u->execute([$user_id]);
    $user = $_u->fetch(PDO::FETCH_ASSOC);
}

if (!$user || !in_array($user['role'] ?? '', ['reviewer', 'both', 'editor'])) {
    header('Location: /reviewer/login.php');
    exit;
}

// ── Sidebar variables ─────────────────────────────────────────
$full_name    = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
$display_name = $full_name ?: ($user['username'] ?? 'Reviewer');
$user_initial = strtoupper(substr($user['first_name'] ?? 'R', 0, 1));
$showAuthorLink = in_array($user['role'] ?? '', ['author', 'both']);

// Fetch reviewer record for sidebar stats
$_rv = $pdo->prepare("SELECT * FROM reviewers WHERE user_id = ? LIMIT 1");
$_rv->execute([$user_id]);
$reviewer = $_rv->fetch(PDO::FETCH_ASSOC);

$error_message   = $success_message = null;
$submission      = null;
$assignment      = null;
$existing_review = null;
$keywords_list   = array();
$submission_files = array();
$file_url        = null;

$assignment_id  = intval($_GET['assignment_id'] ?? 0);
$submission_id  = intval($_GET['submission_id'] ?? 0);

if (!$assignment_id && !$submission_id) {
    header('Location: dashboard.php');
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT id FROM reviewers WHERE user_id = ? LIMIT 1");
    $stmt->execute([$user_id]);
    $rev = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$rev) { header('Location: dashboard.php'); exit; }
    $reviewer_id = (int)$rev['id'];

    if ($assignment_id) {
        $stmt = $pdo->prepare("SELECT * FROM review_assignments WHERE id = ? AND reviewer_id = ? LIMIT 1");
        $stmt->execute([$assignment_id, $reviewer_id]);
    } else {
        $stmt = $pdo->prepare("SELECT * FROM review_assignments WHERE submission_id = ? AND reviewer_id = ? LIMIT 1");
        $stmt->execute([$submission_id, $reviewer_id]);
    }
    $assignment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$assignment) { header('Location: dashboard.php'); exit; }
    $submission_id = (int)$assignment['submission_id'];
    $assignment_id = (int)$assignment['id'];

    $stmt = $pdo->prepare("
        SELECT s.submission_id, s.tracking_code, s.submitted_at, s.status,
               mi.article_title AS title, mi.running_title, mi.abstract,
               j.name AS journal_name,
               u.email AS author_email, u.first_name AS author_first, u.last_name AS author_last
        FROM submissions s
        LEFT JOIN manuscript_info mi ON s.submission_id = mi.submission_id
        LEFT JOIN journals j         ON s.journal_id    = j.journal_id
        LEFT JOIN users u            ON s.user_id       = u.user_id
        WHERE s.submission_id = ?
    ");
    $stmt->execute([$submission_id]);
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$submission) throw new Exception("Submission not found.");

    // Keywords
    try {
        $kw_stmt = $pdo->prepare("
            SELECT k.keyword FROM submission_keywords sk
            JOIN keywords k ON sk.keyword_id = k.keyword_id
            WHERE sk.submission_id = ? ORDER BY sk.display_order ASC
        ");
        $kw_stmt->execute([$submission_id]);
        $keywords_list = $kw_stmt->fetchAll(PDO::FETCH_COLUMN);
    } catch (Exception $e) { $keywords_list = array(); }

    // ── Manuscript files — fetch ALL files visible to reviewer ──
    try {
        $file_stmt = $pdo->prepare("
            SELECT file_id, stored_path, file_type, original_name, file_size_kb, uploaded_at
            FROM submission_files
            WHERE submission_id = ?
              AND file_type IN ('manuscript_pdf', 'manuscript', 'figure', 'supplementary')
            ORDER BY
              FIELD(file_type, 'manuscript_pdf', 'manuscript', 'figure', 'supplementary'),
              file_id ASC
        ");
        $file_stmt->execute([$submission_id]);
        $submission_files = $file_stmt->fetchAll(PDO::FETCH_ASSOC);
        // Backward-compat single file variable
        // Files are stored under /author/uploads/ on the server
        $file_url = !empty($submission_files[0])
            ? '/author/uploads/' . ltrim($submission_files[0]['stored_path'], '/')
            : null;
    } catch (Exception $e) {
        $submission_files = array();
        $file_url = null;
    }

    // Reviewer details
    $rv_stmt = $pdo->prepare("SELECT email, first_name, last_name FROM users WHERE user_id = ?");
    $rv_stmt->execute([$user_id]);
    $rv_details    = $rv_stmt->fetch(PDO::FETCH_ASSOC);
    $reviewer_email = $rv_details['email'] ?? '';
    $reviewer_name  = trim(($rv_details['first_name']??'') . ' ' . ($rv_details['last_name']??'')) ?: 'Reviewer';

    // Existing review
    $stmt = $pdo->prepare("SELECT * FROM reviews WHERE submission_id = ? AND reviewer_id = ? LIMIT 1");
    $stmt->execute([$submission_id, $reviewer_id]);
    $existing_review = $stmt->fetch(PDO::FETCH_ASSOC);

    // ── POST: submit review ───────────────────────────────────
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $required = array('originality','presentation','applicability','overall_status','strengths','weaknesses','suggestions','recommendation');
        $missing  = array_filter($required, function($f){ return empty($_POST[$f]); });
        if (!empty($missing)) {
            throw new Exception("Please fill all required fields: " . implode(', ', array_map('ucfirst', $missing)));
        }
        foreach (array('strengths','weaknesses','suggestions') as $field) {
            $wc = str_word_count(trim($_POST[$field]));
            if ($wc < 75) throw new Exception(ucfirst($field) . " must be at least 75 words (current: {$wc} words).");
        }

        $uploaded_file_path = null;
        if (isset($_FILES['review_file']) && $_FILES['review_file']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['review_file'];
            if ($file['size'] > 10 * 1024 * 1024 || $file['size'] === 0) throw new Exception("Review file must be under 10 MB.");
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime  = finfo_file($finfo, $file['tmp_name']);
            finfo_close($finfo);
            $allowed_mimes = array(
                'application/pdf' => 'pdf',
                'application/msword' => 'doc',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
                'application/rtf' => 'rtf', 'text/rtf' => 'rtf',
            );
            if (!array_key_exists($mime, $allowed_mimes)) throw new Exception("Only PDF, DOC, DOCX, RTF files are allowed.");
            $ext      = $allowed_mimes[$mime];
            $new_name = 'review_' . $submission_id . '_' . $reviewer_id . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
            $upload_dir = __DIR__ . '/uploads/reviews/';
            if (!is_dir($upload_dir)) @mkdir($upload_dir, 0755, true);
            if (move_uploaded_file($file['tmp_name'], $upload_dir . $new_name)) {
                $uploaded_file_path = '/reviewer/uploads/reviews/' . $new_name;
            } else {
                throw new Exception("File upload failed.");
            }
        }

        $pdo->beginTransaction();
        try {
            $comments_editor = $_POST['comments_editor'] ?? '';
            if ($existing_review) {
                $pdo->prepare("
                    UPDATE reviews SET originality=?,presentation=?,applicability=?,overall_status=?,
                    strengths=?,weaknesses=?,suggestions=?,recommendation=?,comments=?,review_file=?,reviewed_at=NOW()
                    WHERE id=?
                ")->execute(array(
                    $_POST['originality'], $_POST['presentation'], $_POST['applicability'], $_POST['overall_status'],
                    $_POST['strengths'], $_POST['weaknesses'], $_POST['suggestions'], $_POST['recommendation'],
                    $comments_editor, $uploaded_file_path ?? $existing_review['review_file'], $existing_review['id']
                ));
            } else {
                $pdo->prepare("
                    INSERT INTO reviews (submission_id,reviewer_id,originality,presentation,applicability,overall_status,
                    strengths,weaknesses,suggestions,recommendation,comments,review_file,reviewed_at)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW())
                ")->execute(array(
                    $submission_id, $reviewer_id,
                    $_POST['originality'], $_POST['presentation'], $_POST['applicability'], $_POST['overall_status'],
                    $_POST['strengths'], $_POST['weaknesses'], $_POST['suggestions'], $_POST['recommendation'],
                    $comments_editor, $uploaded_file_path
                ));
            }
            try {
                $pdo->prepare("UPDATE review_assignments SET assignment_status='review_submitted',submitted_date=NOW() WHERE id=? AND reviewer_id=?")
                    ->execute([$assignment_id, $reviewer_id]);
            } catch (PDOException $e) {
                $pdo->prepare("UPDATE review_assignments SET assignment_status='review_submitted' WHERE id=? AND reviewer_id=?")
                    ->execute([$assignment_id, $reviewer_id]);
            }
            $assignment['assignment_status'] = 'review_submitted';
            $pdo->commit();
            $success_message = "Your review has been submitted successfully!";
            $stmt = $pdo->prepare("SELECT * FROM reviews WHERE submission_id=? AND reviewer_id=? LIMIT 1");
            $stmt->execute([$submission_id, $reviewer_id]);
            $existing_review = $stmt->fetch(PDO::FETCH_ASSOC);
            try {
                $subject = "Thank You for Completing Your Review — Communeglobal";
                $body    = "<p>Dear {$reviewer_name},</p><p>Thank you for reviewing <strong>" . htmlspecialchars($submission['title'] ?? '') . "</strong>.</p><p><strong>Recommendation:</strong> " . htmlspecialchars($_POST['recommendation']) . "</p><p>Best regards,<br>Communeglobal Editorial Team</p>";
                if (function_exists('sendEmail')) sendEmail($reviewer_email, $reviewer_name, $subject, $body);
                else @mail($reviewer_email, $subject, $body, "Content-type: text/html\r\nFrom: editorial@communeglobal.com");
            } catch (Exception $e) {}
        } catch (Exception $e) { $pdo->rollBack(); throw $e; }
    }

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    $error_message = $e->getMessage();
}

function statusPill($status) {
    $map    = array('request_sent'=>'p-pending','accepted'=>'p-accepted','review_submitted'=>'p-submitted','declined'=>'p-declined','cancelled'=>'p-declined');
    $labels = array('request_sent'=>'Pending','accepted'=>'Accepted','review_submitted'=>'Submitted','declined'=>'Declined','cancelled'=>'Cancelled');
    return array(isset($map[$status]) ? $map[$status] : 'p-closed', isset($labels[$status]) ? $labels[$status] : ucfirst($status));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Review Manuscript — Communeglobal</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Sora:wght@600;700&display=swap" rel="stylesheet">
<style>
body{font-family:'Inter',sans-serif;background:#f8fafc;color:#1e293b}
.font-display{font-family:'Sora',sans-serif}
#sidebar{transition:width .25s ease}
#sidebar.collapsed{width:72px}
#sidebar.collapsed .nav-label,#sidebar.collapsed .sidebar-brand-text,#sidebar.collapsed .sidebar-user-text{display:none}
#sidebar.collapsed .nav-link{justify-content:center;padding-left:0;padding-right:0}
#sidebar.collapsed .nav-icon{margin-right:0}
#main-content{transition:margin-left .25s ease}
.pill{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:600;border:1px solid;white-space:nowrap}
.p-pending{background:#fffbeb;color:#92400e;border-color:#fcd34d}
.p-accepted{background:#eff6ff;color:#1e40af;border-color:#bfdbfe}
.p-submitted{background:#f0fdf4;color:#166534;border-color:#bbf7d0}
.p-declined{background:#fef2f2;color:#991b1b;border-color:#fecaca}
.p-closed{background:#f1f5f9;color:#475569;border-color:#e2e8f0}
.wc-bar{height:3px;background:#e2e8f0;border-radius:2px;margin-top:4px}
.wc-fill{height:100%;border-radius:2px;transition:width .3s,background .3s}
.clamp-3{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
.file-row:hover{background:#f8fafc}
@media(max-width:768px){
  #sidebar{position:fixed;z-index:50;transform:translateX(-100%);width:256px!important}
  #sidebar.mobile-open{transform:translateX(0)}
  #main-content{margin-left:0!important}
  #mobile-overlay{display:none}
  #mobile-overlay.active{display:block}
}
</style>
</head>
<body class="bg-gray-50 min-h-screen">

<div id="mobile-overlay" class="fixed inset-0 bg-black opacity-40 z-40 md:hidden" onclick="closeSidebar()"></div>
<button onclick="openSidebar()" class="fixed top-4 left-4 z-30 md:hidden bg-white border border-gray-200 p-2 rounded-lg shadow-sm text-gray-600">
  <i class="fas fa-bars text-sm"></i>
</button>

<!-- ══ SIDEBAR ════════════════════════════════════════════════ -->
<aside id="sidebar" class="fixed top-0 left-0 h-full w-64 bg-white border-r border-gray-200 flex flex-col z-40 shadow-sm overflow-hidden">
  <div class="flex items-center gap-3 px-5 py-4 border-b border-gray-100">
    <div class="w-9 h-9 bg-blue-600 rounded-xl flex items-center justify-center flex-shrink-0">
      <span class="text-white font-display font-bold text-sm">C</span>
    </div>
    <div class="sidebar-brand-text min-w-0">
      <div class="font-display text-gray-800 text-sm font-bold truncate">Communeglobal</div>
      <div class="text-gray-400 text-xs">Reviewer Portal</div>
    </div>
    <button onclick="toggleSidebar()" class="ml-auto text-gray-400 hover:text-gray-600 p-1 flex-shrink-0">
      <i class="fas fa-bars text-sm"></i>
    </button>
  </div>

  <!-- User info block -->
  <div class="sidebar-user px-4 py-4 border-b border-gray-100">
    <div class="flex items-center gap-3 bg-gray-50 rounded-xl px-3 py-2.5 mb-3">
      <div class="w-9 h-9 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-sm flex-shrink-0">
        <?php echo htmlspecialchars($user_initial); ?>
      </div>
      <div class="sidebar-user-text min-w-0 flex-1">
        <div class="text-gray-800 text-sm font-semibold truncate"><?php echo htmlspecialchars($display_name); ?></div>
        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-700 mt-0.5">Reviewer</span>
      </div>
    </div>
    <?php if ($reviewer): ?>
    <div class="sidebar-user-text grid grid-cols-3 gap-1.5">
      <div class="bg-white border border-gray-200 rounded-lg py-2 px-1 text-center">
        <div class="text-gray-800 text-sm font-bold leading-none"><?php echo (int)($reviewer['total_reviews_completed'] ?? 0); ?></div>
        <div class="text-gray-400 text-xs mt-0.5">Done</div>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg py-2 px-1 text-center">
        <div class="text-gray-800 text-sm font-bold leading-none"><?php echo number_format($reviewer['reviewer_rating'] ?? 0, 1); ?></div>
        <div class="text-gray-400 text-xs mt-0.5">Rating</div>
      </div>
      <div class="bg-white border border-gray-200 rounded-lg py-2 px-1 text-center">
        <?php $avail = isset($reviewer['is_available']) ? $reviewer['is_available'] : 0; ?>
        <div class="text-sm font-bold leading-none <?php echo $avail ? 'text-emerald-600' : 'text-red-500'; ?>">
          <?php echo $avail ? 'Yes' : 'No'; ?>
        </div>
        <div class="text-gray-400 text-xs mt-0.5">Avail</div>
      </div>
    </div>
    <?php endif; ?>
  </div>

  <!-- Nav items -->
  <nav class="flex-1 px-3 py-4 overflow-y-auto space-y-0.5">
    <?php
    $navItems = array(
      array('href'=>'dashboard.php',                         'icon'=>'fa-clipboard-list', 'label'=>'My Reviews'),
      array('href'=>'dashboard.php?section=profile',         'icon'=>'fa-user-circle',    'label'=>'My Profile'),
      array('href'=>'dashboard.php?section=change_password', 'icon'=>'fa-key',            'label'=>'Change Password'),
      array('href'=>'dashboard.php?section=raise_ticket',    'icon'=>'fa-headset',        'label'=>'Raise a Ticket'),
      array('href'=>'dashboard.php?section=tickets',         'icon'=>'fa-ticket-alt',     'label'=>'My Tickets'),
      array('href'=>'dashboard.php?section=certificate',     'icon'=>'fa-certificate',    'label'=>'Certificates'),
      array('href'=>'dashboard.php?section=reviewer_profiles','icon'=>'fa-id-badge',      'label'=>'Reviewer Profiles'),
    );
    foreach ($navItems as $nav): ?>
    <a href="<?php echo $nav['href']; ?>"
       class="nav-link flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-gray-600 hover:bg-gray-100 hover:text-gray-900 border-l-4 border-transparent transition-all">
      <i class="nav-icon fas <?php echo $nav['icon']; ?> w-4 text-center text-gray-400 flex-shrink-0"></i>
      <span class="nav-label"><?php echo $nav['label']; ?></span>
    </a>
    <?php endforeach; ?>
  </nav>

  <div class="px-3 py-4 border-t border-gray-100">
    <a href="logout.php" class="nav-link flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm text-gray-500 hover:bg-red-50 hover:text-red-600 transition-all border-l-4 border-transparent">
      <i class="nav-icon fas fa-sign-out-alt w-4 text-center flex-shrink-0"></i>
      <span class="nav-label">Sign Out</span>
    </a>
  </div>
</aside>

<!-- ══ MAIN ══════════════════════════════════════════════════ -->
<div id="main-content" class="ml-64 min-h-screen flex flex-col">
  <header class="bg-white border-b border-gray-200 px-6 py-3.5 flex items-center justify-between sticky top-0 z-20 shadow-sm">
    <div class="flex items-center gap-3">
      <button onclick="toggleSidebar()" class="hidden md:flex text-gray-400 hover:text-gray-600 p-1.5 rounded-lg hover:bg-gray-100">
        <i class="fas fa-bars text-sm"></i>
      </button>
      <div>
        <h1 class="font-display text-base font-bold text-gray-800">
          Review Manuscript
          <?php if (!empty($submission['tracking_code'])): ?>
          <span class="text-gray-400 font-normal text-sm">#<?php echo htmlspecialchars($submission['tracking_code']); ?></span>
          <?php endif; ?>
        </h1>
        <p class="text-xs text-gray-400"><?php echo date('l, d F Y'); ?></p>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <?php if ($showAuthorLink): ?>
      <a href="/author/auth_bridge.php" class="hidden sm:flex items-center gap-2 text-xs bg-blue-600 hover:bg-blue-700 text-white px-3.5 py-2 rounded-lg font-medium">
        Switch to Author Dashboard →
      </a>
      <?php endif; ?>
      <div class="flex items-center gap-2 border-l border-gray-200 pl-3">
        <div class="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-xs">
          <?php echo htmlspecialchars($user_initial); ?>
        </div>
        <div class="hidden sm:block">
          <div class="text-xs font-semibold text-gray-700"><?php echo htmlspecialchars($display_name); ?></div>
          <div class="text-xs text-gray-400">Reviewer</div>
        </div>
      </div>
      <a href="dashboard.php" class="text-xs text-gray-500 hover:text-blue-600 border border-gray-200 hover:border-blue-200 px-3 py-2 rounded-lg transition-all">
        <i class="fas fa-arrow-left mr-1"></i> Dashboard
      </a>
      <a href="logout.php" class="flex items-center gap-1.5 text-xs text-gray-500 hover:text-red-600 border border-gray-200 hover:border-red-200 px-3 py-2 rounded-lg transition-all">
        <i class="fas fa-sign-out-alt"></i><span class="hidden sm:inline">Logout</span>
      </a>
    </div>
  </header>

  <main class="flex-1 p-6">

    <?php if ($error_message): ?>
    <div class="mb-5 flex items-start gap-3 bg-red-50 border border-red-200 text-red-700 rounded-xl px-4 py-3 text-sm">
      <i class="fas fa-exclamation-circle flex-shrink-0 mt-0.5"></i>
      <span><?php echo htmlspecialchars($error_message); ?></span>
    </div>
    <?php endif; ?>

    <?php if ($success_message): ?>
    <div class="mb-5 flex items-start gap-3 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-xl px-4 py-3 text-sm">
      <i class="fas fa-check-circle flex-shrink-0 mt-0.5"></i>
      <span><?php echo htmlspecialchars($success_message); ?></span>
    </div>
    <?php endif; ?>

    <?php if (isset($_GET['accepted'])): ?>
    <div class="mb-5 flex items-start gap-3 bg-blue-50 border border-blue-200 text-blue-700 rounded-xl px-4 py-3 text-sm">
      <i class="fas fa-check-circle flex-shrink-0 mt-0.5"></i>
      <span>You have accepted this review. Please download the manuscript below and submit your evaluation.</span>
    </div>
    <?php endif; ?>

    <?php if ($submission): ?>

    <!-- ── Manuscript Info Card ───────────────────────────── -->
    <div class="bg-white rounded-xl border border-slate-200 overflow-hidden mb-6 max-w-4xl">
      <div class="p-6">

        <!-- Title + status pill -->
        <?php $pill = statusPill($assignment['assignment_status'] ?? ''); ?>
        <div class="flex items-start justify-between gap-4 mb-5">
          <h2 class="font-display font-bold text-slate-800 text-lg leading-snug flex-1">
            <?php echo htmlspecialchars($submission['title'] ?? 'Untitled Manuscript'); ?>
          </h2>
          <span class="pill <?php echo $pill[0]; ?> flex-shrink-0"><?php echo $pill[1]; ?></span>
        </div>

        <!-- Meta grid -->
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-5 text-sm">
          <div class="bg-slate-50 rounded-lg p-3">
            <div class="text-slate-500 text-xs mb-1">Submitted</div>
            <div class="font-semibold text-slate-700">
              <?php echo !empty($submission['submitted_at']) ? date('M d, Y', strtotime($submission['submitted_at'])) : 'N/A'; ?>
            </div>
          </div>
          <div class="bg-slate-50 rounded-lg p-3">
            <div class="text-slate-500 text-xs mb-1">Review Due</div>
            <div class="font-semibold text-slate-700">
              <?php echo !empty($assignment['review_due_date']) ? date('M d, Y', strtotime($assignment['review_due_date'])) : 'Not set'; ?>
            </div>
          </div>
          <div class="bg-slate-50 rounded-lg p-3">
            <div class="text-slate-500 text-xs mb-1">Round</div>
            <div class="font-semibold text-slate-700">Round <?php echo (int)($assignment['review_round'] ?? 1); ?></div>
          </div>
        </div>

        <hr class="border-slate-100 mb-5">

        <!-- Abstract -->
        <?php if (!empty($submission['abstract'])): ?>
        <div class="text-sm text-slate-700 mb-4 leading-relaxed">
          <strong class="text-slate-600">Abstract:</strong>
          <p class="mt-2 clamp-3" id="abs-short"><?php echo htmlspecialchars($submission['abstract']); ?></p>
          <p class="hidden mt-2" id="abs-full"><?php echo nl2br(htmlspecialchars($submission['abstract'])); ?></p>
          <?php if (strlen($submission['abstract']) > 400): ?>
          <button onclick="toggleAbs()" id="abs-btn" class="text-blue-600 text-xs mt-1 hover:underline">Read more</button>
          <?php endif; ?>
        </div>
        <?php endif; ?>

        <!-- Keywords -->
        <?php if (!empty($keywords_list)): ?>
        <div class="flex flex-wrap gap-2 mb-5">
          <?php foreach ($keywords_list as $kw): ?>
          <span class="bg-slate-100 text-slate-600 text-xs px-3 py-1 rounded-full font-medium">
            <?php echo htmlspecialchars(trim($kw)); ?>
          </span>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- ── Manuscript Files Section ─────────────────────── -->
        <?php
        $typeLabels = array(
            'manuscript_pdf' => array('label'=>'Manuscript PDF',    'icon'=>'fa-file-pdf',   'color'=>'text-red-500',    'bg'=>'bg-red-50',    'badge'=>'bg-red-100 text-red-700'),
            'manuscript'     => array('label'=>'Manuscript (Doc)',  'icon'=>'fa-file-word',  'color'=>'text-blue-500',   'bg'=>'bg-blue-50',   'badge'=>'bg-blue-100 text-blue-700'),
            'figure'         => array('label'=>'Figure',            'icon'=>'fa-file-image', 'color'=>'text-purple-500', 'bg'=>'bg-purple-50', 'badge'=>'bg-purple-100 text-purple-700'),
            'supplementary'  => array('label'=>'Supplementary',     'icon'=>'fa-file-alt',   'color'=>'text-amber-500',  'bg'=>'bg-amber-50',  'badge'=>'bg-amber-100 text-amber-700'),
        );
        ?>

        <?php if (!empty($submission_files)): ?>
        <div class="border border-slate-200 rounded-xl overflow-hidden">

          <!-- Files header -->
          <div class="bg-slate-50 border-b border-slate-200 px-4 py-3 flex items-center gap-2">
            <i class="fas fa-folder-open text-slate-500 text-sm"></i>
            <span class="text-sm font-semibold text-slate-700">Manuscript Files</span>
            <span class="ml-2 text-xs bg-blue-100 text-blue-700 font-semibold px-2 py-0.5 rounded-full">
              <?php echo count($submission_files); ?> file<?php echo count($submission_files) !== 1 ? 's' : ''; ?>
            </span>
            <p class="ml-auto text-xs text-slate-400 hidden sm:block">
              Download all files before starting your review
            </p>
          </div>

          <!-- File rows -->
          <div class="divide-y divide-slate-100">
            <?php foreach ($submission_files as $sf):
              $ft      = $sf['file_type'] ?? 'manuscript';
              $meta    = isset($typeLabels[$ft]) ? $typeLabels[$ft] : array('label'=>ucfirst(str_replace('_',' ',$ft)),'icon'=>'fa-file','color'=>'text-slate-500','bg'=>'bg-slate-50','badge'=>'bg-slate-100 text-slate-600');
              $dl_url  = '/author/uploads/' . ltrim($sf['stored_path'], '/');
              $size_kb = (int)($sf['file_size_kb'] ?? 0);
              $size_str = $size_kb >= 1024
                ? number_format($size_kb / 1024, 1) . ' MB'
                : ($size_kb > 0 ? $size_kb . ' KB' : '');
              $orig_name = $sf['original_name'] ?? basename($sf['stored_path'] ?? '');
            ?>
            <div class="file-row flex items-center gap-4 px-4 py-3.5 transition-colors">

              <!-- File type icon -->
              <div class="w-11 h-11 <?php echo $meta['bg']; ?> rounded-xl flex items-center justify-center flex-shrink-0 border border-slate-100">
                <i class="fas <?php echo $meta['icon']; ?> <?php echo $meta['color']; ?> text-xl"></i>
              </div>

              <!-- File info -->
              <div class="flex-1 min-w-0">
                <div class="text-sm font-semibold text-slate-800 truncate" title="<?php echo htmlspecialchars($orig_name); ?>">
                  <?php echo htmlspecialchars($orig_name); ?>
                </div>
                <div class="flex flex-wrap items-center gap-x-2 gap-y-1 mt-1">
                  <span class="text-xs font-medium px-2 py-0.5 rounded-full <?php echo $meta['badge']; ?>">
                    <?php echo $meta['label']; ?>
                  </span>
                  <?php if ($size_str): ?>
                  <span class="text-xs text-slate-400"><?php echo $size_str; ?></span>
                  <?php endif; ?>
                  <?php if (!empty($sf['uploaded_at'])): ?>
                  <span class="text-xs text-slate-400">
                    <i class="fas fa-clock mr-0.5"></i><?php echo date('M d, Y', strtotime($sf['uploaded_at'])); ?>
                  </span>
                  <?php endif; ?>
                </div>
              </div>

              <!-- Download button -->
              <a href="<?php echo htmlspecialchars($dl_url); ?>"
                 target="_blank"
                 download="<?php echo htmlspecialchars($orig_name); ?>"
                 class="flex-shrink-0 flex items-center gap-2 bg-blue-600 hover:bg-blue-700 active:bg-blue-800 text-white text-xs font-semibold px-4 py-2.5 rounded-lg transition-colors shadow-sm">
                <i class="fas fa-download"></i>
                <span class="hidden sm:inline">Download</span>
              </a>

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

          <!-- Download all footer (only when multiple files) -->
          <?php if (count($submission_files) > 1): ?>
          <div class="bg-slate-50 border-t border-slate-200 px-4 py-3 flex items-center justify-between">
            <p class="text-xs text-slate-500">
              <i class="fas fa-info-circle mr-1 text-blue-400"></i>
              Please review all uploaded files before submitting your evaluation.
            </p>
            <button onclick="downloadAll()" class="inline-flex items-center gap-2 text-xs font-semibold text-blue-600 hover:text-blue-700 border border-blue-200 hover:border-blue-300 bg-white px-3 py-1.5 rounded-lg transition-colors">
              <i class="fas fa-cloud-download-alt"></i> Download All
            </button>
          </div>
          <?php endif; ?>

        </div><!-- /files card -->

        <!-- Store file URLs for JS download-all -->
        <script>
        var allFileUrls = <?php echo json_encode(array_map(function($sf){
            return array(
                'url'  => '/author/uploads/' . ltrim($sf['stored_path'], '/'),
                'name' => $sf['original_name'] ?? basename($sf['stored_path'])
            );
        }, $submission_files)); ?>;
        </script>

        <?php else: ?>
        <!-- No files uploaded -->
        <div class="bg-amber-50 border border-amber-200 rounded-xl p-5 text-center">
          <i class="fas fa-exclamation-triangle text-amber-500 text-2xl mb-2"></i>
          <p class="text-amber-700 text-sm font-medium">No manuscript files have been uploaded yet.</p>
          <p class="text-amber-600 text-xs mt-1">Please contact the editorial office if this is unexpected.</p>
        </div>
        <?php endif; ?>

      </div><!-- /p-6 -->
    </div><!-- /manuscript info card -->


    <!-- ── Review Form ───────────────────────────────────── -->
    <?php if (in_array($assignment['assignment_status'], array('accepted','review_in_progress'))): ?>
    <form method="POST" enctype="multipart/form-data" class="bg-white rounded-xl border border-slate-200 overflow-hidden max-w-4xl">
      <div class="bg-gray-50 border-b border-gray-200 px-6 py-4 flex items-center gap-3">
        <div class="w-9 h-9 bg-blue-100 rounded-xl flex items-center justify-center">
          <i class="fas fa-edit text-blue-600"></i>
        </div>
        <div>
          <h3 class="font-display font-bold text-gray-800">Manuscript Evaluation Form</h3>
          <p class="text-xs text-gray-400">All * fields required — minimum 75 words per comment section</p>
        </div>
      </div>
      <div class="p-6">

        <!-- Score fields -->
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          <?php
          $scoreFields  = array('originality'=>'Originality','presentation'=>'Presentation','applicability'=>'Applicability','overall_status'=>'Overall Status');
          $scoreOptions = array('Outstanding','Excellent','Very Good','Good','Fair','Very Poor');
          foreach ($scoreFields as $name => $label): ?>
          <div>
            <label class="block text-xs font-semibold text-slate-600 mb-1"><?php echo $label; ?> <span class="text-red-500">*</span></label>
            <select name="<?php echo $name; ?>" required class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 bg-white">
              <option value="">Select...</option>
              <?php foreach ($scoreOptions as $opt): ?>
              <option value="<?php echo $opt; ?>" <?php echo (!empty($existing_review[$name]) && $existing_review[$name]===$opt) ? 'selected' : ''; ?>><?php echo $opt; ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <?php endforeach; ?>
        </div>

        <hr class="border-slate-100 mb-6">

        <!-- Comment textareas -->
        <?php foreach (array('strengths'=>'Strengths','weaknesses'=>'Weaknesses','suggestions'=>'Suggestions') as $key => $label): ?>
        <div class="mb-6">
          <label class="block text-xs font-semibold text-slate-600 mb-1">
            <?php echo $label; ?> <span class="text-red-500">*</span>
            <span class="font-normal text-slate-400">(min 75 words)</span>
          </label>
          <textarea name="<?php echo $key; ?>" id="ta-<?php echo $key; ?>" rows="6" required
                    oninput="updateWC('<?php echo $key; ?>',this.value)"
                    placeholder="Provide detailed and constructive feedback..."
                    class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 resize-none"><?php echo htmlspecialchars($existing_review[$key] ?? ''); ?></textarea>
          <div class="wc-bar"><div class="wc-fill" id="wc-<?php echo $key; ?>" style="width:0%;background:#ef4444"></div></div>
          <p class="text-xs mt-1" id="wl-<?php echo $key; ?>" style="color:#ef4444">0 / 75 words</p>
        </div>
        <?php endforeach; ?>

        <!-- Editor comments -->
        <div class="mb-6">
          <label class="block text-xs font-semibold text-slate-600 mb-1">
            Comments to Editor <span class="font-normal text-slate-400">(optional — confidential)</span>
          </label>
          <textarea name="comments_editor" rows="4" placeholder="Private notes for the editor..."
                    class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 resize-none"><?php echo htmlspecialchars($existing_review['comments'] ?? ''); ?></textarea>
        </div>

        <!-- Upload annotated file -->
        <div class="mb-6">
          <label class="block text-xs font-semibold text-slate-600 mb-1">
            Upload Annotated File <span class="font-normal text-slate-400">(optional — PDF, DOC, DOCX, RTF, max 10 MB)</span>
          </label>
          <input type="file" name="review_file" accept=".pdf,.doc,.docx,.rtf"
                 class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm file:mr-4 file:py-1 file:px-4 file:rounded-lg file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
          <?php if (!empty($existing_review['review_file'])): ?>
          <p class="text-xs text-slate-500 mt-1">
            <i class="fas fa-paperclip mr-1"></i>
            Previously uploaded: <?php echo htmlspecialchars(basename($existing_review['review_file'])); ?>
          </p>
          <?php endif; ?>
        </div>

        <!-- Final recommendation -->
        <div class="mb-6">
          <label class="block text-xs font-semibold text-slate-600 mb-1">Final Recommendation <span class="text-red-500">*</span></label>
          <select name="recommendation" required class="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:border-blue-400 bg-white">
            <option value="">Select a recommendation...</option>
            <?php foreach (array('Accepted','Accepted with change','Resubmission','Rejected') as $rec): ?>
            <option value="<?php echo $rec; ?>" <?php echo (!empty($existing_review['recommendation']) && $existing_review['recommendation']===$rec) ? 'selected' : ''; ?>>
              <?php echo $rec; ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>

        <!-- Submit row -->
        <div class="flex items-center justify-center gap-4 pt-4 border-t border-slate-100">
          <a href="dashboard.php" class="px-8 py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg font-semibold text-sm transition-colors">
            <i class="fas fa-arrow-left mr-2"></i> Back
          </a>
          <button type="submit" class="px-10 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-bold text-sm transition-colors">
            <i class="fas fa-paper-plane mr-2"></i> Submit Review
          </button>
        </div>

      </div>
    </form>

    <!-- ── Review Already Submitted ──────────────────────── -->
    <?php elseif ($assignment['assignment_status'] === 'review_submitted'): ?>
    <div class="bg-white rounded-xl border border-slate-200 overflow-hidden max-w-4xl">
      <div class="bg-emerald-600 text-white p-10 text-center">
        <i class="fas fa-check-circle text-7xl mb-4 opacity-90"></i>
        <h3 class="font-display text-3xl font-bold">Review Submitted!</h3>
        <p class="text-emerald-100 text-lg mt-2">Thank you for your valuable contribution.</p>
        <?php if (!empty($existing_review['reviewed_at'])): ?>
        <p class="text-emerald-200 text-sm mt-2">Submitted on <?php echo date('F d, Y \a\t g:i A', strtotime($existing_review['reviewed_at'])); ?></p>
        <?php endif; ?>
      </div>
      <div class="p-8">
        <h4 class="font-display font-bold text-gray-800 text-xl mb-6">Your Review Summary</h4>
        <div class="grid md:grid-cols-2 gap-8 mb-8">
          <div class="bg-gray-50 rounded-xl border border-gray-200 p-6">
            <h5 class="font-semibold text-gray-700 mb-4 flex items-center gap-2">
              <i class="fas fa-star text-amber-400"></i> Evaluation Scores
            </h5>
            <dl class="space-y-3 text-sm">
              <?php foreach (array('originality'=>'Originality','presentation'=>'Presentation','applicability'=>'Applicability','overall_status'=>'Overall Status') as $f => $lbl): ?>
              <div class="flex justify-between items-center py-1 border-b border-gray-100 last:border-0">
                <dt class="text-gray-500"><?php echo $lbl; ?></dt>
                <dd class="font-semibold text-gray-800"><?php echo htmlspecialchars($existing_review[$f] ?? '—'); ?></dd>
              </div>
              <?php endforeach; ?>
            </dl>
          </div>
          <div class="bg-blue-50 border border-blue-200 rounded-xl p-6 flex flex-col items-center justify-center text-center">
            <h5 class="font-semibold text-blue-800 mb-4">Final Recommendation</h5>
            <?php
            $rec  = $existing_review['recommendation'] ?? '';
            $rc   = array('Accepted'=>'bg-emerald-600','Accepted with change'=>'bg-blue-600','Resubmission'=>'bg-amber-500','Rejected'=>'bg-red-600');
            $rcls = isset($rc[$rec]) ? $rc[$rec] : 'bg-gray-600';
            ?>
            <span class="inline-block px-8 py-4 rounded-full text-xl font-bold text-white <?php echo $rcls; ?>">
              <?php echo htmlspecialchars($rec ?: 'Not specified'); ?>
            </span>
          </div>
        </div>

        <?php if (!empty($existing_review['review_file'])): ?>
        <div class="bg-indigo-50 border border-indigo-200 rounded-xl p-6 text-center mb-6">
          <i class="fas fa-paperclip text-3xl text-indigo-600 mb-3"></i>
          <p class="font-semibold text-indigo-800 mb-3">You attached a review file</p>
          <a href="<?php echo htmlspecialchars($existing_review['review_file']); ?>" target="_blank"
             class="inline-flex items-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-lg font-semibold text-sm transition-colors">
            <i class="fas fa-download"></i> Download Attached File
          </a>
        </div>
        <?php endif; ?>

        <div class="text-center">
          <a href="dashboard.php" class="inline-flex items-center gap-3 bg-blue-600 hover:bg-blue-700 text-white px-10 py-4 rounded-xl font-bold text-lg transition-colors">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
          </a>
        </div>
      </div>
    </div>

    <?php else: ?>
    <div class="bg-amber-50 border border-amber-200 rounded-xl p-6 text-amber-800 max-w-2xl">
      <i class="fas fa-info-circle mr-2"></i>
      This assignment has status: <strong><?php echo htmlspecialchars($assignment['assignment_status'] ?? 'unknown'); ?></strong>.
      You can only submit a review after accepting the invitation.
      <div class="mt-3">
        <a href="dashboard.php" class="text-blue-600 hover:underline text-sm">← Back to Dashboard</a>
      </div>
    </div>
    <?php endif; ?>

    <?php endif; // $submission ?>

  </main>
</div>

<script>
// ── Sidebar ──────────────────────────────────────────────────
function toggleSidebar() {
  var sb = document.getElementById('sidebar');
  var mc = document.getElementById('main-content');
  sb.classList.toggle('collapsed');
  mc.style.marginLeft = sb.classList.contains('collapsed') ? '72px' : '256px';
}
function openSidebar() {
  document.getElementById('sidebar').classList.add('mobile-open');
  document.getElementById('mobile-overlay').classList.add('active');
}
function closeSidebar() {
  document.getElementById('sidebar').classList.remove('mobile-open');
  document.getElementById('mobile-overlay').classList.remove('active');
}

// ── Abstract toggle ──────────────────────────────────────────
function toggleAbs() {
  var s = document.getElementById('abs-short');
  var f = document.getElementById('abs-full');
  var b = document.getElementById('abs-btn');
  if (!f) return;
  var open = !f.classList.contains('hidden');
  if (open) { f.classList.add('hidden'); s.classList.remove('hidden'); b.textContent = 'Read more'; }
  else       { f.classList.remove('hidden'); s.classList.add('hidden'); b.textContent = 'Read less'; }
}

// ── Word count bar ───────────────────────────────────────────
function updateWC(field, val) {
  var w   = val.trim().split(/\s+/).filter(function(x){ return x.length > 0; }).length;
  var pct = Math.min(100, Math.round((w / 75) * 100));
  var fill = document.getElementById('wc-' + field);
  var lbl  = document.getElementById('wl-' + field);
  var col  = w >= 75 ? '#10b981' : w >= 40 ? '#f59e0b' : '#ef4444';
  if (fill) { fill.style.width = pct + '%'; fill.style.background = col; }
  if (lbl)  { lbl.textContent = w + ' / 75 words'; lbl.style.color = col; }
}

// ── Download All (sequential anchor clicks with delay) ───────
function downloadAll() {
  if (typeof allFileUrls === 'undefined' || !allFileUrls.length) return;
  allFileUrls.forEach(function(f, i) {
    setTimeout(function() {
      var a = document.createElement('a');
      a.href     = f.url;
      a.download = f.name;
      a.target   = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }, i * 800); // 800 ms gap between each download
  });
}

// ── Init word counts on page load ────────────────────────────
document.addEventListener('DOMContentLoaded', function() {
  ['strengths', 'weaknesses', 'suggestions'].forEach(function(f) {
    var el = document.getElementById('ta-' + f);
    if (el && el.value) updateWC(f, el.value);
  });
});
</script>
</body>
</html>