<?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 Entry — Week of ' . ($entry['week_ending'] ?? '');
$active    = 'home';
$isModalMode = !empty($_GET['modal']);
$isReviewer = \App\Models\CesarKpi::canReview($user);

if (!$isModalMode) {
    require __DIR__ . '/../layout/workspace_header.php';
} else {
    ?><!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="stylesheet" href="/assets/css/app.css?v=<?= defined('ASSET_VERSION') ? ASSET_VERSION : time() ?>">
    <style>body,.admin-shell{background:#fff!important;}.main-inner{padding:20px 24px 32px!important;}.sidebar{display:none!important;}.main{margin:0!important;}</style>
    </head><body><div class="admin-shell"><main class="main"><div class="main-inner">
    <?php
}

function siteLabel(array $sites, $siteId, string $fallback = ''): string {
    foreach ($sites as $s) {
        if ($s['id'] == $siteId) return $s['name'];
    }
    return $fallback ?: ('Site #' . $siteId);
}

$contractsStarted = \App\Models\CesarKpi::decodeJson($entry['contracts_started'] ?? null);
$contractsLost    = \App\Models\CesarKpi::decodeJson($entry['contracts_lost']    ?? null);
$postOrders       = \App\Models\CesarKpi::decodeJson($entry['post_order_updates'] ?? null);
$meetings         = \App\Models\CesarKpi::decodeJson($entry['client_meetings']   ?? null);
$siteScores       = \App\Models\CesarKpi::decodeJson($entry['site_visit_scores'] ?? null);
$reachouts        = \App\Models\CesarKpi::decodeJson($entry['new_client_reachouts'] ?? null);
$renewals         = \App\Models\CesarKpi::decodeJson($entry['contract_renewals'] ?? null);

$statusColors = [
    'draft'=>'#6b7280','submitted'=>'#2563eb','reviewed'=>'#7c3aed',
    'approved'=>'#059669','locked'=>'#059669','returned'=>'#dc2626'
];
$sc = $statusColors[$entry['status']] ?? '#6b7280';
?>
<style>
.vcard { background:#fff;border:1px solid var(--border);border-radius:16px;padding:22px 26px;margin-bottom:18px; }
.vcard h3 { font-size:12px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--text-muted);margin:0 0 16px; }
.vrow { border:1px solid var(--border);border-radius:10px;padding:14px 16px;margin-bottom:10px;background:#fbfcfe; }
.vgrid-3 { display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px; }
.vgrid-2 { display:grid;grid-template-columns:1fr 1fr;gap:12px; }
.vfld label { font-size:11px;font-weight:700;letter-spacing:.05em;text-transform:uppercase;color:var(--text-muted);display:block;margin-bottom:3px; }
.vfld .val { font-size:14px;color:var(--text); }
.score-table { width:100%;border-collapse:separate;border-spacing:0 10px; }
.score-table td { vertical-align:top;padding:0 8px 0 0; }
</style>

<div class="topbar">
  <div>
    <h1>Operations Manager KPI — <?= fmtDate($entry['week_ending']) ?></h1>
    <div class="crumbs">
      <?php if ($isReviewer): ?>
        <a href="/projects/cesar-kpi/review" style="color:var(--blue-600);">Review Queue</a> →
      <?php else: ?>
        <a href="/projects/cesar-kpi/my-records" style="color:var(--blue-600);">My KPI Records</a> →
      <?php endif; ?>
      Week of <?= fmtDate($entry['week_ending']) ?>
    </div>
  </div>
  <div style="display:flex;align-items:center;gap:14px;">
    <span style="padding:5px 16px;border-radius:20px;font-size:13px;font-weight:600;background:<?= $sc ?>22;color:<?= $sc ?>;">
      <?= ucfirst($entry['status']) ?>
    </span>
    <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($user['name']) ?></div>
  </div>
</div>

<!-- Reviewer action panel -->
<?php if ($isReviewer && $entry['status'] === 'submitted'): ?>
<div class="vcard" style="background:#f0f4ff;border-color:#c7d2fe;">
  <h3>Review Actions</h3>
  <form method="POST" action="/projects/cesar-kpi/review-action"
        onsubmit="return validateCesarApprove(this);">
    <input type="hidden" name="id" value="<?= $entry['id'] ?>">
    <input type="hidden" name="action" value="approve">
    <?php if ($isModalMode): ?><input type="hidden" name="modal" value="1"><?php endif; ?>
    <div style="display:grid;grid-template-columns:140px 1fr;gap:12px;margin-bottom:14px;">
      <div>
        <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted);display:block;margin-bottom:6px;">Score (1–10) <span style="color:#dc2626;">*</span></label>
        <input type="number" name="review_score" id="cesar_rs_<?= $entry['id'] ?>" min="1" max="10" step="1" placeholder="8"
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted);display:block;margin-bottom:6px;">Review comments <span style="color:#dc2626;">*</span></label>
        <input type="text" name="review_comment_approve" id="cesar_rc_<?= $entry['id'] ?>" placeholder="What went well, areas to improve..."
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
      </div>
    </div>
    <button type="submit" class="btn-primary">✓ Approve &amp; Lock</button>
  </form>
  <form method="POST" action="/projects/cesar-kpi/review-action" style="display:flex;gap:10px;align-items:center;margin-top:12px;flex-wrap:wrap;">
    <input type="hidden" name="id" value="<?= $entry['id'] ?>">
    <input type="hidden" name="action" value="return">
    <?php if ($isModalMode): ?><input type="hidden" name="modal" value="1"><?php endif; ?>
    <input type="text" name="reason" placeholder="Reason for returning..." required
           style="flex:1;min-width:260px;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:13px;">
    <button type="submit" class="btn-secondary">↩ Return</button>
  </form>
</div>
<script>
function validateCesarApprove(form) {
  var score = form.querySelector('[name="review_score"]').value;
  var comment = form.querySelector('[name="review_comment_approve"]').value.trim();
  if (!score || score < 1 || score > 10) { alert('Please enter a score between 1 and 10 before approving.'); return false; }
  if (!comment) { alert('Please enter review comments before approving.'); return false; }
  return confirm('Approve and lock this KPI entry?');
}
</script>
<?php endif; ?>

<?php
$cesarReviewHistory = ($entry['status'] === 'locked' && ($entry['review_score'] ?? 0))
    ? \App\Models\CesarKpi::reviewHistory($entry['id']) : [];
?>
<?php if ($entry['status'] === 'locked' && ($entry['review_score'] ?? 0)): ?>
<div class="vcard" style="border-left:3px solid #3B6D11;border-radius:0 12px 12px 0;margin-bottom:18px;">
  <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:12px;">
    <div>
      <div style="font-size:13px;font-weight:700;color:#3B6D11;">KPI review completed</div>
      <div style="font-size:12px;color:var(--text-muted);margin-top:2px;">
        Reviewed by <?= htmlspecialchars($entry['reviewer_name'] ?? '—') ?>
        <?= $entry['reviewed_at'] ? ' · ' . fmtDate($entry['reviewed_at']) : '' ?>
        <?php if (!empty($cesarReviewHistory)): ?>
          &nbsp;<span style="font-size:11px;color:var(--blue-600);"><?= count($cesarReviewHistory) ?> revision<?= count($cesarReviewHistory)>1?'s':'' ?></span>
        <?php endif; ?>
      </div>
    </div>
    <span style="background:#EAF3DE;color:#3B6D11;padding:4px 12px;border-radius:20px;font-size:12px;font-weight:600;">Approved &amp; Locked</span>
  </div>
  <div style="display:grid;grid-template-columns:120px 1fr;gap:14px;margin-bottom:12px;">
    <div>
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted);margin-bottom:4px;">Score</div>
      <div style="font-size:20px;font-weight:800;color:#633806;background:#FAEEDA;display:inline-block;padding:4px 14px;border-radius:8px;"><?= (int)$entry['review_score'] ?> / 10</div>
    </div>
    <div>
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted);margin-bottom:4px;">Reviewer comments</div>
      <div style="font-size:14px;"><?= nl2br(htmlspecialchars($entry['review_comment'] ?? '—')) ?></div>
    </div>
  </div>
  <?php if ($isReviewer): ?>
  <details style="margin-top:8px;">
    <summary style="font-size:12px;color:var(--blue-600);cursor:pointer;">✎ Revise rating</summary>
    <form method="POST" action="/projects/cesar-kpi/review-action" style="margin-top:12px;"
          onsubmit="if(!this.new_score.value||!this.revise_reason.value.trim()){alert('New score and reason are required.');return false;}return confirm('Save revised rating?');">
      <input type="hidden" name="id" value="<?= $entry['id'] ?>">
      <input type="hidden" name="action" value="revise_score">
      <?php if ($isModalMode): ?><input type="hidden" name="modal" value="1"><?php endif; ?>
      <div style="display:grid;grid-template-columns:130px 1fr;gap:12px;margin-bottom:10px;">
        <div>
          <label style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);display:block;margin-bottom:4px;">New score (1–10)</label>
          <input type="number" name="new_score" min="1" max="10" step="1" value="<?= (int)$entry['review_score'] ?>"
                 style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
        </div>
        <div>
          <label style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);display:block;margin-bottom:4px;">Updated comments</label>
          <input type="text" name="new_comment" value="<?= htmlspecialchars($entry['review_comment'] ?? '') ?>"
                 style="width:100%;padding:8px 12px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
        </div>
      </div>
      <div style="display:flex;gap:10px;align-items:center;">
        <input type="text" name="revise_reason" placeholder="Reason for revision (required)" required
               style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:8px;font-size:13px;">
        <button type="submit" class="btn-secondary">Save revision</button>
      </div>
    </form>
    <?php if (!empty($cesarReviewHistory)): ?>
    <div style="margin-top:12px;border-top:1px solid var(--border);padding-top:10px;">
      <div style="font-size:11px;font-weight:700;text-transform:uppercase;color:var(--text-muted);margin-bottom:8px;">Revision history</div>
      <?php foreach ($cesarReviewHistory as $rh): ?>
      <div style="font-size:12px;color:var(--text-muted);padding:6px 0;border-bottom:0.5px solid var(--border);">
        <strong style="color:var(--text);"><?= htmlspecialchars($rh['revised_by_name']) ?></strong>
        changed score from <strong><?= $rh['previous_score'] ?? '—' ?>/10</strong> to <strong><?= $rh['new_score'] ?>/10</strong>
        · <?= fmtDate($rh['created_at']) ?>
        <br><span style="color:var(--text-muted);">Reason: <?= htmlspecialchars($rh['revised_reason']) ?></span>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </details>
  <?php endif; ?>
</div>
<?php endif; ?>

<?php if ($entry['review_comment'] && $entry['status'] === 'returned'): ?>
<div style="padding:18px 22px;background:#fef2f2;border:1.5px solid #fca5a5;border-radius:14px;margin-bottom:18px;display:flex;gap:16px;align-items:flex-start;">
  <div style="font-size:22px;line-height:1;">↩</div>
  <div style="flex:1;">
    <div style="font-weight:800;font-size:14px;color:#991b1b;margin-bottom:4px;">Returned by <?= htmlspecialchars($entry['reviewer_name'] ?? 'Reviewer') ?> · <?= fmtDate($entry['reviewed_at'] ?? '') ?></div>
    <div style="font-size:14px;color:#7f1d1d;"><?= nl2br(htmlspecialchars($entry['review_comment'])) ?></div>
    <?php if (\App\Models\CesarKpi::canSubmit($user)): ?>
    <div style="margin-top:12px;">
      <a href="/projects/cesar-kpi/entry?id=<?= $entry['id'] ?>" class="btn-primary" style="text-decoration:none;">✏️ Edit &amp; Resubmit →</a>
    </div>
    <?php endif; ?>
  </div>
</div>
<?php elseif ($entry['review_comment']): ?>
<div class="vcard" style="background:#fef3c7;border-color:#fcd34d;">
  <h3>Reviewer Comment</h3>
  <p style="margin:0;font-size:14px;"><?= nl2br(htmlspecialchars($entry['review_comment'])) ?></p>
  <p style="margin:8px 0 0;font-size:12px;color:var(--text-muted);"><?= htmlspecialchars($entry['reviewer_name'] ?? '') ?> · <?= fmtDate($entry['reviewed_at'] ?? '') ?></p>
</div>
<?php endif; ?>

<!-- Contracts Started -->
<div class="vcard">
  <h3>Hours Pipeline — Contracts Started</h3>
  <?php if (empty($contractsStarted)): ?><p style="color:var(--text-muted);font-size:13px;">None recorded.</p>
  <?php else: foreach ($contractsStarted as $cs): ?>
  <div class="vrow">
    <div class="vgrid-3">
      <div class="vfld"><label>Site / Contract</label><div class="val"><?= htmlspecialchars($cs['site_name'] ?: ($cs['custom_name'] ?: '—')) ?></div></div>
      <div class="vfld"><label>Custom Name</label><div class="val"><?= htmlspecialchars($cs['custom_name'] ?: '—') ?></div></div>
      <div class="vfld"><label>Total Hours</label><div class="val"><?= htmlspecialchars($cs['hours'] ?? '0') ?></div></div>
    </div>
  </div>
  <?php endforeach; endif; ?>
</div>

<!-- Contracts Lost -->
<div class="vcard">
  <h3>Hours Pipeline — Contracts Lost</h3>
  <?php if (empty($contractsLost)): ?><p style="color:var(--text-muted);font-size:13px;">None recorded.</p>
  <?php else: foreach ($contractsLost as $cl): ?>
  <div class="vrow">
    <div class="vgrid-3" style="margin-bottom:10px;">
      <div class="vfld"><label>Site / Contract</label><div class="val"><?= htmlspecialchars($cl['site_name'] ?: ($cl['custom_name'] ?: '—')) ?></div></div>
      <div class="vfld"><label>Custom Name</label><div class="val"><?= htmlspecialchars($cl['custom_name'] ?: '—') ?></div></div>
      <div class="vfld"><label>Total Hours</label><div class="val"><?= htmlspecialchars($cl['hours'] ?? '0') ?></div></div>
    </div>
    <div class="vfld"><label>Comments</label><div class="val"><?= nl2br(htmlspecialchars($cl['comments'] ?? '—')) ?></div></div>
  </div>
  <?php endforeach; endif; ?>
  <div style="margin-top:12px;">
    <span style="font-size:13px;color:var(--text-muted);">Net hours change: </span>
    <strong><?= htmlspecialchars($entry['net_hours_change'] ?? '—') ?></strong>
  </div>
</div>

<!-- Post Order Updates -->
<div class="vcard">
  <h3>Post Order Updates</h3>
  <?php if (empty($postOrders)): ?><p style="color:var(--text-muted);font-size:13px;">None recorded.</p>
  <?php else: foreach ($postOrders as $po): ?>
  <div class="vrow">
    <div class="vgrid-2">
      <div class="vfld"><label>Site</label><div class="val"><?= htmlspecialchars($po['site_name'] ?: '—') ?></div></div>
      <div class="vfld"><label>Comments / What Changed</label><div class="val"><?= nl2br(htmlspecialchars($po['comments'] ?? '—')) ?></div></div>
    </div>
  </div>
  <?php endforeach; endif; ?>
</div>

<!-- Client Meetings -->
<div class="vcard">
  <h3>Client Meetings</h3>
  <?php if (empty($meetings)): ?><p style="color:var(--text-muted);font-size:13px;">None recorded.</p>
  <?php else: foreach ($meetings as $m): ?>
  <div class="vrow">
    <div class="vgrid-2" style="margin-bottom:10px;">
      <div class="vfld"><label>Site Visited</label><div class="val"><?= htmlspecialchars($m['site_name'] ?: '—') ?></div></div>
      <div class="vfld"><label>Client Name</label><div class="val"><?= htmlspecialchars($m['client_name'] ?? '—') ?></div></div>
    </div>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:12px;">
      <div class="vfld"><label>Meeting Notes</label><div class="val"><?= nl2br(htmlspecialchars($m['meeting_notes'] ?? '—')) ?></div></div>
      <div class="vfld"><label>Open Notes / Follow-up</label><div class="val"><?= nl2br(htmlspecialchars($m['open_notes'] ?? '—')) ?></div></div>
      <div class="vfld"><label>Satisfaction</label><div class="val"><?= htmlspecialchars($m['satisfaction'] ?: '—') ?></div></div>
      <div class="vfld"><label>Risk Level</label><div class="val"><?= htmlspecialchars($m['risk_level'] ?: '—') ?></div></div>
    </div>
  </div>
  <?php endforeach; endif; ?>
</div>

<!-- Site Visit Scores -->
<div class="vcard">
  <h3>Site Visit Scores</h3>
  <?php if (empty($siteScores)): ?><p style="color:var(--text-muted);font-size:13px;">None recorded.</p>
  <?php else: foreach ($siteScores as $ss): ?>
  <div class="vrow">
    <div style="display:grid;grid-template-columns:1.6fr 100px 1fr;gap:12px;">
      <div class="vfld"><label>Site</label><div class="val"><?= htmlspecialchars($ss['site_name'] ?: '—') ?></div></div>
      <div class="vfld"><label>Score (1–5)</label><div class="val"><?= htmlspecialchars($ss['score'] ?? '—') ?></div></div>
      <div class="vfld"><label>Reason / Comments</label><div class="val"><?= nl2br(htmlspecialchars($ss['reason'] ?? '—')) ?></div></div>
    </div>
  </div>
  <?php endforeach; endif; ?>
</div>

<!-- New Client Reach Out -->
<div class="vcard">
  <h3>New Client Reach Out</h3>
  <?php if (empty($reachouts)): ?><p style="color:var(--text-muted);font-size:13px;">None recorded.</p>
  <?php else: foreach ($reachouts as $ro): ?>
  <div class="vrow">
    <div class="vgrid-3" style="margin-bottom:10px;">
      <div class="vfld"><label>Client / Company</label><div class="val"><?= htmlspecialchars($ro['company_name'] ?? '—') ?></div></div>
      <div class="vfld"><label>Contact Name</label><div class="val"><?= htmlspecialchars($ro['contact_name'] ?? '—') ?></div></div>
      <div class="vfld"><label>Phone</label><div class="val"><?= htmlspecialchars($ro['phone'] ?? '—') ?></div></div>
    </div>
    <div class="vfld"><label>What Happened / Next Steps</label><div class="val"><?= nl2br(htmlspecialchars($ro['notes'] ?? '—')) ?></div></div>
  </div>
  <?php endforeach; endif; ?>
</div>

<!-- Contract Renewals -->
<div class="vcard">
  <h3>Contract Renewals</h3>
  <?php if (empty($renewals)): ?><p style="color:var(--text-muted);font-size:13px;">None recorded.</p>
  <?php else: foreach ($renewals as $rn): ?>
  <div class="vrow">
    <div class="vgrid-2" style="margin-bottom:10px;">
      <div class="vfld"><label>Site</label><div class="val"><?= htmlspecialchars($rn['site_name'] ?: '—') ?></div></div>
      <div class="vfld"><label>Client Name</label><div class="val"><?= htmlspecialchars($rn['client_name'] ?? '—') ?></div></div>
    </div>
    <div class="vgrid-2">
      <div class="vfld"><label>Rate Increase?</label><div class="val"><?= htmlspecialchars($rn['rate_increase'] ?: '—') ?></div></div>
      <div class="vfld"><label>Notes</label><div class="val"><?= htmlspecialchars($rn['notes'] ?? '—') ?></div></div>
    </div>
  </div>
  <?php endforeach; endif; ?>
</div>

<!-- OT vs Budget -->
<div class="vcard">
  <h3>OT vs Budget</h3>
  <div style="display:grid;grid-template-columns:180px 180px 180px;gap:20px;">
    <div class="vfld"><label>Budgeted OT Hours</label><div class="val"><?= htmlspecialchars($entry['ot_budgeted'] ?? '0') ?></div></div>
    <div class="vfld"><label>Actual OT Hours</label><div class="val"><?= htmlspecialchars($entry['ot_actual'] ?? '0') ?></div></div>
    <div class="vfld"><label>Variance</label>
      <div class="val"><?= htmlspecialchars($entry['ot_variance'] ?? '—') ?>
        <span style="font-size:12px;color:var(--text-muted);">(Negative = over budget)</span>
      </div>
    </div>
  </div>
</div>

<!-- Escalations -->
<div class="vcard">
  <h3>Escalations &amp; Open Investigations</h3>
  <div style="display:grid;grid-template-columns:160px 1fr 160px 1fr;gap:14px;">
    <div class="vfld"><label>Open Investigations</label><div class="val"><?= (int)($entry['open_investigations'] ?? 0) ?></div></div>
    <div class="vfld"><label>Investigation Description</label><div class="val"><?= htmlspecialchars($entry['investigation_desc'] ?: '—') ?></div></div>
    <div class="vfld"><label>Escalations Received</label><div class="val"><?= (int)($entry['escalations_received'] ?? 0) ?></div></div>
    <div class="vfld"><label>From Who + Summary</label><div class="val"><?= htmlspecialchars($entry['escalations_from_summary'] ?: '—') ?></div></div>
  </div>
</div>

<div style="padding-bottom:32px;">
  <?php if ($isReviewer): ?>
    <a href="/projects/cesar-kpi/review" class="btn-secondary" style="text-decoration:none;">← Back to Review Queue</a>
  <?php else: ?>
    <a href="/projects/cesar-kpi/my-records" class="btn-secondary" style="text-decoration:none;">← Back to My Records</a>
  <?php endif; ?>
</div>

<?php if ($isModalMode): ?>
<script>
(function() {
  function autoResize() {
    try { window.parent.postMessage({type:'kpi-resize', height: document.body.scrollHeight}, '*'); } catch(e) {}
  }
  window.addEventListener('load', autoResize);
  new MutationObserver(autoResize).observe(document.body, {childList:true, subtree:true});
})();
</script>
</div></main></div></body></html>
<?php else: ?>
<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
<?php endif; ?>
