<?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 = 'My KPI Records';
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'];
$qs = $_GET;
?>

<!-- ═══ KPI MODAL ═══════════════════════════════════════════════════════════ -->
<style>
#kpi-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;
}
#kpi-modal-backdrop.open { display:flex; }
#kpi-modal {
  background:#fff;border-radius:20px;
  width:100%;max-width:900px;
  box-shadow:0 24px 80px rgba(0,0,0,0.22);
  position:relative;overflow:hidden;min-height:400px;
}
#kpi-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;
}
#kpi-modal-header h2 { margin:0;font-size:17px;font-weight:800;color:var(--navy-900); }
#kpi-modal-close {
  background:none;border:none;cursor:pointer;font-size:22px;
  color:var(--text-muted);line-height:1;padding:4px 8px;border-radius:8px;
}
#kpi-modal-close:hover { background:var(--bg);color:var(--text); }
#kpi-modal-iframe { width:100%;border:none;display:block;min-height:600px; }
</style>

<div id="kpi-modal-backdrop">
  <div id="kpi-modal">
    <div id="kpi-modal-header">
      <h2 id="kpi-modal-title">Weekly KPI Entry</h2>
      <button type="button" id="kpi-modal-close" onclick="closeKpiModal()" title="Close">✕</button>
    </div>
    <iframe id="kpi-modal-iframe" src="" title="KPI Entry Form"></iframe>
  </div>
</div>

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

<?php if (!empty($flash)): ?>
  <div class="alert alert-<?= $flash['type'] === 'error' ? 'error' : 'success' ?>"><?= htmlspecialchars($flash['msg']) ?></div>
<?php endif; ?>

<div class="card">
  <div class="toolbar">
    <form method="GET" action="/projects/kpi/my-records" 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 (['draft','submitted','reviewed','returned','locked'] as $s): ?>
            <option value="<?= $s ?>" <?= ($qs['status'] ?? '') === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="field" style="margin-bottom:0;">
        <label>Range</label>
        <select name="range" onchange="this.form.submit()" style="padding:10px;border:1px solid var(--border);border-radius:10px;">
          <option value="">All time</option>
          <option value="current_week" <?= ($qs['range'] ?? '') === 'current_week' ? 'selected' : '' ?>>Current Week</option>
          <option value="previous_week" <?= ($qs['range'] ?? '') === 'previous_week' ? 'selected' : '' ?>>Previous Week</option>
          <option value="current_month" <?= ($qs['range'] ?? '') === 'current_month' ? 'selected' : '' ?>>Current Month</option>
          <option value="current_year" <?= ($qs['range'] ?? '') === 'current_year' ? 'selected' : '' ?>>Current Year</option>
        </select>
      </div>
      <div class="field" style="margin-bottom:0;"><label>From</label><input type="date" name="from_date" value="<?= htmlspecialchars($qs['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</label><input type="date" name="to_date" value="<?= htmlspecialchars($qs['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($qs)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ CSV</a>
      <a href="/projects/kpi/export.xlsx?<?= htmlspecialchars(http_build_query($qs)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ Excel</a>
      <a href="/projects/kpi/export.pdf?<?= htmlspecialchars(http_build_query($qs)) ?>" class="btn-secondary" style="text-decoration:none;">⬇ PDF</a>
    </form>
    <button type="button" class="btn-primary" onclick="openKpiModal('/projects/kpi/entry?modal=1','New Weekly KPI')">+ New Weekly KPI</button>
  </div>

  <table>
    <thead><tr><th>Week Starting</th><th>Week Ending</th><th>Status</th><th>Total Hours</th><th>Incidents</th><th>Submitted</th><th>Score</th><th>Reviewer</th><th>Actions</th></tr></thead>
    <tbody>
      <?php foreach ($records as $r): ?>
        <tr class="<?= $r['status'] === 'returned' ? 'needs-action-red' : '' ?>">
          <td style="color:var(--text-muted);font-size:13px;"><?= $r['week_starting'] ? fmtDate($r['week_starting']) : '—' ?></td>
          <td style="font-weight:700;"><?= 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 style="color:var(--text-muted);font-size:12px;"><?= fmtDate($r['submitted_at']) ?></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>
            <?php if (in_array($r['status'], ['draft','returned'], true)): ?>
              <button type="button"
                      onclick="openKpiModal('/projects/kpi/entry?id=<?= $r['id'] ?>&modal=1','<?= $r['status']==='returned'?'Edit &amp; Resubmit':'Edit KPI' ?>')"
                      class="<?= $r['status']==='returned'?'btn-primary':'btn-secondary' ?>"
                      style="padding:6px 12px;font-size:12px;">
                <?= $r['status'] === 'returned' ? '✏️ Edit & Resubmit' : 'Edit' ?>
              </button>
            <?php else: ?>
              <a href="/projects/kpi/view?id=<?= $r['id'] ?>" class="btn-secondary" style="text-decoration:none;padding:6px 12px;font-size:12px;">View</a>
            <?php endif; ?>
            <a href="/projects/kpi/export.pdf?employee=<?= $user['user_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 if (empty($records)): ?>
        <tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:30px;">No KPI records yet. Click "+ New Weekly KPI" to submit your first one.</td></tr>
      <?php endif; ?>
    </tbody>
  </table>
</div>

<script>
function openKpiModal(src, title) {
  document.getElementById('kpi-modal-title').textContent = title || 'Weekly KPI Entry';
  document.getElementById('kpi-modal-iframe').src = src;
  document.getElementById('kpi-modal-backdrop').classList.add('open');
  document.body.style.overflow = 'hidden';
  document.getElementById('kpi-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 closeKpiModal() {
  document.getElementById('kpi-modal-backdrop').classList.remove('open');
  document.getElementById('kpi-modal-iframe').src = '';
  document.body.style.overflow = '';
}
document.getElementById('kpi-modal-backdrop').addEventListener('click', function(e) {
  if (e.target === this) closeKpiModal();
});
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') closeKpiModal();
});
window.addEventListener('message', function(e) {
  if (e.data && (e.data.type === 'kpi-saved' || e.data.type === 'kpi-submitted')) {
    closeKpiModal();
    window.location.reload();
  }
  if (e.data && e.data.type === 'kpi-cancel') closeKpiModal();
  if (e.data && e.data.type === 'kpi-resize') {
    var iframe = document.getElementById('kpi-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'; ?>
