<?php
/**
 * ajax/reviewer_feedback_modal.php
 * Returns HTML: list of reviews submitted by a specific reviewer in the range.
 * Opened from Tab 3 (Feedback Received) count link.
 */
session_start();
include __DIR__ . '/../config/db.php';
include __DIR__ . '/../config/auth.php';
require_role('admin');

$reviewer_id = (int)($_GET['id']    ?? 0);
$range       = trim($_GET['range']  ?? '7');
$from        = trim($_GET['from']   ?? '');
$to          = trim($_GET['to']     ?? '');

if (!$reviewer_id) { echo '<div class="p-6 text-red-400">Invalid reviewer ID.</div>'; exit; }

function buildDateRange($range, $from, $to) {
    switch ($range) {
        case 'today':     return ["DATE(rv.reviewed_at) = CURDATE()", []];
        case 'yesterday': return ["DATE(rv.reviewed_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)", []];
        case 'custom':
            if ($from && $to)   return ["DATE(rv.reviewed_at) BETWEEN ? AND ?", [$from, $to]];
            if ($from)          return ["DATE(rv.reviewed_at) >= ?", [$from]];
            if ($to)            return ["DATE(rv.reviewed_at) <= ?", [$to]];
            return ["1=1", []];
        default:
            $days = is_numeric($range) ? (int)$range : 7;
            return ["rv.reviewed_at >= DATE_SUB(NOW(), INTERVAL $days DAY)", []];
    }
}

[$dateWhere, $dateParams] = buildDateRange($range, $from, $to);

try {
    $stmt = $pdo->prepare("
        SELECT
            rv.id               AS review_id,
            rv.submission_id,
            rv.reviewed_at,
            rv.recommendation,
            rv.originality,
            rv.presentation,
            rv.applicability,
            rv.overall_status,

            s.tracking_code,
            s.submitted_at,

            mi.article_title,
            j.name AS journal_name,

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

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

        FROM reviews rv
        JOIN reviewers rev ON rev.id = rv.reviewer_id
        JOIN submissions s ON s.submission_id = rv.submission_id
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        LEFT JOIN users u_author     ON u_author.user_id = s.user_id
        LEFT JOIN journals j         ON j.journal_id     = s.journal_id
        LEFT JOIN review_assignments ra ON ra.submission_id = rv.submission_id
                                       AND ra.reviewer_id   = rev.id
        WHERE rv.reviewer_id = ?
          AND rv.reviewed_at IS NOT NULL
          AND $dateWhere
        ORDER BY rv.reviewed_at DESC
    ");
    $stmt->execute(array_merge([$reviewer_id], $dateParams));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo '<div class="p-6 text-red-400">DB Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
    exit;
}

$recColors = [
    'accepted'  => ['#dcfce7','#166534'],
    'rejected'  => ['#fee2e2','#991b1b'],
    'resubmit'  => ['#fef9c3','#854d0e'],
];
function recColor($rec) {
    global $recColors;
    $r = strtolower($rec ?? '');
    if (str_contains($r,'accept'))   return $recColors['accepted'];
    if (str_contains($r,'reject'))   return $recColors['rejected'];
    if (str_contains($r,'resubmit') || str_contains($r,'revis')) return $recColors['resubmit'];
    return ['#f1f5f9','#475569'];
}
?>
<?php if (empty($rows)): ?>
<div class="p-10 text-center text-gray-400">
  <i class="fas fa-inbox text-3xl mb-3 block opacity-30"></i>
  <p class="text-sm">No feedback submitted in this period.</p>
</div>
<?php else: ?>
<div style="overflow-x:auto">
<table style="width:100%;border-collapse:collapse;font-size:12.5px">
  <thead>
    <tr style="background:#f8fafc;border-bottom:2px solid #e2e8f0">
      <th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;white-space:nowrap">Sub. ID</th>
      <th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;white-space:nowrap">Tracking</th>
      <th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase">Title</th>
      <th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;white-space:nowrap">Sub. Date</th>
      <th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;white-space:nowrap">Assigned</th>
      <th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;white-space:nowrap">Feedback Date</th>
      <th style="padding:10px 12px;text-align:center;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;white-space:nowrap">Days Taken</th>
      <th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase">Recommendation</th>
      <th style="padding:10px 12px;text-align:center;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase">Action</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($rows as $row):
      [$bgColor, $textColor] = recColor($row['recommendation']);
    ?>
    <tr style="border-bottom:1px solid #f1f5f9">
      <td style="padding:8px 12px">
        <span style="font-family:monospace;font-size:11px;background:#f1f5f9;padding:2px 6px;border-radius:4px">#<?= $row['submission_id'] ?></span>
      </td>
      <td style="padding:8px 12px">
        <?php if ($row['tracking_code']): ?>
        <span style="font-family:monospace;font-size:11px;font-weight:700;color:#3730a3;background:#eef2ff;border:1px solid #c7d2fe;padding:2px 6px;border-radius:4px">
          <?= htmlspecialchars($row['tracking_code']) ?>
        </span>
        <?php else: ?><span style="color:#d1d5db">—</span><?php endif; ?>
      </td>
      <td style="padding:8px 12px;max-width:200px">
        <div style="font-size:12px;color:#374151;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px"
             title="<?= htmlspecialchars($row['article_title'] ?? '') ?>">
          <?= htmlspecialchars(mb_strimwidth($row['article_title'] ?? '—', 0, 50, '…')) ?>
        </div>
        <div style="font-size:11px;color:#94a3b8"><?= htmlspecialchars($row['author_name'] ?? '') ?>, <?= htmlspecialchars($row['author_country'] ?? '') ?></div>
      </td>
      <td style="padding:8px 12px;font-size:11px;color:#6b7280;white-space:nowrap">
        <?= $row['submitted_at'] ? date('d M Y', strtotime($row['submitted_at'])) : '—' ?>
      </td>
      <td style="padding:8px 12px;font-size:11px;color:#6b7280;white-space:nowrap">
        <?= $row['request_sent_date'] ? date('d M Y', strtotime($row['request_sent_date'])) : '—' ?>
      </td>
      <td style="padding:8px 12px;font-size:11px;font-weight:600;color:#374151;white-space:nowrap">
        <?= $row['reviewed_at'] ? date('d M Y', strtotime($row['reviewed_at'])) : '—' ?>
      </td>
      <td style="padding:8px 12px;text-align:center">
        <?php if ($row['days_taken'] !== null): ?>
        <span style="display:inline-block;background:<?= $row['days_taken'] <= 7 ? '#dcfce7' : ($row['days_taken'] <= 14 ? '#fef9c3' : '#fee2e2') ?>;
               color:<?= $row['days_taken'] <= 7 ? '#166534' : ($row['days_taken'] <= 14 ? '#854d0e' : '#991b1b') ?>;
               padding:2px 8px;border-radius:9999px;font-size:11px;font-weight:700">
          <?= $row['days_taken'] ?> days
        </span>
        <?php else: ?>—<?php endif; ?>
      </td>
      <td style="padding:8px 12px">
        <?php if ($row['recommendation']): ?>
        <span style="display:inline-flex;align-items:center;padding:2px 8px;border-radius:9999px;font-size:10px;font-weight:700;background:<?= $bgColor ?>;color:<?= $textColor ?>">
          <?= htmlspecialchars(ucfirst($row['recommendation'])) ?>
        </span>
        <?php else: ?><span style="color:#d1d5db;font-size:11px">—</span><?php endif; ?>
      </td>
      <td style="padding:8px 12px;text-align:center">
        <a href="review_assignment.php?id=<?= $row['submission_id'] ?>"
           style="color:#6366f1;font-size:14px" title="View">
          <i class="fas fa-external-link-alt"></i>
        </a>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>
</div>
<div style="padding:10px 16px;border-top:1px solid #f1f5f9;font-size:12px;color:#94a3b8">
  <?= count($rows) ?> review(s) submitted &nbsp;·&nbsp;
  Avg. days: <?=
    count(array_filter($rows, fn($r) => $r['days_taken'] !== null)) > 0
      ? round(array_sum(array_column($rows, 'days_taken')) / count(array_filter($rows, fn($r) => $r['days_taken'] !== null)), 1)
      : '—'
  ?> days
</div>
<?php endif; ?>