<?php
// admin/review_assignment.php
// ══════════════════════════════════════════════════════
// Review workflow — assign reviewers, view reviews,
// make editorial decision
// ══════════════════════════════════════════════════════
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set('display_errors', 1);
session_start();

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_role('admin');
require_once __DIR__ . '/include/activity_logger.php';

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

// ── Auto-create tables ────────────────────────────────
foreach ([
    "CREATE TABLE IF NOT EXISTS review_assignments (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        submission_id INT UNSIGNED NOT NULL,
        reviewer_id INT UNSIGNED NOT NULL,
        review_round TINYINT UNSIGNED DEFAULT 1,
        assignment_status ENUM('request_sent','accepted','declined','review_submitted','cancelled') DEFAULT 'request_sent',
        reviewer_type VARCHAR(60) DEFAULT 'anonymous_reviewer_anonymous_author',
        access_key VARCHAR(64) NULL UNIQUE,
        request_sent_date DATETIME NULL,
        response_due_date DATE NULL,
        review_due_date DATE NULL,
        submitted_date DATETIME NULL,
        reviewer_rating DECIMAL(3,2) NULL,
        recommendation VARCHAR(100) NULL,
        created_at DATETIME DEFAULT NOW(),
        KEY idx_sub (submission_id), KEY idx_rev (reviewer_id),
        UNIQUE KEY uq_sub_rev (submission_id, reviewer_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

    "CREATE TABLE IF NOT EXISTS reviews (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        submission_id INT UNSIGNED NOT NULL,
        reviewer_id INT UNSIGNED NOT NULL,
        assignment_id INT UNSIGNED NULL,
        originality VARCHAR(50) NULL,
        presentation VARCHAR(50) NULL,
        applicability VARCHAR(50) NULL,
        overall_status VARCHAR(50) NULL,
        strengths TEXT NULL,
        weaknesses TEXT NULL,
        suggestions TEXT NULL,
        recommendation VARCHAR(100) NULL,
        comments TEXT NULL,
        review_file VARCHAR(500) NULL,
        reviewed_at DATETIME NULL,
        created_at DATETIME DEFAULT NOW(),
        KEY idx_sub (submission_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",

    "CREATE TABLE IF NOT EXISTS editorial_decisions (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        submission_id INT UNSIGNED NOT NULL,
        editor_id INT UNSIGNED NOT NULL,
        based_on_review_id INT UNSIGNED NULL,
        decision ENUM('accepted','accepted_with_changes','resubmit','rejected') NOT NULL,
        due_date DATE NULL,
        review_file TEXT NULL,
        originality VARCHAR(50) NULL, presentation VARCHAR(50) NULL,
        applicability VARCHAR(50) NULL, overall_status VARCHAR(50) NULL,
        strengths TEXT NULL, weaknesses TEXT NULL,
        suggestions TEXT NULL, recommendation TEXT NULL,
        editor_comments TEXT NULL, internal_notes TEXT NULL,
        created_at DATETIME DEFAULT NOW(),
        KEY idx_sub (submission_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4",
] as $sql) {
    try { $pdo->exec($sql); } catch(PDOException $e) {}
}

$msg = ''; $msgType = '';

// ═══════════════════════════════════════════════════════
// POST: ASSIGN EXISTING REVIEWER
// ═══════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_reviewer'])) {
    try {
        $reviewer_id       = (int)$_POST['reviewer_id'];
        $response_due_date = $_POST['response_due_date'] ?? null;
        $review_due_date   = $_POST['review_due_date'] ?? null;
        $reviewer_type     = $_POST['reviewer_type'] ?? 'anonymous_reviewer_anonymous_author';

        if ($reviewer_id <= 0) throw new Exception("Select a reviewer.");

        // Check duplicate
        $chk = $pdo->prepare("SELECT id FROM review_assignments WHERE submission_id=? AND reviewer_id=?");
        $chk->execute([$sid, $reviewer_id]);
        if ($chk->fetch()) throw new Exception("This reviewer is already assigned.");

        // Unique access key
        do {
            $access_key = bin2hex(random_bytes(32));
            $chkKey = $pdo->prepare("SELECT 1 FROM review_assignments WHERE access_key=?");
            $chkKey->execute([$access_key]);
        } while ($chkKey->fetch());

        $pdo->prepare("
            INSERT INTO review_assignments
            (submission_id, reviewer_id, review_round, assignment_status,
             request_sent_date, response_due_date, review_due_date,
             reviewer_type, access_key)
            VALUES (?, ?, 1, 'request_sent', NOW(), ?, ?, ?, ?)
        ")->execute([$sid, $reviewer_id,
            $response_due_date ?: null,
            $review_due_date ?: null,
            $reviewer_type, $access_key]);

        $assignment_id = (int)$pdo->lastInsertId();

        // Update submission status
        $pdo->prepare("UPDATE submissions SET submission_status='under_review', updated_at=NOW() WHERE submission_id=?")
            ->execute([$sid]);

        // Update reviewer last_review_assigned
        $pdo->prepare("UPDATE reviewers SET last_review_assigned=NOW() WHERE id=?")
            ->execute([$reviewer_id]);

        $logger->log($sid, 'reviewer_assigned', "Reviewer ID:{$reviewer_id} assigned",
            ['reviewer_id'=>$reviewer_id,'assignment_id'=>$assignment_id], $_SESSION['user_id']??null);

        $msg = "Reviewer assigned successfully! Assignment ID: $assignment_id";
        $msgType = 'success';

    } catch(Exception $e) {
        $msg = "Error: " . $e->getMessage();
        $msgType = 'error';
    }
}

// ═══════════════════════════════════════════════════════
// POST: RATE REVIEWER
// ═══════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_rating'])) {
    try {
        $reviewer_id = (int)$_POST['reviewer_id'];
        $rating      = (float)$_POST['rating'];
        if ($rating < 1 || $rating > 5) throw new Exception("Rating must be 1-5.");

        $pdo->prepare("
            UPDATE review_assignments SET reviewer_rating=?
            WHERE submission_id=? AND reviewer_id=? AND assignment_status='review_submitted'
        ")->execute([$rating, $sid, $reviewer_id]);

        // Recalculate avg rating
        $avg = $pdo->prepare("SELECT AVG(reviewer_rating), COUNT(*) FROM review_assignments
                              WHERE reviewer_id=? AND reviewer_rating IS NOT NULL");
        $avg->execute([$reviewer_id]);
        [$newAvg, $totalRated] = $avg->fetch(PDO::FETCH_NUM);

        $pdo->prepare("UPDATE reviewers SET reviewer_rating=?, total_reviews_completed=? WHERE id=?")
            ->execute([$newAvg, $totalRated, $reviewer_id]);

        $logger->log($sid, 'reviewer_rated', "Reviewer rated {$rating}/5",
            ['reviewer_id'=>$reviewer_id,'rating'=>$rating], $_SESSION['user_id']??null);

        $msg = "Rating submitted! New average: " . number_format($newAvg, 2) . "/5";
        $msgType = 'success';
    } catch(Exception $e) {
        $msg = "Error: " . $e->getMessage(); $msgType = 'error';
    }
}

// ═══════════════════════════════════════════════════════
// POST: EDITORIAL DECISION
// ═══════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_editorial_decision'])) {
    try {
        $pdo->beginTransaction();

        $decision          = $_POST['editorial_decision'] ?? '';
        $based_on_review_id= !empty($_POST['based_on_review_id']) ? (int)$_POST['based_on_review_id'] : null;
        $due_date          = $_POST['due_date'] ?? null;

        if (empty($decision)) throw new Exception("Select a decision.");

        $pdo->prepare("
            INSERT INTO editorial_decisions
            (submission_id, editor_id, based_on_review_id, decision, due_date,
             originality, presentation, applicability, overall_status,
             strengths, weaknesses, suggestions, recommendation,
             editor_comments, internal_notes)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ")->execute([
            $sid,
            $_SESSION['user_id'] ?? 0,
            $based_on_review_id,
            $decision,
            $due_date,
            $_POST['ed_originality']    ?? null,
            $_POST['ed_presentation']   ?? null,
            $_POST['ed_applicability']  ?? null,
            $_POST['ed_overall_status'] ?? null,
            trim($_POST['ed_strengths']       ?? ''),
            trim($_POST['ed_weaknesses']      ?? ''),
            trim($_POST['ed_suggestions']     ?? ''),
            trim($_POST['ed_recommendation']  ?? ''),
            trim($_POST['ed_editor_comments'] ?? ''),
            trim($_POST['ed_internal_notes']  ?? ''),
        ]);

        // Update submission status
        $statusMap = [
            'accepted'              => 'accepted',
            'accepted_with_changes' => 'accepted_with_changes',
            'resubmit'              => 'resubmit',
            'rejected'              => 'rejected',
        ];
        $newStatus = $statusMap[$decision] ?? 'under_review';
        $pdo->prepare("UPDATE submissions SET submission_status=?, updated_at=NOW() WHERE submission_id=?")
            ->execute([$newStatus, $sid]);

        $logger->log($sid, 'editorial_decision', "Decision: $decision",
            ['decision'=>$decision], $_SESSION['user_id']??null);

        $pdo->commit();
        $msg = "Editorial decision saved! Status → $newStatus";
        $msgType = 'success';

    } catch(Exception $e) {
        $pdo->rollBack();
        $msg = "Error: " . $e->getMessage(); $msgType = 'error';
    }
}

// ═══════════════════════════════════════════════════════
// FETCH DATA
// ═══════════════════════════════════════════════════════

// Submission
$q = $pdo->prepare("
    SELECT s.*, u.first_name, u.last_name, u.email,
           j.name AS journal_name, at.name AS article_type_name,
           sp.name AS specialty_name, mi.article_title
    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
    LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
    WHERE s.submission_id = ?
");
$q->execute([$sid]);
$sub = $q->fetch();
if (!$sub) { header('Location: submissions.php'); exit; }

// All reviewers (role = reviewer or both)
$reviewers = $pdo->query("
    SELECT r.id AS reviewer_id, r.reviewer_rating, r.total_reviews_completed,
           r.total_reviews_declined, r.is_available, r.last_review_assigned,
           r.reviewing_interests, r.reviewer_come_from,
           u.first_name, u.last_name, u.email,
           a.name AS affiliation, a.country
    FROM reviewers r
    JOIN users u ON r.user_id = u.user_id
    LEFT JOIN affiliations a ON a.affiliation_id = u.affiliation_id
    WHERE u.role IN ('reviewer','both') AND u.is_active = 1
    ORDER BY r.reviewer_rating DESC, r.total_reviews_completed DESC
")->fetchAll(PDO::FETCH_ASSOC);

// Suggested reviewers from editorial step
$suggestedRevs = $pdo->prepare("
    SELECT sr.*, u.first_name AS u_fn, u.last_name AS u_ln,
           u.user_id AS linked_user_id_check
    FROM suggested_reviewers sr
    LEFT JOIN users u ON u.user_id = sr.linked_user_id
    WHERE sr.submission_id = ? ORDER BY sr.reviewer_type, sr.display_order
");
$suggestedRevs->execute([$sid]);
$suggestedRevs = $suggestedRevs->fetchAll(PDO::FETCH_ASSOC);

// Assignments
$assignments = $pdo->prepare("
    SELECT ra.*, u.first_name, u.last_name, u.email
    FROM review_assignments ra
    JOIN reviewers rv ON ra.reviewer_id = rv.id
    JOIN users u ON rv.user_id = u.user_id
    WHERE ra.submission_id = ?
    ORDER BY ra.created_at DESC
");
$assignments->execute([$sid]);
$assignments = $assignments->fetchAll(PDO::FETCH_ASSOC);

// Reviews
$reviewsData = $pdo->prepare("
    SELECT r.*, u.first_name, u.last_name, u.email,
           a.name AS affiliation, a.country
    FROM reviews r
    JOIN reviewers rv ON r.reviewer_id = rv.id
    JOIN users u ON rv.user_id = u.user_id
    LEFT JOIN affiliations a ON a.affiliation_id = u.affiliation_id
    WHERE r.submission_id = ?
    ORDER BY r.reviewed_at DESC
");
$reviewsData->execute([$sid]);
$reviewsData = $reviewsData->fetchAll(PDO::FETCH_ASSOC);

// Editorial decisions
$decisions = $pdo->prepare("
    SELECT ed.*, u.first_name AS ed_fn, u.last_name AS ed_ln
    FROM editorial_decisions ed
    JOIN users u ON u.user_id = ed.editor_id
    WHERE ed.submission_id = ?
    ORDER BY ed.created_at DESC
");
$decisions->execute([$sid]);
$decisions = $decisions->fetchAll(PDO::FETCH_ASSOC);

$status   = $sub['submission_status'] ?? 'draft';
$fullName = trim(($sub['first_name']??'').' '.($sub['last_name']??''));

function p($v){ return htmlspecialchars($v??''); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Review Workflow — Submission #<?=$sid?></title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
body{font-family:'Inter',sans-serif}
.sidebar{width:240px;height:100vh;position:fixed;top:0;left:0;background:#1e293b;z-index:100;overflow-y:auto}
.content{margin-left:240px;min-height:100vh;overflow-y:auto}
.tab-btn{padding:8px 16px;border-radius:8px;font-size:13px;font-weight:500;cursor:pointer;border:none;background:transparent;color:#64748b;transition:all .15s}
.tab-btn.active{background:#eff6ff;color:#1d4ed8;font-weight:600}
.reviewer-card{border:1px solid #e2e8f0;border-radius:10px;padding:14px;transition:border-color .15s;cursor:pointer}
.reviewer-card:hover{border-color:#93c5fd;background:#f8faff}
.reviewer-card.selected{border-color:#1d4ed8;background:#eff6ff}
.badge{padding:2px 10px;border-radius:20px;font-size:11px;font-weight:600}
.spinner{display:inline-block;width:14px;height:14px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .6s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
</style>
</head>
<body class="bg-gray-50">

<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content">

<!-- Header -->
<div class="bg-white border-b border-gray-200 px-6 py-4 sticky top-0 z-10 shadow-sm">
  <div class="flex items-center justify-between">
    <div class="flex items-center gap-3">
      <a href="submissions.php" class="text-gray-400 hover:text-gray-600">
        <i class="fas fa-arrow-left"></i>
      </a>
      <div>
        <h1 class="text-lg font-bold text-gray-800">
          Review Workflow — #<?=$sid?>
          <span class="ml-2 badge <?=match($status){
            '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',
            default=>'bg-gray-100 text-gray-600'
          }?>">
            <?=ucfirst(str_replace('_',' ',$status))?>
          </span>
        </h1>
        <p class="text-xs text-gray-400 mt-0.5">
          <?=p($sub['article_title'] ?: 'Untitled')?> · <?=p($fullName)?>
        </p>
      </div>
    </div>
    <div class="flex gap-2">
      <a href="submission_view.php?id=<?=$sid?>"
         class="border border-gray-300 text-gray-600 px-3 py-1.5 rounded-lg text-sm font-medium hover:bg-gray-50">
        <i class="fas fa-eye mr-1"></i> View Submission
      </a>
      <a href="review_assignment.php?id=<?=$sid?>&tab=assign"
         class="bg-blue-600 text-white px-4 py-1.5 rounded-lg text-sm font-semibold hover:bg-blue-700">
        <i class="fas fa-plus mr-1"></i> Add Reviewer
      </a>
    </div>
  </div>
</div>

<?php if($msg): ?>
<div class="mx-6 mt-4 p-3 rounded-lg text-sm font-medium
    <?=$msgType==='success'?'bg-green-50 border border-green-200 text-green-700':'bg-red-50 border border-red-200 text-red-700'?>">
  <?=p($msg)?>
</div>
<?php endif; ?>

<div class="p-6">

<!-- Tabs -->
<div class="flex gap-2 mb-6 bg-white rounded-xl border border-gray-200 p-1.5 w-fit">
  <?php
  $activeTab = $_GET['tab'] ?? 'overview';
  $tabs = ['overview'=>'Overview','assign'=>'Assign Reviewer','reviews'=>'Reviews','decision'=>'Editorial Decision'];
  foreach($tabs as $k=>$label):
  ?>
  <button onclick="switchTab('<?=$k?>')"
          id="tab-btn-<?=$k?>"
          class="tab-btn <?=$activeTab===$k?'active':''?>">
    <?=$label?>
    <?php if($k==='reviews' && !empty($reviewsData)): ?>
    <span class="ml-1 bg-blue-100 text-blue-600 px-1.5 py-0.5 rounded-full text-xs"><?=count($reviewsData)?></span>
    <?php endif; ?>
  </button>
  <?php endforeach; ?>
</div>

<!-- ══════════════════════════════════════
     TAB: OVERVIEW
══════════════════════════════════════ -->
<div id="tab-overview" class="<?=$activeTab==='overview'?'block':'hidden'?>">
  <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">

    <!-- Stat: Assignments -->
    <div class="bg-white rounded-xl border border-gray-200 p-5">
      <div class="text-xs text-gray-400 uppercase tracking-wide mb-1">Assigned Reviewers</div>
      <div class="text-3xl font-bold text-blue-600"><?=count($assignments)?></div>
      <div class="text-xs text-gray-400 mt-1">
        <?=count(array_filter($assignments, fn($a)=>$a['assignment_status']==='review_submitted'))?> submitted
      </div>
    </div>

    <!-- Stat: Reviews -->
    <div class="bg-white rounded-xl border border-gray-200 p-5">
      <div class="text-xs text-gray-400 uppercase tracking-wide mb-1">Reviews Received</div>
      <div class="text-3xl font-bold text-green-600"><?=count($reviewsData)?></div>
      <div class="text-xs text-gray-400 mt-1">Completed reviews</div>
    </div>

    <!-- Stat: Decision -->
    <div class="bg-white rounded-xl border border-gray-200 p-5">
      <div class="text-xs text-gray-400 uppercase tracking-wide mb-1">Editorial Decision</div>
      <?php if(!empty($decisions)): ?>
      <div class="text-lg font-bold <?=match($decisions[0]['decision']){
        'accepted'=>'text-green-600','rejected'=>'text-red-600',
        'resubmit'=>'text-orange-600',default=>'text-blue-600'
      }?>">
        <?=ucfirst(str_replace('_',' ',$decisions[0]['decision']))?>
      </div>
      <div class="text-xs text-gray-400"><?=date('d M Y',strtotime($decisions[0]['created_at']))?></div>
      <?php else: ?>
      <div class="text-lg font-bold text-gray-300">Pending</div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Suggested Reviewers (from editorial step) -->
  <?php if(!empty($suggestedRevs)): ?>
  <div class="bg-white rounded-xl border border-gray-200 overflow-hidden mb-4">
    <div class="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
      <h3 class="font-semibold text-gray-800 flex items-center gap-2">
        <i class="fas fa-user-check text-blue-500"></i>
        Author-Suggested Reviewers
      </h3>
      <span class="text-xs text-gray-400">From editorial step</span>
    </div>
    <div class="divide-y divide-gray-50">
      <?php foreach($suggestedRevs as $sr): ?>
      <div class="px-5 py-3 flex items-center justify-between">
        <div>
          <span class="badge mr-2 <?=$sr['reviewer_type']==='recommended'?'bg-green-100 text-green-700':'bg-red-100 text-red-700'?>">
            <?=$sr['reviewer_type']==='recommended'?'Recommended':'Excluded'?>
          </span>
          <span class="font-medium text-sm text-gray-700">
            <?=p(trim(($sr['first_name']??'').' '.($sr['last_name']??'')))?>
          </span>
          <span class="text-xs text-gray-400 ml-2"><?=p($sr['email']??'')?></span>
          <?php if($sr['affiliation_name']): ?>
          <span class="text-xs text-gray-400 ml-2">· <?=p($sr['affiliation_name'])?></span>
          <?php endif; ?>
        </div>
        <div class="flex items-center gap-2">
          <?php if($sr['linked_user_id']): ?>
          <span class="text-xs text-green-600 font-medium"><i class="fas fa-check-circle"></i> In users table</span>
          <?php endif; ?>
          <?php if($sr['reviewer_type']==='recommended'): ?>
          <button onclick="quickAssign(<?=$sr['linked_user_id']??0?>, '<?=p($sr['first_name'].' '.$sr['last_name'])?>')"
                  class="text-xs bg-blue-600 text-white px-3 py-1 rounded-lg hover:bg-blue-700">
            Assign
          </button>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>

  <!-- Assignments table -->
  <div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <div class="px-5 py-4 border-b border-gray-100">
      <h3 class="font-semibold text-gray-800">Assigned Reviewers</h3>
    </div>
    <?php if(empty($assignments)): ?>
    <div class="text-center py-10 text-gray-400">
      <i class="fas fa-user-plus text-3xl mb-2 opacity-30"></i>
      <p class="text-sm">No reviewers assigned yet</p>
      <button onclick="switchTab('assign')" class="mt-2 text-blue-600 text-sm hover:underline">
        Add reviewer →
      </button>
    </div>
    <?php else: ?>
    <table class="w-full text-sm">
      <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
        <tr>
          <th class="px-5 py-3 text-left">Reviewer</th>
          <th class="px-5 py-3 text-left">Status</th>
          <th class="px-5 py-3 text-left">Review Due</th>
          <th class="px-5 py-3 text-left">Recommendation</th>
          <th class="px-5 py-3 text-left">Rating</th>
          <th class="px-5 py-3 text-left">Actions</th>
        </tr>
      </thead>
      <tbody class="divide-y divide-gray-50">
        <?php foreach($assignments as $a):
          $aName = trim(($a['first_name']??'').' '.($a['last_name']??''));
        ?>
        <tr class="hover:bg-gray-50">
          <td class="px-5 py-3">
            <div class="font-medium text-gray-800"><?=p($aName)?></div>
            <div class="text-xs text-gray-400"><?=p($a['email']??'')?></div>
          </td>
          <td class="px-5 py-3">
            <span class="badge <?=match($a['assignment_status']??''){
              'request_sent'=>'bg-blue-100 text-blue-700',
              'accepted'=>'bg-teal-100 text-teal-700',
              'review_submitted'=>'bg-green-100 text-green-700',
              'declined'=>'bg-red-100 text-red-700',
              default=>'bg-gray-100 text-gray-600'
            }?>">
              <?=ucfirst(str_replace('_',' ',$a['assignment_status']??''))?>
            </span>
          </td>
          <td class="px-5 py-3 text-gray-600">
            <?=$a['review_due_date']?date('d M Y',strtotime($a['review_due_date'])):'—'?>
          </td>
          <td class="px-5 py-3 text-gray-600"><?=p($a['recommendation']??'—')?></td>
          <td class="px-5 py-3">
            <?php if(!is_null($a['reviewer_rating'])): ?>
            <span class="text-yellow-500 font-bold"><?=number_format($a['reviewer_rating'],1)?>/5</span>
            <?php elseif($a['assignment_status']==='review_submitted'): ?>
            <button onclick="openRatingModal(<?=$a['reviewer_id']?>, '<?=p($aName)?>')"
                    class="text-xs bg-yellow-500 text-white px-2 py-1 rounded hover:bg-yellow-600">
              Rate
            </button>
            <?php else: ?>
            <span class="text-gray-300">—</span>
            <?php endif; ?>
          </td>
          <td class="px-5 py-3">
            <div class="flex gap-2">
              <button onclick="sendReminder('<?=p($a['email'])?>', '<?=p($aName)?>')"
                      class="text-xs border border-gray-300 px-2 py-1 rounded hover:bg-gray-50 text-gray-600">
                Remind
              </button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>
</div>

<!-- ══════════════════════════════════════
     TAB: ASSIGN REVIEWER
══════════════════════════════════════ -->
<div id="tab-assign" class="<?=$activeTab==='assign'?'block':'hidden'?>">
  <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    <!-- Filter + Reviewer List -->
    <div class="lg:col-span-2">
      <div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <div class="p-4 border-b border-gray-100 flex gap-3">
          <input type="text" id="reviewerSearch"
                 placeholder="Search by name, email..."
                 class="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                 oninput="filterReviewers()">
          <select id="filterAvailability" onchange="filterReviewers()"
                  class="border border-gray-200 rounded-lg px-3 py-2 text-sm">
            <option value="">All</option>
            <option value="1">Available</option>
          </select>
        </div>
        <div class="divide-y divide-gray-50 max-h-[500px] overflow-y-auto" id="reviewerList">
          <?php foreach($reviewers as $r):
            $rName = trim(($r['first_name']??'').' '.($r['last_name']??''));
            $alreadyAssigned = !empty(array_filter($assignments, fn($a)=>$a['reviewer_id']==$r['reviewer_id']));
          ?>
          <div class="reviewer-item px-4 py-3 hover:bg-gray-50 <?=$alreadyAssigned?'opacity-50':''?>"
               data-name="<?=strtolower($rName)?>"
               data-email="<?=strtolower($r['email']??'')?>"
               data-available="<?=$r['is_available']??0?>">
            <div class="flex items-center justify-between">
              <div class="flex items-center 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">
                  <?=strtoupper(substr($r['first_name']??'R',0,1).substr($r['last_name']??'',0,1))?>
                </div>
                <div>
                  <div class="font-medium text-sm text-gray-800"><?=p($rName)?></div>
                  <div class="text-xs text-gray-400"><?=p($r['email']??'')?></div>
                  <?php if($r['affiliation']): ?>
                  <div class="text-xs text-gray-400"><?=p($r['affiliation'])?><?=$r['country']?', '.p($r['country']):''?></div>
                  <?php endif; ?>
                </div>
              </div>
              <div class="flex items-center gap-3">
                <div class="text-right text-xs text-gray-500">
                  <div class="text-yellow-500 font-bold"><?=number_format((float)($r['reviewer_rating']??0),1)?>/5</div>
                  <div><?=$r['total_reviews_completed']??0?> reviews</div>
                  <div class="<?=$r['is_available']?'text-green-600':'text-red-500'?>">
                    <?=$r['is_available']?'Available':'Busy'?>
                  </div>
                </div>
                <?php if(!$alreadyAssigned): ?>
                <button onclick="selectReviewer(<?=$r['reviewer_id']?>, '<?=p($rName)?>', '<?=p($r['email']??'')?>')"
                        class="bg-blue-600 text-white px-3 py-1.5 rounded-lg text-xs font-medium hover:bg-blue-700">
                  Select
                </button>
                <?php else: ?>
                <span class="text-xs text-green-600 font-medium"><i class="fas fa-check-circle"></i> Assigned</span>
                <?php endif; ?>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>

    <!-- Assignment Form -->
    <div>
      <div class="bg-white rounded-xl border border-gray-200 overflow-hidden sticky top-20">
        <div class="px-5 py-4 border-b border-gray-100">
          <h3 class="font-semibold text-gray-800">Assignment Details</h3>
        </div>
        <form method="POST" class="p-5 space-y-4">
          <input type="hidden" name="assign_reviewer" value="1">
          <input type="hidden" name="reviewer_id" id="selectedReviewerId">

          <!-- Selected reviewer -->
          <div id="selectedReviewerBox" class="hidden bg-blue-50 border border-blue-100 rounded-lg p-3">
            <div class="text-xs text-gray-500 mb-1">Selected Reviewer</div>
            <div class="font-semibold text-gray-800" id="selectedReviewerName">—</div>
            <div class="text-xs text-gray-500" id="selectedReviewerEmail"></div>
          </div>

          <div>
            <label class="block text-xs font-semibold text-gray-600 mb-1">Response Due Date</label>
            <input type="date" name="response_due_date" id="responseDueDate"
                   class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-600 mb-1">Review Due Date</label>
            <input type="date" name="review_due_date" id="reviewDueDate"
                   class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
          </div>
          <div>
            <label class="block text-xs font-semibold text-gray-600 mb-1">Review Type</label>
            <select name="reviewer_type"
                    class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
              <option value="anonymous_reviewer_anonymous_author">Double Blind</option>
              <option value="anonymous_reviewer_known_author">Single Blind</option>
              <option value="open_review">Open Review</option>
            </select>
          </div>
          <button type="submit"
                  class="w-full bg-blue-600 text-white py-2.5 rounded-lg text-sm font-semibold hover:bg-blue-700 disabled:opacity-50"
                  id="assignBtn" disabled>
            Assign Reviewer
          </button>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- ══════════════════════════════════════
     TAB: REVIEWS
══════════════════════════════════════ -->
<div id="tab-reviews" class="<?=$activeTab==='reviews'?'block':'hidden'?>">
  <?php if(empty($reviewsData)): ?>
  <div class="bg-white rounded-xl border border-gray-200 text-center py-12 text-gray-400">
    <i class="fas fa-clipboard-list text-4xl mb-3 opacity-30"></i>
    <p>No reviews submitted yet</p>
    <p class="text-sm mt-1">Reviews will appear here once reviewers submit them</p>
  </div>
  <?php else: ?>
  <div class="space-y-4">
    <?php foreach($reviewsData as $rv):
      $rvName = trim(($rv['first_name']??'').' '.($rv['last_name']??''));
    ?>
    <div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
      <div class="bg-gradient-to-r from-blue-50 to-indigo-50 px-6 py-4 border-b flex justify-between items-center">
        <div>
          <div class="font-semibold text-gray-800"><?=p($rvName)?></div>
          <div class="text-xs text-gray-500"><?=p($rv['email']??'')?> · <?=p($rv['affiliation']??'')?></div>
        </div>
        <div class="text-right">
          <div class="font-bold text-lg <?=str_contains(strtolower($rv['recommendation']??''),'accept')?'text-green-600':'text-orange-600'?>">
            <?=p($rv['recommendation']??'No recommendation')?>
          </div>
          <?php if($rv['reviewed_at']): ?>
          <div class="text-xs text-gray-400"><?=date('d M Y H:i',strtotime($rv['reviewed_at']))?></div>
          <?php endif; ?>
        </div>
      </div>
      <div class="p-6">
        <!-- Scores -->
        <div class="grid grid-cols-4 gap-3 mb-5">
          <?php foreach(['originality'=>'Originality','presentation'=>'Presentation','applicability'=>'Applicability','overall_status'=>'Overall'] as $f=>$l): ?>
          <div class="bg-gray-50 rounded-lg p-3 text-center">
            <div class="text-xs text-gray-400 mb-1"><?=$l?></div>
            <div class="font-semibold text-sm text-gray-800"><?=p($rv[$f]??'N/A')?></div>
          </div>
          <?php endforeach; ?>
        </div>
        <!-- Feedback -->
        <div class="space-y-3">
          <?php foreach(['strengths'=>['Strengths','green'],'weaknesses'=>['Weaknesses','red'],'suggestions'=>['Suggestions','yellow']] as $f=>[$l,$c]): ?>
          <?php if(!empty($rv[$f])): ?>
          <div>
            <div class="text-xs font-semibold text-<?=$c?>-700 mb-1"><?=$l?></div>
            <div class="bg-<?=$c?>-50 border border-<?=$c?>-100 rounded-lg p-3 text-sm text-gray-700 leading-relaxed">
              <?=nl2br(p($rv[$f]))?>
            </div>
          </div>
          <?php endif; ?>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>
</div>

<!-- ══════════════════════════════════════
     TAB: EDITORIAL DECISION
══════════════════════════════════════ -->
<div id="tab-decision" class="<?=$activeTab==='decision'?'block':'hidden'?>">

  <!-- Existing decisions -->
  <?php if(!empty($decisions)): ?>
  <div class="mb-6">
    <h3 class="font-semibold text-gray-700 mb-3">Previous Decisions</h3>
    <?php foreach($decisions as $d): ?>
    <div class="bg-white rounded-xl border border-gray-200 p-5 mb-3 flex justify-between items-start">
      <div>
        <span class="badge <?=match($d['decision']){
          'accepted'=>'bg-green-100 text-green-700',
          'accepted_with_changes'=>'bg-blue-100 text-blue-700',
          'resubmit'=>'bg-orange-100 text-orange-700',
          'rejected'=>'bg-red-100 text-red-700',
          default=>'bg-gray-100 text-gray-600'
        }?> text-sm px-3 py-1">
          <?=ucfirst(str_replace('_',' ',$d['decision']))?>
        </span>
        <?php if(!empty($d['strengths'])): ?>
        <p class="text-sm text-gray-600 mt-2"><?=p(substr($d['strengths'],0,120)).'...'?></p>
        <?php endif; ?>
      </div>
      <div class="text-xs text-gray-400 text-right">
        <div>By <?=p(($d['ed_fn']??'').' '.($d['ed_ln']??''))?></div>
        <div><?=date('d M Y H:i',strtotime($d['created_at']))?></div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <!-- Decision Form -->
  <div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <div class="px-6 py-4 border-b border-gray-100">
      <h3 class="font-semibold text-gray-800">
        <i class="fas fa-gavel text-blue-500 mr-2"></i>New Editorial Decision
      </h3>
    </div>
    <form method="POST" class="p-6 space-y-5">
      <input type="hidden" name="save_editorial_decision" value="1">
      <input type="hidden" name="based_on_review_id" id="basedOnReviewId">

      <!-- Base on review -->
      <?php if(!empty($reviewsData)): ?>
      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-1">Base on Review (optional)</label>
        <select onchange="loadReviewIntoForm(this.value)"
                class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
          <option value="">— Start from scratch —</option>
          <?php foreach($reviewsData as $rv): ?>
          <option value="<?=$rv['id']?>">
            <?=p(trim(($rv['first_name']??'').' '.($rv['last_name']??'')))?>
            — <?=p($rv['recommendation']??'No recommendation')?>
          </option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php endif; ?>

      <!-- Decision + Due Date -->
      <div class="grid grid-cols-2 gap-4">
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1">Decision *</label>
          <select name="editorial_decision" required
                  class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
            <option value="">— Select —</option>
            <option value="accepted">✅ Accepted</option>
            <option value="accepted_with_changes">✏️ Accepted with Changes</option>
            <option value="resubmit">🔄 Resubmit for Review</option>
            <option value="rejected">❌ Rejected</option>
          </select>
        </div>
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1">Due Date</label>
          <input type="date" name="due_date"
                 class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>
      </div>

      <!-- Scores -->
      <div>
        <label class="block text-xs font-semibold text-gray-600 mb-2">Evaluation Scores</label>
        <div class="grid grid-cols-4 gap-3">
          <?php foreach(['ed_originality'=>'Originality','ed_presentation'=>'Presentation','ed_applicability'=>'Applicability','ed_overall_status'=>'Overall'] as $f=>$l): ?>
          <div>
            <label class="block text-xs text-gray-500 mb-1"><?=$l?></label>
            <select name="<?=$f?>" id="<?=$f?>"
                    class="w-full border border-gray-200 rounded-lg px-2 py-1.5 text-sm">
              <option value="">—</option>
              <?php foreach(['Outstanding','Excellent','Very Good','Good','Fair','Poor'] as $opt): ?>
              <option value="<?=$opt?>"><?=$opt?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- Feedback -->
      <?php foreach(['ed_strengths'=>['Strengths','green'],'ed_weaknesses'=>['Weaknesses / Areas','red'],'ed_suggestions'=>['Suggestions','yellow'],'ed_recommendation'=>['Recommendation Summary','blue']] as $f=>[$l,$c]): ?>
      <div>
        <label class="block text-xs font-semibold text-<?=$c?>-700 mb-1"><?=$l?></label>
        <textarea name="<?=$f?>" id="<?=$f?>" rows="3"
                  class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm resize-y focus:outline-none focus:ring-2 focus:ring-<?=$c?>-400"
                  placeholder="<?=$l?>..."></textarea>
      </div>
      <?php endforeach; ?>

      <!-- Notes -->
      <div class="grid grid-cols-2 gap-4 border-t pt-4">
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1">Comments to Author</label>
          <textarea name="ed_editor_comments" rows="3"
                    class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm resize-y focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Sent in email to author..."></textarea>
        </div>
        <div>
          <label class="block text-xs font-semibold text-gray-600 mb-1">Internal Notes <span class="text-gray-400 font-normal">(confidential)</span></label>
          <textarea name="ed_internal_notes" rows="3"
                    class="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm resize-y focus:outline-none focus:ring-2 focus:ring-gray-400"
                    placeholder="Not sent to author..."></textarea>
        </div>
      </div>

      <button type="submit"
              onclick="return confirm('Save this editorial decision?')"
              class="w-full bg-green-600 text-white py-3 rounded-xl font-semibold hover:bg-green-700 flex items-center justify-center gap-2">
        <i class="fas fa-save"></i> Save Editorial Decision
      </button>
    </form>
  </div>
</div>

</div><!-- /p-6 -->
</div><!-- /content -->

<!-- ── Rating Modal ── -->
<div id="ratingModal" class="fixed inset-0 bg-black/50 hidden z-50 flex items-center justify-center">
  <div class="bg-white rounded-xl shadow-xl w-full max-w-sm p-6">
    <h3 class="font-bold text-gray-800 mb-4">Rate Reviewer</h3>
    <form method="POST">
      <input type="hidden" name="submit_rating" value="1">
      <input type="hidden" name="reviewer_id" id="ratingReviewerId">
      <p class="text-sm text-gray-600 mb-4">Reviewer: <strong id="ratingReviewerName"></strong></p>
      <div class="flex justify-center gap-3 mb-4" id="starRow">
        <?php for($i=1;$i<=5;$i++): ?>
        <button type="button" onclick="setRating(<?=$i?>)"
                class="text-3xl text-gray-300 hover:text-yellow-400 transition star-btn" data-val="<?=$i?>">★</button>
        <?php endfor; ?>
      </div>
      <input type="hidden" name="rating" id="hiddenRating" required>
      <div class="flex gap-2">
        <button type="button" onclick="closeRatingModal()"
                class="flex-1 border border-gray-300 text-gray-600 py-2 rounded-lg text-sm">Cancel</button>
        <button type="submit"
                class="flex-1 bg-yellow-500 text-white py-2 rounded-lg text-sm font-semibold hover:bg-yellow-600">Submit</button>
      </div>
    </form>
  </div>
</div>

<script>
// Review data for prefill
const REVIEWS = <?=json_encode(array_column($reviewsData, null, 'id'))?>;

function switchTab(tab) {
  document.querySelectorAll('[id^="tab-"]').forEach(el => el.classList.add('hidden'));
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.getElementById('tab-' + tab)?.classList.remove('hidden');
  document.getElementById('tab-btn-' + tab)?.classList.add('active');
  history.replaceState(null,'','?id=<?=$sid?>&tab='+tab);
}

// Initialize with URL tab
(function(){
  const params = new URLSearchParams(location.search);
  const t = params.get('tab');
  if(t && document.getElementById('tab-btn-' + t)) switchTab(t);
})();

// Reviewer selection
function selectReviewer(id, name, email) {
  document.getElementById('selectedReviewerId').value = id;
  document.getElementById('selectedReviewerName').textContent = name;
  document.getElementById('selectedReviewerEmail').textContent = email;
  document.getElementById('selectedReviewerBox').classList.remove('hidden');
  document.getElementById('assignBtn').disabled = false;

  // Set default dates
  const today = new Date();
  const r1 = new Date(today); r1.setDate(r1.getDate()+3);
  const r2 = new Date(today); r2.setDate(r2.getDate()+14);
  document.getElementById('responseDueDate').value = r1.toISOString().split('T')[0];
  document.getElementById('reviewDueDate').value   = r2.toISOString().split('T')[0];

  switchTab('assign');
  document.getElementById('assignBtn').scrollIntoView({behavior:'smooth'});
}

// Quick assign from suggested reviewers
function quickAssign(userId, name) {
  // Find reviewer_id by user_id — switch to assign tab with pre-selected
  switchTab('assign');
  alert('Please find and select "' + name + '" from the reviewer list below.');
}

// Filter reviewers
function filterReviewers() {
  const q = document.getElementById('reviewerSearch').value.toLowerCase();
  const avail = document.getElementById('filterAvailability').value;
  document.querySelectorAll('.reviewer-item').forEach(item => {
    const nameMatch  = item.dataset.name?.includes(q) ?? true;
    const emailMatch = item.dataset.email?.includes(q) ?? true;
    const availMatch = !avail || item.dataset.available === avail;
    item.style.display = ((nameMatch || emailMatch) && availMatch) ? '' : 'none';
  });
}

// Load review data into decision form
function loadReviewIntoForm(reviewId) {
  if (!reviewId) return;
  const r = REVIEWS[reviewId];
  if (!r) return;
  document.getElementById('basedOnReviewId').value  = reviewId;
  document.getElementById('ed_originality').value   = r.originality   || '';
  document.getElementById('ed_presentation').value  = r.presentation  || '';
  document.getElementById('ed_applicability').value = r.applicability || '';
  document.getElementById('ed_overall_status').value= r.overall_status|| '';
  document.getElementById('ed_strengths').value     = r.strengths     || '';
  document.getElementById('ed_weaknesses').value    = r.weaknesses    || '';
  document.getElementById('ed_suggestions').value   = r.suggestions   || '';
  document.getElementById('ed_recommendation').value= r.recommendation|| '';
}

// Rating modal
function openRatingModal(reviewerId, name) {
  document.getElementById('ratingReviewerId').value = reviewerId;
  document.getElementById('ratingReviewerName').textContent = name;
  document.getElementById('hiddenRating').value = '';
  document.querySelectorAll('.star-btn').forEach(b => b.style.color = '#D1D5DB');
  document.getElementById('ratingModal').classList.remove('hidden');
}
function closeRatingModal() {
  document.getElementById('ratingModal').classList.add('hidden');
}
function setRating(val) {
  document.getElementById('hiddenRating').value = val;
  document.querySelectorAll('.star-btn').forEach(b => {
    b.style.color = parseInt(b.dataset.val) <= val ? '#F59E0B' : '#D1D5DB';
  });
}

function sendReminder(email, name) {
  alert('Reminder: email ' + email + ' — implement sendReminder AJAX here');
}
</script>
</body>
</html>