<?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 = "My KPI Records";
$active    = 'home';
require __DIR__ . '/../layout/workspace_header.php';

$statusColors = [
    'draft'     => '#6b7280',
    'submitted' => '#2563eb',
    'reviewed'  => '#7c3aed',
    'approved'  => '#059669',
    'locked'    => '#059669',
    'returned'  => '#dc2626',
];
$statusLabels = [
    'draft'     => 'Draft',
    'submitted' => 'Submitted — Awaiting Review',
    'reviewed'  => 'Reviewed',
    'approved'  => 'Approved',
    'locked'    => 'Approved & Locked',
    'returned'  => 'Returned — Needs Changes',
];

// Auto-open modal if we're coming back from a save (flash present) or if ?new=1
$autoOpen   = !empty($_GET['new']);
$editId     = (int)($_GET['edit'] ?? 0);
$modalSrc   = $editId ? "/projects/cesar-kpi/entry?id={$editId}&modal=1"
                      : "/projects/cesar-kpi/entry?modal=1";
?>

<!-- ═══ 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">César's 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 CONTENT ════════════════════════════════════════════════════════ -->
<div class="topbar">
  <div>
    <h1>My KPI Records</h1>
    <div class="crumbs">
      <a href="/workspace" style="color:var(--blue-600);">Workspace</a> →
      <a href="/projects/cesar-kpi" style="color:var(--blue-600);">KPI Tracker</a> → My Records
    </div>
  </div>
  <div style="display:flex;align-items:center;gap:14px;">
    <button type="button" class="btn-primary" onclick="openKpiModal('<?= htmlspecialchars($modalSrc) ?>', 'New Weekly KPI')">+ New Weekly KPI</button>
    <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($user['name']) ?></div>
  </div>
</div>

<?php if ($flash): ?>
<div style="padding:14px 20px;border-radius:12px;margin-bottom:16px;
  background:<?= $flash['type']==='success' ? '#ecfdf5' : '#fef2f2' ?>;
  border:1px solid <?= $flash['type']==='success' ? '#6ee7b7' : '#fca5a5' ?>;
  color:<?= $flash['type']==='success' ? '#065f46' : '#991b1b' ?>;font-size:14px;">
  <?= htmlspecialchars($flash['msg']) ?>
</div>
<?php endif; ?>

<?php
$returned = array_filter($records, fn($r) => $r['status'] === 'returned');
if (!empty($returned)):
?>
<div style="padding:14px 18px;background:#fef2f2;border:1px solid #fca5a5;border-radius:12px;margin-bottom:16px;font-size:13px;color:#991b1b;">
  ⚠️ <strong><?= count($returned) ?></strong> entr<?= count($returned)===1?'y':'ies' ?> returned by Sara — review the feedback and resubmit.
</div>
<?php endif; ?>

<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/cesar-kpi/my-records" style="font-size:13px;color:var(--text-muted);">Clear</a>
  </form>

  <table>
    <thead>
      <tr>
        <th>Week Starting</th>
        <th>Week Ending</th>
        <th>Status</th>
        <th>Submitted</th>
        <th>Reviewed By</th>
        <th>Score</th>
        <th>Reviewed At</th>
        <th>Sara's 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 yet. Click "+ New Weekly KPI" to get started.
        </td>
      </tr>
    <?php else: ?>
      <?php foreach ($records as $r):
        $sc = $statusColors[$r['status']] ?? '#6b7280';
        $sl = $statusLabels[$r['status']] ?? ucfirst($r['status']);
      ?>
      <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 style="display:inline-block;padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600;
            background:<?= $sc ?>22;color:<?= $sc ?>;">
            <?= $sl ?>
          </span>
        </td>
        <td style="color:var(--text-muted);font-size:13px;">
          <?= $r['submitted_at'] ? fmtDate($r['submitted_at']) : '—' ?>
        </td>
        <td style="font-size:13px;">
          <?= $r['reviewer_name'] ? htmlspecialchars($r['reviewer_name']) : '<span style="color:var(--text-muted);">Not yet reviewed</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;">
          <?= $r['reviewed_at'] ? fmtDate($r['reviewed_at']) : '—' ?>
        </td>
        <td style="font-size:13px;max-width:200px;">
          <?php if ($r['review_comment']): ?>
            <span title="<?= htmlspecialchars($r['review_comment']) ?>"
                  style="color:<?= $r['status']==='returned' ? '#dc2626' : 'var(--text-muted)' ?>;">
              <?= htmlspecialchars(mb_strimwidth($r['review_comment'], 0, 55, '…')) ?>
            </span>
          <?php else: ?>
            <span style="color:var(--text-muted);">—</span>
          <?php endif; ?>
        </td>
        <td>
          <?php if (in_array($r['status'], ['draft','returned'])): ?>
            <button type="button"
                    onclick="openKpiModal('/projects/cesar-kpi/entry?id=<?= $r['id'] ?>&modal=1','<?= $r['status']==='returned'?'Edit & Resubmit':'Edit KPI' ?>')"
                    class="<?= $r['status']==='returned'?'btn-primary':'btn-secondary' ?>"
                    style="font-size:12px;padding:5px 14px;">
              <?= $r['status']==='returned' ? 'Edit & Resubmit' : 'Edit' ?>
            </button>
          <?php else: ?>
            <a href="/projects/cesar-kpi/view?id=<?= $r['id'] ?>"
               class="btn-secondary" style="font-size:12px;padding:5px 14px;text-decoration:none;">View</a>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    <?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';

  // Auto-resize iframe to its content height
  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 = '';
}

// Close on backdrop click
document.getElementById('kpi-modal-backdrop').addEventListener('click', function(e) {
  if (e.target === this) closeKpiModal();
});

// Close on Escape key
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') closeKpiModal();
});

// Listen for messages from the iframe (after save/submit, reload the parent)
window.addEventListener('message', function(e) {
  if (e.data && e.data.type === 'kpi-saved') {
    closeKpiModal();
    window.location.reload();
  }
  if (e.data && e.data.type === 'kpi-submitted') {
    closeKpiModal();
    window.location.reload();
  }
  if (e.data && e.data.type === 'kpi-cancel') {
    closeKpiModal();
  }
});

<?php if ($autoOpen || $editId): ?>
// Auto-open modal on page load
window.addEventListener('DOMContentLoaded', function() {
  openKpiModal('<?= htmlspecialchars($modalSrc) ?>', '<?= $editId ? 'Edit KPI' : 'New Weekly KPI' ?>');
});
<?php endif; ?>
</script>

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