<?php
if (!function_exists('fmtDate')) {
    function fmtDate($d, $t = false) {
        if (!$d || $d === '0000-00-00' || $d === '0000-00-00 00:00:00') return '—';
        try {
            $dt = new DateTime($d);
            return $t ? $dt->format('m/d/Y g:i A') : $dt->format('m/d/Y');
        } catch (Exception $e) {
            return htmlspecialchars((string)$d);
        }
    }
}
$active    = 'home';
$pageTitle = 'KPI Review Queue';
require __DIR__ . '/../layout/workspace_header.php';
$statusColors = ['draft'=>'badge-role-default','submitted'=>'badge-role-manager','reviewed'=>'badge-role-director','approved'=>'badge-role-employee','returned'=>'badge-role-ceo','locked'=>'badge-role-super'];
?>

<!-- ═══ REVIEW DETAIL MODAL ══════════════════════════════════════════════ -->
<style>
#review-modal-backdrop {
  display:none;position:fixed;inset:0;z-index:1000;
  background:rgba(15,23,42,0.55);backdrop-filter:blur(3px);
  align-items:flex-start;justify-content:center;padding:28px 16px;overflow-y:auto;
}
#review-modal-backdrop.open { display:flex; }
#review-modal {
  background:#fff;border-radius:20px;width:100%;max-width:960px;
  box-shadow:0 24px 80px rgba(0,0,0,0.22);position:relative;overflow:hidden;min-height:400px;
}
#review-modal-header {
  display:flex;justify-content:space-between;align-items:center;
  padding:18px 24px 14px;border-bottom:1px solid var(--border);
  background:#fff;position:sticky;top:0;z-index:10;
}
#review-modal-header h2 { margin:0;font-size:17px;font-weight:800;color:var(--navy-900); }
#review-modal-close { background:none;border:none;cursor:pointer;font-size:22px;color:var(--text-muted);line-height:1;padding:4px 8px;border-radius:8px; }
#review-modal-close:hover { background:var(--bg); }
#review-modal-iframe { width:100%;border:none;display:block;min-height:600px; }
/* Row the notification pointed at, so it is obvious which record is meant.
   Same pattern as the existing tr.needs-action highlight. */
tr.notif-target { background:rgba(79,110,247,0.10) !important; }
tr.notif-target td:first-child { border-left:3px solid #4F6EF7; }
tr.notif-target td { font-weight:600; }
@keyframes notifPulse { 0%,100% { background:rgba(79,110,247,0.10); } 50% { background:rgba(79,110,247,0.24); } }
tr.notif-target.pulse { animation:notifPulse 1s ease-in-out 2; }
</style>

<div id="review-modal-backdrop">
  <div id="review-modal">
    <div id="review-modal-header">
      <h2 id="review-modal-title">KPI Record</h2>
      <button type="button" id="review-modal-close" onclick="closeReviewModal()" title="Close">✕</button>
    </div>
    <iframe id="review-modal-iframe" src="" title="KPI Record"></iframe>
  </div>
</div>

<div class="topbar">
  <div>
    <h1>KPI Review Queue</h1>
    <div class="crumbs"><a href="/workspace" style="color:var(--blue-600);">Workspace</a> → Projects → KPI Tracker</div>
  </div>
  <div style="display:flex;align-items:center;gap:12px;">
    <?php if ($user['is_super_admin'] || \App\Models\CesarKpi::canReview($user)): ?>
      <?php $cesarPending = count(\App\Models\CesarKpi::all(['status'=>'submitted'])); ?>
      <a href="/projects/cesar-kpi/review" class="btn-secondary" style="text-decoration:none;font-size:13px;">
        Operations Manager KPI
        <?php if ($cesarPending > 0): ?>
          <span style="background:#dc2626;color:#fff;border-radius:20px;font-size:11px;font-weight:700;padding:1px 7px;margin-left:6px;"><?= $cesarPending ?></span>
        <?php endif; ?>
      </a>
    <?php endif; ?>
    <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($user['name']) ?></div>
  </div>
</div>

<div class="card">
  <div style="margin-bottom:20px;">
    <form method="GET" action="/projects/kpi/review" style="display:flex;gap:10px;flex-wrap:wrap;align-items:end;">
      <div class="field" style="margin-bottom:0;">
        <label>Status</label>
        <select name="status" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;">
          <option value="">All</option>
          <?php foreach (['submitted','reviewed','locked','returned','draft'] as $s): ?>
            <option value="<?= $s ?>" <?= ($_GET['status']??'')===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="field" style="margin-bottom:0;"><label>From Date</label><input type="date" name="from_date" value="<?= htmlspecialchars($_GET['from_date']??'') ?>" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;"></div>
      <div class="field" style="margin-bottom:0;"><label>To Date</label><input type="date" name="to_date" value="<?= htmlspecialchars($_GET['to_date']??'') ?>" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;"></div>
      <a href="/projects/kpi/export.csv?<?= htmlspecialchars(http_build_query($_GET)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ CSV</a>
      <a href="/projects/kpi/export.xlsx?<?= htmlspecialchars(http_build_query($_GET)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ Excel</a>
      <a href="/projects/kpi/export.pdf?<?= htmlspecialchars(http_build_query($_GET)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ PDF</a>
    </form>
  </div>

  <?php $pendingCount = count(array_filter($records, fn($r) => $r['status'] === 'submitted')); ?>
  <?php if ($pendingCount > 0): ?>
  <div style="padding:12px 16px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:12px;margin-bottom:16px;font-size:13px;color:#1d4ed8;">
    ⚠️ <strong><?= $pendingCount ?></strong> entr<?= $pendingCount===1?'y':'ies' ?> pending review — click <strong>Review</strong> to take action
  </div>
  <?php endif; ?>

  <table>
    <thead>
      <tr><th>Submitted By</th><th>Week Starting</th><th>Week Ending</th><th>Status</th><th>Total Hours</th><th>Incidents</th><th>Score</th><th>Reviewer</th><th>Actions</th></tr>
    </thead>
    <tbody>
      <?php if (empty($records)): ?>
        <tr><td colspan="9" style="text-align:center;color:var(--text-muted);padding:30px;">No KPI submissions yet.</td></tr>
      <?php else: ?>
      <?php
        // Which of these records carry a submitter response, and which are
        // still waiting on the reviewer. Read-only lookup; nothing else on
        // this page changes.
        // Record the notification chip pointed at (?highlight=ID), so the
        // matching row can be visibly marked. Read-only; no other behaviour.
        $__highlightId  = (int)($_GET['highlight'] ?? 0);
        $__recIds       = array_map(fn($x) => (int)$x['id'], $records);
        $__awaitingIds  = \App\Models\KpiDiscussion::entryIdsAwaitingResponse($__recIds, 'submitter');
        $__awaitingSet  = array_flip($__awaitingIds);
      ?>
      <?php foreach ($records as $r): ?>
        <?php
          $__hasResponse = isset($__awaitingSet[(int)$r['id']]);
          $__isTarget    = $__highlightId && (int)$r['id'] === $__highlightId;
          $__rowClasses  = trim(($r['status'] === 'submitted' ? 'needs-action' : '') . ($__isTarget ? ' notif-target pulse' : ''));
        ?>
        <tr class="<?= $__rowClasses ?>"<?= $__isTarget ? ' id="kpi-row-' . (int)$r['id'] . '"' : '' ?>>
          <td style="font-weight:700;">
            <?= htmlspecialchars($r['submitter_name']) ?>
            <?php if ($__hasResponse): ?>
              <span title="This person has responded to your review comment"
                    style="display:inline-block;margin-left:6px;background:#E5EAFE;color:#3049C4;border-radius:20px;padding:2px 8px;font-size:11px;font-weight:600;vertical-align:middle;">💬 Response</span>
            <?php endif; ?>
          </td>
          <td style="color:var(--text-muted);font-size:13px;"><?= $r['week_starting'] ? fmtDate($r['week_starting']) : '—' ?></td>
          <td><?= fmtDate($r['week_ending']) ?></td>
          <td><span class="badge <?= $statusColors[$r['status']] ?? 'badge-role-default' ?>"><?= ucfirst($r['status']) ?></span></td>
          <td><?= htmlspecialchars($r['total_hours'] ?? '—') ?></td>
          <td><?= htmlspecialchars($r['incidents'] ?? '—') ?></td>
          <td>
            <?php if ($r['review_score'] ?? 0): ?>
              <span style="background:#FAEEDA;color:#633806;border-radius:8px;padding:3px 10px;font-size:13px;font-weight:600;">
                <?= (int)$r['review_score'] ?>/10<?= !empty($r['score_revised']) ? ' ✎' : '' ?>
              </span>
            <?php else: ?>
              <span style="color:var(--text-muted);">—</span>
            <?php endif; ?>
          </td>
          <td><?= htmlspecialchars($r['reviewer_name'] ?? '—') ?></td>
          <td>
            <button type="button"
                    onclick="openReviewModal('/projects/kpi/view?id=<?= $r['id'] ?>&modal=1','<?= htmlspecialchars(addslashes($r['submitter_name'])) ?> — <?= $r['week_ending'] ?>')"
                    class="<?= $r['status'] === 'submitted' ? 'btn-primary' : 'btn-secondary' ?>"
                    style="padding:6px 14px;font-size:12px;">
              <?= in_array($r['status'], ['submitted','reviewed'], true) ? 'Review' : 'View' ?>
            </button>
            <a href="/projects/kpi/export.pdf?employee=<?= $r['submitter_id'] ?>&week_ending=<?= $r['week_ending'] ?>" class="btn-secondary" style="text-decoration:none;padding:6px 12px;font-size:12px;">⬇</a>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>
</div>

<script>
function openReviewModal(src, title) {
  document.getElementById('review-modal-title').textContent = title || 'KPI Record';
  document.getElementById('review-modal-iframe').src = src;
  document.getElementById('review-modal-backdrop').classList.add('open');
  document.body.style.overflow = 'hidden';
  document.getElementById('review-modal-iframe').onload = function() {
    try {
      var h = this.contentWindow.document.body.scrollHeight;
      this.style.height = Math.min(Math.max(h + 40, 500), window.innerHeight - 120) + 'px';
    } catch(e) { this.style.height = '80vh'; }
  };
}
function closeReviewModal() {
  document.getElementById('review-modal-backdrop').classList.remove('open');
  document.getElementById('review-modal-iframe').src = '';
  document.body.style.overflow = '';
  window.location.reload();
}
document.getElementById('review-modal-backdrop').addEventListener('click', function(e) {
  if (e.target === this) closeReviewModal();
});
document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeReviewModal(); });
window.addEventListener('message', function(e) {
  if (e.data && e.data.type === 'kpi-resize') {
    var iframe = document.getElementById('review-modal-iframe');
    if (iframe) iframe.style.height = Math.min(e.data.height + 40, window.innerHeight - 120) + 'px';
  }
});

// When arrived here from a notification (?highlight=ID), bring the matching
// row into view so it is obvious which record the notification referred to.
// Purely visual — no data or workflow behaviour is affected.
(function() {
  var m = window.location.search.match(/[?&]highlight=(\d+)/);
  if (!m) return;
  var row = document.getElementById('kpi-row-' + m[1]);
  if (!row) return;
  try { row.scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (err) { row.scrollIntoView(); }
})();
</script>

<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
