<?php
/**
 * ajax/reviewer_assignments_modal.php
 * Returns HTML: list of all review assignments for a specific reviewer
 * in the given date range. Opened from Tab 2 (Reviewer Load).
 */
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(ra.request_sent_date) = CURDATE()", []];
        case 'yesterday': return ["DATE(ra.request_sent_date) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)", []];
        case 'custom':
            if ($from && $to)   return ["DATE(ra.request_sent_date) BETWEEN ? AND ?", [$from, $to]];
            if ($from)          return ["DATE(ra.request_sent_date) >= ?", [$from]];
            if ($to)            return ["DATE(ra.request_sent_date) <= ?", [$to]];
            return ["1=1", []];
        default:
            $days = is_numeric($range) ? (int)$range : 7;
            return ["ra.request_sent_date >= DATE_SUB(NOW(), INTERVAL $days DAY)", []];
    }
}

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

try {
    $stmt = $pdo->prepare("
        SELECT
            ra.id               AS assignment_id,
            ra.submission_id,
            ra.assignment_status,
            ra.request_sent_date,
            ra.review_due_date,
            ra.accepted_date,
            ra.submitted_date,
            ra.declined_date,

            s.tracking_code,
            s.submitted_at,
            s.submission_status,

            mi.article_title,

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

            j.name AS journal_name

        FROM review_assignments ra
        JOIN submissions s     ON s.submission_id = ra.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
        WHERE ra.reviewer_id = ?
          AND $dateWhere
        ORDER BY ra.request_sent_date 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;
}

$statusColors = [
    'request_sent'      => 'bg-blue-100 text-blue-700',
    'accepted'          => 'bg-indigo-100 text-indigo-700',
    'review_submitted'  => 'bg-green-100 text-green-700',
    'declined'          => 'bg-red-100 text-red-700',
    'cancelled'         => 'bg-gray-100 text-gray-500',
];
?>
<?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 assignments found for 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">Author</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">Due Date</th>
      <th style="padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase">Status</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):
      $statusClass = $statusColors[$row['assignment_status']] ?? 'bg-gray-100 text-gray-500';
      $isOverdue   = $row['review_due_date'] && $row['review_due_date'] < date('Y-m-d')
                     && !in_array($row['assignment_status'], ['review_submitted','declined','cancelled']);
      $rowBg       = $isOverdue ? 'background:#fef2f2' : '';
    ?>
    <tr style="border-bottom:1px solid #f1f5f9;<?= $rowBg ?>">
      <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['journal_name'] ?? '') ?></div>
      </td>
      <td style="padding:8px 12px">
        <div style="font-size:12px;color:#374151"><?= htmlspecialchars(trim($row['author_name'])) ?></div>
        <div style="font-size:11px;color:#94a3b8"><?= 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;white-space:nowrap">
        <span style="font-size:11px;color:<?= $isOverdue ? '#dc2626' : '#6b7280' ?>;font-weight:<?= $isOverdue ? '700' : '400' ?>">
          <?= $row['review_due_date'] ? date('d M Y', strtotime($row['review_due_date'])) : '—' ?>
          <?= $isOverdue ? ' ⚠' : '' ?>
        </span>
      </td>
      <td style="padding:8px 12px">
        <span style="display:inline-flex;align-items:center;padding:2px 8px;border-radius:9999px;font-size:10px;font-weight:700"
              class="<?= $statusClass ?>">
          <?= ucwords(str_replace('_', ' ', $row['assignment_status'])) ?>
        </span>
      </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 Assignment">
          <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) ?> assignment(s) found &nbsp;·&nbsp;
  <?php $over = array_sum(array_map(fn($r) => ($r['review_due_date'] && $r['review_due_date'] < date('Y-m-d') && !in_array($r['assignment_status'],['review_submitted','declined','cancelled'])) ? 1 : 0, $rows)); ?>
  <?php if ($over): ?><span style="color:#dc2626;font-weight:700"><?= $over ?> overdue</span><?php endif; ?>
</div>
<?php endif; ?>