<?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);
        }
    }
}
$pageTitle = "KPI Review Queue — César Saona";
$active    = 'home';
require __DIR__ . '/../layout/workspace_header.php';
?>

<!-- Modal for viewing/reviewing KPI details -->
<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);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-iframe{width:100%;border:none;display:block;min-height:600px;}
</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()">✕</button>
    </div>
    <iframe id="review-modal-iframe" src="" title="KPI Record"></iframe>
  </div>
</div>
<?php

$statusColors = [
    'draft'     => '#6b7280',
    'submitted' => '#2563eb',
    'reviewed'  => '#7c3aed',
    'approved'  => '#059669',
    'locked'    => '#059669',
    'returned'  => '#dc2626',
];
?>

<div class="topbar">
  <div>
    <h1>KPI Review Queue — Operations Manager</h1>
    <div class="crumbs">
      <a href="/workspace" style="color:var(--blue-600);">Workspace</a> →
      <a href="/projects/kpi" style="color:var(--blue-600);">Projects</a> → César KPI Review
    </div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:4px;">
      Reviewing weekly KPI submissions from César Saona — Operations Manager
    </div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($user['name']) ?></div>
</div>

<div class="card">
  <!-- Filters -->
  <form method="GET" style="display:flex;gap:12px;align-items:center;margin-bottom:22px;flex-wrap:wrap;">
    <select name="status" style="padding:8px 14px;border:1px solid var(--border);border-radius:10px;font-size:13px;">
      <option value="">All Statuses</option>
      <?php foreach (['draft','submitted','reviewed','locked','returned'] as $s): ?>
        <option value="<?= $s ?>" <?= ($_GET['status']??'')===$s?'selected':'' ?>><?= ucfirst($s) ?></option>
      <?php endforeach; ?>
    </select>
    <input type="date" name="from" value="<?= htmlspecialchars($_GET['from']??'') ?>"
           style="padding:8px 14px;border:1px solid var(--border);border-radius:10px;font-size:13px;">
    <input type="date" name="to" value="<?= htmlspecialchars($_GET['to']??'') ?>"
           style="padding:8px 14px;border:1px solid var(--border);border-radius:10px;font-size:13px;">
    <button type="submit" class="btn-secondary" style="padding:8px 18px;">Filter</button>
    <a href="/projects/cesar-kpi/review" style="font-size:13px;color:var(--text-muted);">Clear</a>
  </form>

  <!-- Summary counts -->
  <?php
  $countByStatus = [];
  foreach ($records as $r) {
    $countByStatus[$r['status']] = ($countByStatus[$r['status']] ?? 0) + 1;
  }
  $pending = ($countByStatus['submitted'] ?? 0);
  ?>
  <?php if ($pending > 0): ?>
  <div style="padding:12px 16px;background:#eff6ff;border:1px solid #bfdbfe;border-radius:12px;margin-bottom:18px;font-size:13px;color:#1d4ed8;">
    ⚠️ <strong><?= $pending ?></strong> entr<?= $pending===1?'y':'ies' ?> pending your review.
  </div>
  <?php endif; ?>

  <!-- Table -->
  <table>
    <thead>
      <tr>
        <th>Week Ending</th>
        <th>Status</th>
        <th>Submitted At</th>
        <th>Reviewer</th>
        <th>Score</th>
        <th>Review Comment</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
    <?php if (empty($records)): ?>
      <tr>
        <td colspan="7" style="text-align:center;color:var(--text-muted);padding:30px;">
          No KPI records found.
        </td>
      </tr>
    <?php else: ?>
      <?php foreach ($records as $r): ?>
      <tr class="<?= $r['status'] === 'submitted' ? 'needs-action' : ($r['status'] === 'returned' ? 'needs-action-red' : '') ?>">
        <td style="font-weight:700;"><?= fmtDate($r['week_ending']) ?></td>
        <td>
          <span style="display:inline-block;padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600;
            background:<?= $statusColors[$r['status']] ?? '#6b7280' ?>22;
            color:<?= $statusColors[$r['status']] ?? '#6b7280' ?>;">
            <?= ucfirst($r['status']) ?>
          </span>
        </td>
        <td style="color:var(--text-muted);font-size:13px;">
          <?= fmtDate($r['submitted_at']) ?>
        </td>
        <td style="color:var(--text-muted);font-size:13px;">
          <?= $r['reviewer_name'] ? htmlspecialchars($r['reviewer_name']) : '—' ?>
        </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 style="font-size:13px;max-width:220px;">
          <?php if ($r['review_comment']): ?>
            <span style="color:var(--text-muted);" title="<?= htmlspecialchars($r['review_comment']) ?>">
              <?= htmlspecialchars(mb_strimwidth($r['review_comment'], 0, 60, '…')) ?>
            </span>
          <?php else: ?>
            <span style="color:var(--text-muted);">—</span>
          <?php endif; ?>
        </td>
        <td>
          <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <button type="button"
                    onclick="openReviewModal('/projects/cesar-kpi/view?id=<?= $r['id'] ?>&modal=1','César KPI — <?= $r['week_ending'] ?>')"
                    class="<?= $r['status'] === 'submitted' ? 'btn-primary' : 'btn-secondary' ?>" style="font-size:12px;padding:5px 14px;">
              <?= $r['status'] === 'submitted' ? 'Review' : 'View' ?>
            </button>
            <?php if ($r['status'] === 'submitted'): ?>
              <form method="POST" action="/projects/cesar-kpi/review-action"
                    style="display:inline;" id="return-form-<?= $r['id'] ?>">
                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                <input type="hidden" name="action" value="return">
                <input type="hidden" name="reason" id="return-reason-<?= $r['id'] ?>">
                <button type="button"
                        style="font-size:12px;padding:5px 14px;background:none;border:1px solid #dc2626;
                               color:#dc2626;border-radius:8px;cursor:pointer;"
                        onclick="promptReturn(<?= $r['id'] ?>)">
                  ↩ Return
                </button>
              </form>
            <?php endif; ?>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
    <?php endif; ?>
    </tbody>
  </table>
</div>

<script>
function promptReturn(id) {
    const reason = prompt('Reason for returning this KPI entry to César:');
    if (!reason || !reason.trim()) return;
    document.getElementById('return-reason-' + id).value = reason.trim();
    document.getElementById('return-form-' + id).submit();
}
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';
  }
});
</script>
<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
