<?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 — Accounts';
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 modal -->
<style>
#jatrev-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;}
#jatrev-modal-backdrop.open{display:flex;}
#jatrev-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;}
#jatrev-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;}
#jatrev-modal-header h2{margin:0;font-size:17px;font-weight:800;}
#jatrev-modal-close{background:none;border:none;cursor:pointer;font-size:22px;color:var(--text-muted);}
#jatrev-modal-iframe{width:100%;border:none;display:block;min-height:600px;}
</style>
<div id="jatrev-modal-backdrop">
  <div id="jatrev-modal">
    <div id="jatrev-modal-header">
      <h2 id="jatrev-modal-title">KPI Detail</h2>
      <button type="button" id="jatrev-modal-close" onclick="closeJatRevModal()">✕</button>
    </div>
    <iframe id="jatrev-modal-iframe" src="" title="KPI Detail"></iframe>
  </div>
</div>

<div class="topbar">
  <div>
    <h1>KPI Review Queue — Accounts</h1>
    <div class="crumbs"><a href="/workspace" style="color:var(--blue-600);">Workspace</a> → Projects → KPI Tracker — Accounts</div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($user['name']) ?></div>
</div>

<div class="card">
  <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/jatinder-kpi/review" style="font-size:13px;color:var(--text-muted);">Clear</a>
  </form>

  <table>
    <thead><tr>
      <th>Submitted By</th><th>Week Starting</th><th>Week Ending</th>
      <th>Status</th><th>Score</th><th>Reviewer</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 submissions yet.</td></tr>
    <?php else: ?>
      <?php foreach ($records as $r): ?>
      <tr class="<?= $r['status']==='submitted'?'needs-action':'' ?>">
        <td style="font-weight:700;"><?= htmlspecialchars($r['submitter_name']) ?></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']] ?? '' ?>"><?= ucfirst($r['status']) ?></span></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="color:var(--text-muted);font-size:13px;"><?= htmlspecialchars($r['reviewer_name'] ?? '—') ?></td>
        <td>
          <button type="button" onclick="openJatRevModal('/projects/jatinder-kpi/view?id=<?= $r['id'] ?>&modal=1','<?= htmlspecialchars(addslashes($r['submitter_name'])) ?> — <?= $r['week_ending'] ?>')"
                  class="<?= $r['status']==='submitted'?'btn-primary':'btn-secondary' ?>" style="font-size:12px;padding:5px 14px;">
            <?= $r['status']==='submitted'?'Review':'View' ?>
          </button>
        </td>
      </tr>
      <?php endforeach; ?>
    <?php endif; ?>
    </tbody>
  </table>
</div>

<script>
function openJatRevModal(src,title){
  document.getElementById('jatrev-modal-title').textContent=title||'KPI Detail';
  document.getElementById('jatrev-modal-iframe').src=src;
  document.getElementById('jatrev-modal-backdrop').classList.add('open');
  document.body.style.overflow='hidden';
  document.getElementById('jatrev-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 closeJatRevModal(){
  document.getElementById('jatrev-modal-backdrop').classList.remove('open');
  document.getElementById('jatrev-modal-iframe').src='';
  document.body.style.overflow='';
}
document.getElementById('jatrev-modal-backdrop').addEventListener('click',function(e){if(e.target===this)closeJatRevModal();});
document.addEventListener('keydown',function(e){if(e.key==='Escape')closeJatRevModal();});
window.addEventListener('message',function(e){
  if(e.data&&(e.data.type==='kpi-saved'||e.data.type==='review-done')){closeJatRevModal();window.location.reload();}
});
</script>
<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
