<?php
/**
 * ajax/review_detail_modal.php
 * Returns HTML: full details of a single review record.
 * Opened when clicking the file icon on any row in Tab 1.
 */
session_start();
include __DIR__ . '/../config/db.php';
include __DIR__ . '/../config/auth.php';
require_role('admin');

$review_id = (int)($_GET['review_id'] ?? 0);
if (!$review_id) { echo '<div class="p-6 text-red-400">Invalid review ID.</div>'; exit; }

try {
    $stmt = $pdo->prepare("
        SELECT
            rv.*,
            s.tracking_code,
            s.submitted_at,
            s.submission_status,

            mi.article_title,
            mi.abstract,

            j.name  AS journal_name,

            CONCAT(u_author.first_name,' ',u_author.last_name) AS author_name,
            u_author.email   AS author_email,
            u_author.country AS author_country,

            CONCAT(u_rev.first_name,' ',u_rev.last_name) AS reviewer_name,
            u_rev.email      AS reviewer_email,

            ra.request_sent_date,
            ra.review_due_date,
            ra.assignment_status,
            DATEDIFF(rv.reviewed_at, ra.request_sent_date) AS days_taken

        FROM reviews rv
        LEFT JOIN submissions s         ON s.submission_id  = rv.submission_id
        LEFT JOIN manuscript_info mi    ON mi.submission_id = s.submission_id
        LEFT JOIN journals j            ON j.journal_id     = s.journal_id
        LEFT JOIN users u_author        ON u_author.user_id = s.user_id
        LEFT JOIN reviewers rev_rec     ON rev_rec.id       = rv.reviewer_id
        LEFT JOIN users u_rev           ON u_rev.user_id    = rev_rec.user_id
        LEFT JOIN review_assignments ra ON ra.submission_id = rv.submission_id
                                       AND ra.reviewer_id   = rv.reviewer_id
        WHERE rv.id = ?
        LIMIT 1
    ");
    $stmt->execute([$review_id]);
    $r = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo '<div class="p-6 text-red-400">DB Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
    exit;
}

if (!$r) { echo '<div class="p-6 text-gray-400">Review not found.</div>'; exit; }

function ratingBadge($val) {
    if (!$val) return '<span style="color:#d1d5db">—</span>';
    $colors = [
        'outstanding' => ['#fef3c7','#92400e'],
        'excellent'   => ['#dcfce7','#166534'],
        'very good'   => ['#dbeafe','#1e40af'],
        'good'        => ['#e0e7ff','#3730a3'],
        'fair'        => ['#fef9c3','#854d0e'],
        'poor'        => ['#fee2e2','#991b1b'],
        'very poor'   => ['#fce7f3','#9d174d'],
    ];
    $key = strtolower(trim($val));
    [$bg, $fg] = $colors[$key] ?? ['#f1f5f9','#475569'];
    return "<span style=\"display:inline-block;background:$bg;color:$fg;padding:2px 8px;border-radius:9999px;font-size:11px;font-weight:700\">" . htmlspecialchars(ucwords($val)) . "</span>";
}

function field($label, $value) {
    $v = trim((string)($value ?? ''));
    if ($v === '') return '';
    return "
    <div style=\"margin-bottom:16px\">
      <div style=\"font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.4px;margin-bottom:5px\">$label</div>
      <div style=\"font-size:13px;color:#1e293b;line-height:1.6;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:10px 12px\">" . nl2br(htmlspecialchars($v)) . "</div>
    </div>";
}
?>
<div style="padding:20px 24px;font-family:'Roboto',sans-serif">

  <!-- Meta info -->
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px;padding:14px;background:#f8fafc;border-radius:10px;border:1px solid #e2e8f0">

    <div>
      <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:4px">Paper</div>
      <div style="font-size:13px;font-weight:600;color:#1e293b"><?= htmlspecialchars($r['article_title'] ?? '—') ?></div>
      <div style="font-size:11px;color:#94a3b8;margin-top:2px">
        <?= $r['tracking_code'] ? htmlspecialchars($r['tracking_code']) . ' · ' : '' ?>
        <?= htmlspecialchars($r['journal_name'] ?? '') ?>
      </div>
    </div>

    <div>
      <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:4px">Author</div>
      <div style="font-size:13px;color:#1e293b"><?= htmlspecialchars($r['author_name']) ?></div>
      <div style="font-size:11px;color:#94a3b8"><?= htmlspecialchars($r['author_email'] ?? '') ?> · <?= htmlspecialchars($r['author_country'] ?? '') ?></div>
    </div>

    <div>
      <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:4px">Reviewer</div>
      <div style="font-size:13px;color:#1e293b"><?= htmlspecialchars($r['reviewer_name']) ?></div>
      <div style="font-size:11px;color:#94a3b8"><?= htmlspecialchars($r['reviewer_email'] ?? '') ?></div>
    </div>

    <div>
      <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:4px">Dates</div>
      <div style="font-size:12px;color:#374151">
        Assigned: <?= $r['request_sent_date'] ? date('d M Y', strtotime($r['request_sent_date'])) : '—' ?><br>
        Due: <?= $r['review_due_date'] ? date('d M Y', strtotime($r['review_due_date'])) : '—' ?><br>
        Submitted: <strong><?= $r['reviewed_at'] ? date('d M Y', strtotime($r['reviewed_at'])) : '—' ?></strong>
        <?php if ($r['days_taken'] !== null): ?>
          <span style="background:#dbeafe;color:#1e40af;padding:1px 6px;border-radius:99px;font-size:10px;font-weight:700;margin-left:4px">
            <?= $r['days_taken'] ?> days
          </span>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Ratings grid -->
  <div style="margin-bottom:20px">
    <div style="font-size:12px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.4px;margin-bottom:10px">Ratings</div>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px">
      <?php foreach ([
        'Originality'   => $r['originality'],
        'Presentation'  => $r['presentation'],
        'Applicability' => $r['applicability'],
        'Overall'       => $r['overall_status'],
      ] as $label => $val): ?>
      <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:10px;text-align:center">
        <div style="font-size:10px;color:#94a3b8;margin-bottom:5px;font-weight:600;text-transform:uppercase"><?= $label ?></div>
        <?= ratingBadge($val) ?>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Recommendation -->
  <?php if ($r['recommendation']): ?>
  <div style="margin-bottom:20px">
    <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.4px;margin-bottom:6px">Recommendation</div>
    <?php
    $rec = strtolower($r['recommendation']);
    $rcol = str_contains($rec,'accept') ? ['#dcfce7','#166534']
          : (str_contains($rec,'reject') ? ['#fee2e2','#991b1b']
          : (str_contains($rec,'resubmit')||str_contains($rec,'revis') ? ['#fef9c3','#854d0e']
          : ['#f1f5f9','#475569']));
    ?>
    <span style="display:inline-block;background:<?= $rcol[0] ?>;color:<?= $rcol[1] ?>;padding:4px 14px;border-radius:9999px;font-size:13px;font-weight:700">
      <?= htmlspecialchars(ucfirst($r['recommendation'])) ?>
    </span>
  </div>
  <?php endif; ?>

  <!-- Detailed text fields -->
  <?= field('Strengths', $r['strengths']) ?>
  <?= field('Weaknesses', $r['weaknesses']) ?>
  <?= field('Suggestions', $r['suggestions']) ?>
  <?= field('Comments to Editor (Confidential)', $r['comments']) ?>

  <!-- Review file -->
  <?php if (!empty($r['review_file'])):
    /*
     * DB stores paths like: /reviewer/uploads/reviews/filename.docx
     * or sometimes just:     reviewer/uploads/reviews/filename.docx
     * Full URL must be:       https://communeglobal.com/reviewer/uploads/reviews/filename.docx
     */
    $reviewFilePath = trim($r['review_file']);
    // If already a full URL, use as-is
    if (str_starts_with($reviewFilePath, 'http://') || str_starts_with($reviewFilePath, 'https://')) {
        $reviewFileUrl = $reviewFilePath;
    } else {
        // Strip leading slash then prepend site root
        $reviewFileUrl = 'https://communeglobal.com/' . ltrim($reviewFilePath, '/');
    }
    // Detect file type for icon
    $ext = strtolower(pathinfo($reviewFilePath, PATHINFO_EXTENSION));
    $fileIcon = match($ext) {
        'pdf'              => 'fa-file-pdf',
        'doc', 'docx'      => 'fa-file-word',
        'xls', 'xlsx'      => 'fa-file-excel',
        'ppt', 'pptx'      => 'fa-file-powerpoint',
        default            => 'fa-file-alt',
    };
    $fileName = basename($reviewFilePath);
  ?>
  <div style="margin-top:16px;padding:14px;background:#f0f4ff;border:1px solid #c7d2fe;border-radius:10px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px">
    <div style="display:flex;align-items:center;gap:10px">
      <div style="width:40px;height:40px;background:#4f46e5;border-radius:8px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <i class="fas <?= $fileIcon ?>" style="color:#fff;font-size:16px"></i>
      </div>
      <div>
        <div style="font-size:12px;font-weight:700;color:#1e293b">Review File</div>
        <div style="font-size:11px;color:#64748b;word-break:break-all;max-width:400px"><?= htmlspecialchars($fileName) ?></div>
      </div>
    </div>
    <div style="display:flex;gap:8px;flex-shrink:0">
      <!-- Open in new tab (view in browser if supported) -->
      <a href="<?= htmlspecialchars($reviewFileUrl) ?>" target="_blank" rel="noopener noreferrer"
         style="display:inline-flex;align-items:center;gap:6px;background:#4f46e5;color:#fff;padding:8px 16px;border-radius:8px;font-size:12px;font-weight:600;text-decoration:none">
        <i class="fas fa-external-link-alt"></i> Open File
      </a>
      <!-- Force download -->
      <a href="<?= htmlspecialchars($reviewFileUrl) ?>" download="<?= htmlspecialchars($fileName) ?>" target="_blank"
         style="display:inline-flex;align-items:center;gap:6px;background:#059669;color:#fff;padding:8px 16px;border-radius:8px;font-size:12px;font-weight:600;text-decoration:none">
        <i class="fas fa-download"></i> Download
      </a>
    </div>
  </div>
  <?php endif; ?>

  <!-- Action links -->
  <div style="margin-top:20px;padding-top:16px;border-top:1px solid #f1f5f9;display:flex;gap:10px;flex-wrap:wrap">
    <a href="review_assignment.php?id=<?= $r['submission_id'] ?>"
       style="display:inline-flex;align-items:center;gap:5px;background:#6366f1;color:#fff;padding:7px 14px;border-radius:7px;font-size:12px;font-weight:600;text-decoration:none">
      <i class="fas fa-user-check"></i> View Review Assignment
    </a>
    <a href="submission_view.php?id=<?= $r['submission_id'] ?>"
       style="display:inline-flex;align-items:center;gap:5px;background:#0f766e;color:#fff;padding:7px 14px;border-radius:7px;font-size:12px;font-weight:600;text-decoration:none">
      <i class="fas fa-file-alt"></i> View Full Submission
    </a>
  </div>

</div>