<?php
/**
 * reviewer_access.php
 * CommuneGlobal — Reviewer access via email link (no login required)
 *
 * URL format:
 *   https://yourdomain.com/reviewer/reviewer_access.php?access_key=XXXX&submission_id=28
 *
 * Flow:
 *   1. Validate access_key + submission_id  → show manuscript preview
 *   2. Reviewer clicks Accept  → assignment_status = 'accepted', then auto-login to dashboard
 *   3. Reviewer clicks Decline → assignment_status = 'declined'
 *   4. "Go to Dashboard" button → auto-login regardless of current status
 */

error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
session_start();

require_once __DIR__ . '/config/db.php';
// NOTE: Do NOT require auth.php here — this page is intentionally public

// ─────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────
$access_key    = trim($_GET['access_key']    ?? '');
$submission_id = (int)($_GET['submission_id'] ?? 0);

$message      = '';
$message_type = ''; // 'success' | 'error' | 'info'
$assignment   = null;
$submission   = null;
$can_respond  = false;

// ─────────────────────────────────────────────────────────────
// VALIDATE KEY
// ─────────────────────────────────────────────────────────────
if (!$access_key || $submission_id <= 0) {
    $message      = 'Invalid or missing access parameters.';
    $message_type = 'error';
} else {
    try {
        $stmt = db()->prepare("
            SELECT
                ra.id            AS assignment_id,
                ra.submission_id,
                ra.reviewer_id,
                ra.assignment_status,
                ra.reviewer_type,
                ra.access_key,
                ra.request_sent_date,
                ra.response_due_date,
                ra.review_due_date,
                -- reviewer user
                u.user_id,
                u.first_name,
                u.last_name,
                u.email,
                u.username,
                u.role,
                u.is_active,
                -- manuscript
                mi.article_title AS title,
                mi.abstract,
                -- submission
                s.tracking_code,
                s.submitted_at,
                s.submission_status,
                -- journal
                j.name           AS journal_name
            FROM review_assignments ra
            JOIN reviewers rv ON ra.reviewer_id = rv.id
            JOIN users u      ON rv.user_id = u.user_id
            JOIN submissions s ON ra.submission_id = s.submission_id
            LEFT JOIN manuscript_info mi ON s.submission_id = mi.submission_id
            LEFT JOIN journals j ON s.journal_id = j.journal_id
            WHERE ra.submission_id = ?
              AND ra.access_key    = ?
            LIMIT 1
        ");
        $stmt->execute([$submission_id, $access_key]);
        $assignment = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$assignment) {
            $message      = 'Invalid or expired access link. Please contact the editorial office.';
            $message_type = 'error';
        } else {
            $can_respond = ($assignment['assignment_status'] === 'request_sent');
        }
    } catch (PDOException $e) {
        $message      = 'A database error occurred. Please try again later.';
        $message_type = 'error';
        error_log('reviewer_access.php DB error: ' . $e->getMessage());
    }
}

// ─────────────────────────────────────────────────────────────
// AUTO-LOGIN  (?auto_login=1)
// ─────────────────────────────────────────────────────────────
if ($assignment && isset($_GET['auto_login']) && $_GET['auto_login'] === '1') {
    try {
        // Refresh user row to get latest data
        $ustmt = db()->prepare("SELECT user_id, first_name, last_name, email, role, username FROM users WHERE user_id = ? AND is_active = 1 LIMIT 1");
        $ustmt->execute([$assignment['user_id']]);
        $reviewer_user = $ustmt->fetch(PDO::FETCH_ASSOC);

        if ($reviewer_user) {
            // Set session — mirrors what your login.php does
            $_SESSION['user_id']   = $reviewer_user['user_id'];
            $_SESSION['role']      = $reviewer_user['role'];
            $_SESSION['username']  = $reviewer_user['username'] ?? $reviewer_user['email'];
            $_SESSION['logged_in'] = true;

            // Update last_login in users table if that column exists
            try {
                db()->prepare("UPDATE users SET updated_at = NOW() WHERE user_id = ?")
                    ->execute([$reviewer_user['user_id']]);
            } catch (PDOException $e) { /* column may not exist — ignore */ }

            // Redirect to reviewer dashboard
            header('Location: /reviewer/dashboard.php');
            exit;
        } else {
            $message      = 'Your reviewer account is inactive. Please contact the editorial office.';
            $message_type = 'error';
        }
    } catch (PDOException $e) {
        $message      = 'Auto-login failed. Please log in manually.';
        $message_type = 'error';
        error_log('reviewer_access.php auto-login error: ' . $e->getMessage());
    }
}

// ─────────────────────────────────────────────────────────────
// POST: ACCEPT
// ─────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $assignment) {

    if ($_POST['action'] === 'accept' && $can_respond) {
        try {
            db()->beginTransaction();

            db()->prepare("
                UPDATE review_assignments
                SET assignment_status = 'accepted',
                    accepted_date     = NOW()
                WHERE id = ?
                  AND assignment_status = 'request_sent'
            ")->execute([$assignment['assignment_id']]);

            db()->commit();

            $message      = 'Invitation accepted! Click "Go to Dashboard" below to start your review.';
            $message_type = 'success';
            $assignment['assignment_status'] = 'accepted';
            $can_respond  = false;

        } catch (PDOException $e) {
            db()->rollBack();
            $message      = 'Could not accept the invitation. Please try again.';
            $message_type = 'error';
            error_log('reviewer_access accept error: ' . $e->getMessage());
        }

    } elseif ($_POST['action'] === 'decline' && $can_respond) {
        try {
            db()->beginTransaction();

            db()->prepare("
                UPDATE review_assignments
                SET assignment_status = 'declined',
                    declined_date     = NOW()
                WHERE id = ?
                  AND assignment_status = 'request_sent'
            ")->execute([$assignment['assignment_id']]);

            db()->commit();

            $message      = 'Invitation declined. Thank you for letting us know.';
            $message_type = 'info';
            $assignment['assignment_status'] = 'declined';
            $can_respond  = false;

        } catch (PDOException $e) {
            db()->rollBack();
            $message      = 'Could not decline the invitation. Please try again.';
            $message_type = 'error';
            error_log('reviewer_access decline error: ' . $e->getMessage());
        }
    }
}

// ─────────────────────────────────────────────────────────────
// HELPERS
// ─────────────────────────────────────────────────────────────
function daysLeft($date_str) {
    if (!$date_str) return null;
    return max(0, (int)ceil((strtotime($date_str) - time()) / 86400));
}
function p($v) {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

$status_label = [
    'request_sent'     => ['Pending Response',  'bg-amber-100 text-amber-800 border-amber-300'],
    'accepted'         => ['Accepted',           'bg-blue-100 text-blue-800 border-blue-300'],
    'declined'         => ['Declined',           'bg-red-100 text-red-800 border-red-300'],
    'cancelled'        => ['Cancelled',          'bg-gray-100 text-gray-600 border-gray-300'],
    'review_submitted' => ['Review Submitted',   'bg-green-100 text-green-800 border-green-300'],
];
$cur_status = $assignment['assignment_status'] ?? 'request_sent';
$sl         = $status_label[$cur_status] ?? ['Unknown', 'bg-gray-100 text-gray-600 border-gray-300'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Review Invitation — Communeglobal Journals</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; }
  .font-display { font-family: 'Sora', sans-serif; }
  .clamp-4 { display:-webkit-box; -webkit-line-clamp:4; -webkit-box-orient:vertical; overflow:hidden; }
  @keyframes fadeIn { from{opacity:0;transform:translateY(12px)} to{opacity:1;transform:translateY(0)} }
  .fade-in { animation: fadeIn 0.4s ease both; }
</style>
</head>
<body class="bg-gradient-to-br from-slate-50 to-blue-50 min-h-screen">

<!-- ── Header ─────────────────────────────────────────────── -->
<header class="bg-white border-b border-slate-200 shadow-sm">
  <div class="max-w-4xl mx-auto px-6 py-4 flex items-center justify-between">
    <div class="flex items-center gap-3">
      <div class="w-9 h-9 bg-blue-600 rounded-xl flex items-center justify-center">
        <span class="text-white font-display font-bold text-sm">C</span>
      </div>
      <div>
        <div class="font-display font-bold text-slate-800 text-sm leading-tight">Communeglobal</div>
        <div class="text-xs text-slate-400">International Journals</div>
      </div>
    </div>
    <a href="/reviewer/dashboard.php"
       class="text-xs text-blue-600 hover:text-blue-800 border border-blue-200 hover:bg-blue-50 px-3 py-1.5 rounded-lg font-medium transition-all">
      <i class="fas fa-sign-in-alt mr-1"></i> Login
    </a>
  </div>
</header>

<main class="max-w-4xl mx-auto px-6 py-10">

  <!-- ── Error: no valid key ─────────────────────────────── -->
  <?php if ($message_type === 'error' && !$assignment): ?>
  <div class="fade-in bg-white rounded-2xl border border-red-200 p-12 text-center shadow-sm">
    <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
      <i class="fas fa-exclamation-triangle text-red-500 text-2xl"></i>
    </div>
    <h2 class="font-display font-bold text-slate-800 text-xl mb-2">Access Error</h2>
    <p class="text-slate-500 text-sm mb-6"><?= p($message) ?></p>
    <a href="mailto:editorial.office@communeglobal.com"
       class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-5 py-2.5 rounded-xl text-sm font-semibold transition">
      <i class="fas fa-envelope"></i> Contact Editorial Office
    </a>
  </div>

  <?php else: ?>

  <!-- ── Flash message ──────────────────────────────────── -->
  <?php if ($message): ?>
  <div class="fade-in mb-6 flex items-start gap-3 px-5 py-4 rounded-xl border text-sm font-medium
    <?= $message_type === 'success' ? 'bg-emerald-50 border-emerald-200 text-emerald-800' :
       ($message_type === 'info'    ? 'bg-blue-50 border-blue-200 text-blue-800' :
                                      'bg-red-50 border-red-200 text-red-800') ?>">
    <i class="fas fa-<?= $message_type === 'success' ? 'check-circle' : ($message_type === 'info' ? 'info-circle' : 'exclamation-circle') ?> mt-0.5 flex-shrink-0"></i>
    <span><?= p($message) ?></span>
  </div>
  <?php endif; ?>

  <div class="fade-in grid grid-cols-1 lg:grid-cols-3 gap-6">

    <!-- ── Left: Manuscript card ──────────────────────── -->
    <div class="lg:col-span-2 space-y-5">

      <!-- Title + status -->
      <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden shadow-sm">
        <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-6 py-5">
          <div class="flex items-start justify-between gap-3">
            <div>
              <p class="text-blue-100 text-xs font-medium mb-1">
                <i class="fas fa-envelope-open-text mr-1"></i> Peer Review Invitation
              </p>
              <h1 class="font-display font-bold text-white text-lg leading-snug">
                <?= p($assignment['title'] ?: 'Untitled Manuscript') ?>
              </h1>
            </div>
            <span class="flex-shrink-0 text-xs font-bold px-3 py-1 rounded-full border <?= $sl[1] ?>">
              <?= $sl[0] ?>
            </span>
          </div>
        </div>

        <!-- Meta grid -->
        <div class="grid grid-cols-2 sm:grid-cols-3 gap-0 divide-x divide-y divide-slate-100">
          <?php if (!empty($assignment['tracking_code'])): ?>
          <div class="px-4 py-3">
            <div class="text-xs text-slate-400 mb-0.5">Tracking Code</div>
            <div class="font-mono text-sm font-bold text-blue-600"><?= p($assignment['tracking_code']) ?></div>
          </div>
          <?php endif; ?>
          <?php if (!empty($assignment['journal_name'])): ?>
          <div class="px-4 py-3">
            <div class="text-xs text-slate-400 mb-0.5">Journal</div>
            <div class="text-sm font-semibold text-slate-700 line-clamp-2"><?= p($assignment['journal_name']) ?></div>
          </div>
          <?php endif; ?>
          <?php if (!empty($assignment['submitted_at'])): ?>
          <div class="px-4 py-3">
            <div class="text-xs text-slate-400 mb-0.5">Submitted</div>
            <div class="text-sm font-semibold text-slate-700"><?= date('d M Y', strtotime($assignment['submitted_at'])) ?></div>
          </div>
          <?php endif; ?>
          <?php if (!empty($assignment['response_due_date'])): ?>
          <div class="px-4 py-3">
            <div class="text-xs text-slate-400 mb-0.5">Response Due</div>
            <?php $rd = daysLeft($assignment['response_due_date']); ?>
            <div class="text-sm font-semibold <?= $rd !== null && $rd <= 2 ? 'text-red-600' : 'text-slate-700' ?>">
              <?= date('d M Y', strtotime($assignment['response_due_date'])) ?>
              <?php if ($rd !== null): ?>
              <span class="text-xs font-normal ml-1 text-slate-400">(<?= $rd ?>d left)</span>
              <?php endif; ?>
            </div>
          </div>
          <?php endif; ?>
          <?php if (!empty($assignment['review_due_date'])): ?>
          <div class="px-4 py-3">
            <div class="text-xs text-slate-400 mb-0.5">Review Due</div>
            <?php $rvd = daysLeft($assignment['review_due_date']); ?>
            <div class="text-sm font-semibold <?= $rvd !== null && $rvd <= 5 ? 'text-red-600' : 'text-slate-700' ?>">
              <?= date('d M Y', strtotime($assignment['review_due_date'])) ?>
              <?php if ($rvd !== null): ?>
              <span class="text-xs font-normal ml-1 text-slate-400">(<?= $rvd ?>d left)</span>
              <?php endif; ?>
            </div>
          </div>
          <?php endif; ?>
          <?php if (!empty($assignment['reviewer_type'])): ?>
          <div class="px-4 py-3">
            <div class="text-xs text-slate-400 mb-0.5">Review Type</div>
            <div class="text-xs font-medium text-slate-600 capitalize"><?= p(str_replace('_', ' ', $assignment['reviewer_type'])) ?></div>
          </div>
          <?php endif; ?>
        </div>
      </div>

      <!-- Abstract -->
      <?php if (!empty($assignment['abstract'])): ?>
      <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
        <h3 class="text-xs font-bold uppercase tracking-wide text-slate-400 mb-3">
          <i class="fas fa-align-left mr-1"></i> Abstract
        </h3>
        <div class="text-sm text-slate-600 leading-relaxed" id="abstractText">
          <?php
          $abstract = $assignment['abstract'];
          $short    = mb_substr($abstract, 0, 500);
          $hasMore  = mb_strlen($abstract) > 500;
          ?>
          <span id="abstractShort"><?= p($short) ?><?= $hasMore ? '…' : '' ?></span>
          <?php if ($hasMore): ?>
          <span id="abstractFull" class="hidden"><?= p($abstract) ?></span>
          <button onclick="toggleAbstract()" id="abstractToggle"
                  class="text-blue-600 hover:text-blue-800 text-xs font-medium ml-1 underline underline-offset-2">
            Read more
          </button>
          <?php endif; ?>
        </div>
      </div>
      <?php endif; ?>

    </div>

    <!-- ── Right: Action card ──────────────────────────── -->
    <div class="lg:col-span-1 space-y-4">

      <!-- Reviewer greeting -->
      <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
        <div class="flex items-center gap-3 mb-3">
          <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center font-bold text-blue-700">
            <?= strtoupper(substr($assignment['first_name'] ?? 'R', 0, 1)) ?>
          </div>
          <div>
            <div class="text-sm font-semibold text-slate-800">
              <?= p(trim(($assignment['first_name'] ?? '') . ' ' . ($assignment['last_name'] ?? ''))) ?>
            </div>
            <div class="text-xs text-slate-400"><?= p($assignment['email'] ?? '') ?></div>
          </div>
        </div>
        <p class="text-xs text-slate-500 leading-relaxed">
          You have been invited to review this manuscript. Please respond to the invitation below.
        </p>
      </div>

      <!-- ── Accept / Decline (only when request_sent) ── -->
      <?php if ($can_respond): ?>
      <div class="bg-white rounded-2xl border border-slate-200 p-5 shadow-sm">
        <h3 class="text-sm font-bold text-slate-700 mb-4 flex items-center gap-2">
          <i class="fas fa-reply text-blue-500"></i> Respond to Invitation
        </h3>
        <form method="POST" id="responseForm">
          <input type="hidden" name="action" id="actionInput" value="">
          <div class="space-y-3">
            <button type="button"
                    onclick="submitAction('accept')"
                    class="w-full bg-emerald-600 hover:bg-emerald-700 text-white py-3 rounded-xl font-semibold text-sm flex items-center justify-center gap-2 transition-all shadow-sm">
              <i class="fas fa-check-circle"></i> Accept Invitation
            </button>
            <button type="button"
                    onclick="submitAction('decline')"
                    class="w-full bg-white hover:bg-red-50 text-red-600 border border-red-200 hover:border-red-300 py-3 rounded-xl font-semibold text-sm flex items-center justify-center gap-2 transition-all">
              <i class="fas fa-times-circle"></i> Decline Invitation
            </button>
          </div>
          <p class="text-xs text-slate-400 mt-3 text-center">
            Your response will be sent to the editorial team immediately.
          </p>
        </form>
      </div>
      <?php endif; ?>

      <!-- ── Go to Dashboard (auto-login) ── -->
      <div class="bg-gradient-to-br from-blue-600 to-indigo-700 rounded-2xl p-5 shadow-sm text-white">
        <h3 class="font-bold text-sm mb-1 flex items-center gap-2">
          <i class="fas fa-tachometer-alt"></i> Reviewer Dashboard
        </h3>
        <p class="text-blue-100 text-xs mb-4 leading-relaxed">
          Access your full reviewer dashboard — view assignments, submit reviews, and track your progress.
        </p>
        <a href="?access_key=<?= urlencode($access_key) ?>&submission_id=<?= $submission_id ?>&auto_login=1"
           class="block w-full bg-white hover:bg-blue-50 text-blue-700 font-bold text-sm py-3 rounded-xl text-center transition-all">
          <i class="fas fa-sign-in-alt mr-2"></i> Go to Dashboard
        </a>
        <p class="text-blue-200 text-xs mt-2 text-center">No password needed — you'll be logged in automatically.</p>
      </div>

      <!-- Status info (when already responded) -->
      <?php if (!$can_respond && $cur_status !== 'request_sent'): ?>
      <div class="bg-white rounded-2xl border border-slate-200 p-4 shadow-sm text-center text-sm">
        <?php if ($cur_status === 'accepted' || $cur_status === 'review_submitted'): ?>
        <i class="fas fa-check-circle text-emerald-500 text-2xl mb-2 block"></i>
        <p class="text-slate-600 font-medium">You have accepted this review.</p>
        <p class="text-slate-400 text-xs mt-1">Click "Go to Dashboard" to access the full manuscript.</p>
        <?php elseif ($cur_status === 'declined'): ?>
        <i class="fas fa-times-circle text-red-400 text-2xl mb-2 block"></i>
        <p class="text-slate-600 font-medium">You have declined this review.</p>
        <p class="text-slate-400 text-xs mt-1">Thank you for letting us know.</p>
        <?php endif; ?>
      </div>
      <?php endif; ?>

    </div>

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

  <?php endif; ?>
</main>

<!-- Footer -->
<footer class="text-center py-8 text-xs text-slate-400 border-t border-slate-200 mt-10">
  © <?= date('Y') ?> Communeglobal International Journals. All rights reserved. &nbsp;·&nbsp;
  <a href="mailto:editorial.office@communeglobal.com" class="hover:text-blue-600 underline">Contact Support</a>
</footer>

<script>
function submitAction(action) {
    var label = action === 'accept' ? 'accept this review invitation' : 'decline this invitation';
    if (confirm('Are you sure you want to ' + label + '? This action cannot be undone.')) {
        document.getElementById('actionInput').value = action;
        document.getElementById('responseForm').submit();
    }
}
function toggleAbstract() {
    var s = document.getElementById('abstractShort');
    var f = document.getElementById('abstractFull');
    var b = document.getElementById('abstractToggle');
    if (f.classList.contains('hidden')) {
        s.classList.add('hidden');
        f.classList.remove('hidden');
        b.textContent = 'Show less';
    } else {
        f.classList.add('hidden');
        s.classList.remove('hidden');
        b.textContent = 'Read more';
    }
}
</script>
</body>
</html>