<?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  = "César's Weekly KPI Entry";
$active     = 'home';
$isModalMode = !empty($_GET['modal']);

if (!$isModalMode) {
    require __DIR__ . '/../layout/workspace_header.php';
} else {
    // Minimal head for iframe — no sidebar, just styles
    ?><!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="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.css"><script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.js"></script>
<script>
// Flatpickr — MM/DD/YYYY format, blank on new forms, populated on edit
document.addEventListener('DOMContentLoaded', function() {
  function applyFP(el){
    if(el._fp) return;
    var savedVal = el.getAttribute('data-saved') || '';
    var defDate = null;
    if(savedVal){
      var parts=savedVal.split('-');
      if(parts.length===3) defDate=new Date(parseInt(parts[0]),parseInt(parts[1])-1,parseInt(parts[2]));
    }
    el._fp = flatpickr(el, {
      dateFormat: 'm/d/Y',
      allowInput: false,
      defaultDate: defDate,
      onChange: function(dates, str, inst){
        if(dates[0]){
          var d=dates[0];
          var iso=d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0');
          var h=inst.element._hi;
          if(!h){
            h=document.createElement('input');
            h.type='hidden';
            h.name=inst.element.name;
            inst.element.removeAttribute('name');
            inst.element.insertAdjacentElement('afterend',h);
            inst.element._hi=h;
          }
          h.value=iso;
        }
      },
      onReady: function(dates, str, inst){
        if(savedVal){
          var h=document.createElement('input');
          h.type='hidden';
          h.name=inst.element.name;
          inst.element.removeAttribute('name');
          inst.element.insertAdjacentElement('afterend',h);
          h.value=savedVal;
          inst.element._hi=h;
        }
      }
    });
  }
  document.querySelectorAll('input[type="date"]').forEach(applyFP);
  new MutationObserver(function(ms){
    ms.forEach(function(m){
      m.addedNodes.forEach(function(n){
        if(n.nodeType!==1)return;
        if(n.matches&&n.matches('input[type="date"]'))applyFP(n);
        n.querySelectorAll&&n.querySelectorAll('input[type="date"]').forEach(applyFP);
      });
    });
  }).observe(document.body,{childList:true,subtree:true});
});
</script><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; }
      /* Hide sidebar when in modal */
      .sidebar { display:none!important; }
      .main { margin:0!important; }
    </style>
    </head><body><div class="admin-shell"><main class="main"><div class="main-inner">
    <?php
}

$isEdit    = !empty($entry);
$entryId   = $entry['id'] ?? '';
$weekVal   = $entry['week_ending']  ?? '';

// Decode JSON arrays from saved entry
$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);

// Default at least one row for each repeatable section
if (!$contractsStarted) $contractsStarted = [[]];
if (!$contractsLost)    $contractsLost    = [[]];
if (!$postOrders)       $postOrders       = [[]];
if (!$meetings)         $meetings         = [[]];
if (!$siteScores)       $siteScores       = [[]];
if (!$reachouts)        $reachouts        = [[]];
if (!$renewals)         $renewals         = [[]];

// Scalar fields
$otBudgeted   = $entry['ot_budgeted']              ?? '0.0';
$otActual     = $entry['ot_actual']                ?? '0.0';
$scoreKaran   = $entry['score_karan']              ?? 0;
$scoreKaranN  = $entry['score_karan_notes']        ?? '';
$scoreHarry   = $entry['score_harry']              ?? 0;
$scoreHarryN  = $entry['score_harry_notes']        ?? '';
$scoreJatinder= $entry['score_jatinder']           ?? 0;
$scoreJatinderN=$entry['score_jatinder_notes']     ?? '';
$scoreMichael = $entry['score_michael']            ?? 0;
$scoreMichaelN= $entry['score_michael_notes']      ?? '';
$openInv      = $entry['open_investigations']      ?? 0;
$invDesc      = $entry['investigation_desc']       ?? '';
$escalCount   = $entry['escalations_received']     ?? 0;
$escalFrom    = $entry['escalations_from_summary'] ?? '';

// Build site options HTML helper
function siteOptions(array $sites, $selectedId): string {
    $html = '<option value="">— select site —</option>';
    foreach ($sites as $s) {
        $sel = ($s['id'] == $selectedId) ? ' selected' : '';
        $html .= '<option value="' . $s['id'] . '"' . $sel . '>' . htmlspecialchars($s['name']) . '</option>';
    }
    return $html;
}

$editable = !$isEdit || in_array($entry['status'] ?? '', ['draft', 'returned']);
?>

<style>
.cesar-section {
  background:#fff;
  border:1px solid var(--border);
  border-radius:16px;
  padding:24px 28px;
  margin-bottom:22px;
}
.cesar-section h3 {
  font-size:13px;
  font-weight:700;
  letter-spacing:.06em;
  text-transform:uppercase;
  color:var(--text-muted);
  margin:0 0 18px;
}
.cesar-row {
  border:1px solid var(--border);
  border-radius:12px;
  padding:18px 20px;
  margin-bottom:14px;
  position:relative;
  background:#fbfcfe;
}
.cesar-row .remove-row {
  position:absolute;
  top:10px; right:12px;
  background:none; border:none;
  cursor:pointer; color:var(--text-muted);
  font-size:16px; line-height:1;
}
.cesar-row .remove-row:hover { color:#dc2626; }
.cesar-grid-3 { display:grid; grid-template-columns:1fr 1fr 1fr; gap:14px; }
.cesar-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
.cesar-grid-2-1 { display:grid; grid-template-columns:2fr 1fr; gap:14px; }
.cesar-grid-site { display:grid; grid-template-columns:1.5fr 1fr 120px; gap:14px; align-items:start; }
.fld label {
  display:block;
  font-size:11.5px;
  font-weight:600;
  letter-spacing:.05em;
  text-transform:uppercase;
  color:var(--text-muted);
  margin-bottom:6px;
}
.add-row-btn {
  background:none;
  border:1px dashed var(--border);
  border-radius:10px;
  padding:8px 18px;
  font-size:13px;
  color:var(--blue-600);
  cursor:pointer;
  margin-top:4px;
  transition:background .15s;
}
.add-row-btn:hover { background:var(--bg); }
.auto-field {
  background:var(--bg);
  border:1px solid var(--border);
  border-radius:10px;
  padding:10px 14px;
  font-size:14px;
  color:var(--text-muted);
  font-variant-numeric:tabular-nums;
}
.score-table { width:100%; border-collapse:separate; border-spacing:0 12px; }
.score-table td { vertical-align:top; padding:0 8px 0 0; }
.score-table .name-col { font-weight:700; font-size:14px; width:90px; padding-top:10px; }
.score-table .score-col { width:100px; }
.score-table .notes-col { }
.cesar-subtitle {
  font-size:12.5px;
  color:var(--text-muted);
  margin:-10px 0 16px;
  padding:10px 14px;
  background:#f0f4ff;
  border-radius:10px;
  border-left:3px solid var(--blue-600);
}
</style>

<?php if (!$isModalMode): ?>
<div class="topbar">
  <div>
    <h1>César's Weekly KPI Entry</h1>
    <div class="crumbs">
      <a href="/workspace" style="color:var(--blue-600);">Workspace</a> →
      <a href="/projects/cesar-kpi/my-records" style="color:var(--blue-600);">My KPI Records</a> →
      <?= $isEdit ? 'Edit Entry' : 'New Entry' ?>
    </div>
    <div style="font-size:13px;color:var(--text-muted);margin-top:4px;">Operations Manager — strategic &amp; oversight level</div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($user['name']) ?></div>
</div>
<?php else: ?>
<div style="margin-bottom:16px;">
  <div style="font-size:12px;color:var(--text-muted);">Operations Manager — strategic &amp; oversight level</div>
</div>
<?php endif; ?>

<?php if ($isEdit && ($entry['status'] ?? '') === 'returned' && !empty($entry['review_comment'])): ?>
<div style="padding:18px 22px;background:#fef2f2;border:1.5px solid #fca5a5;border-radius:14px;margin-bottom:20px;display:flex;gap:16px;align-items:flex-start;">
  <div style="font-size:22px;line-height:1;">↩</div>
  <div>
    <div style="font-weight:800;font-size:14px;color:#991b1b;margin-bottom:4px;">Returned by <?= htmlspecialchars($entry['reviewer_name'] ?? 'Reviewer') ?></div>
    <div style="font-size:14px;color:#7f1d1d;"><?= nl2br(htmlspecialchars($entry['review_comment'])) ?></div>
    <div style="font-size:12px;color:#dc2626;margin-top:6px;"><?= fmtDate($entry['reviewed_at'] ?? '') ?> — Make the requested changes and click "Submit Weekly KPIs →" to resubmit.</div>
  </div>
</div>
<?php endif; ?>

<form method="POST" action="/projects/cesar-kpi/save-draft<?= $isModalMode ? '?modal=1' : '' ?>" id="cesar-kpi-form" style="max-width:960px;">
  <?php if ($entryId): ?><input type="hidden" name="id" value="<?= $entryId ?>">
  <?php endif; ?>

  <!-- ═══ WEEK ═════════════════════════════════════════════════════════════ -->
  <div class="cesar-section">
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;max-width:520px;">
      <div class="fld">
        <label>Week starting</label>
        <input type="date" name="week_starting" id="week_starting"
               value="" data-saved="<?= htmlspecialchars($entry['week_starting'] ?? '') ?>"
               <?= $editable ? '' : 'disabled' ?>
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
      </div>
      <div class="fld">
        <label>Week ending</label>
        <input type="date" name="week_ending" id="week_ending"
               value="" data-saved="<?= htmlspecialchars($entry['week_ending'] ?? '') ?>"
               <?= $editable ? '' : 'disabled' ?>
               onchange="syncWeekStart(this.value)"
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
      </div>
    </div>
  </div>

  <!-- ═══ HOURS PIPELINE — CONTRACTS STARTED ══════════════════════════════ -->
  <div class="cesar-section">
    <h3>Hours Pipeline — Contracts Started</h3>
    <div id="contracts-started-list">
      <?php foreach ($contractsStarted as $i => $cs): ?>
      <div class="cesar-row">
        <?php if ($editable): ?><button type="button" class="remove-row" onclick="removeRow(this)">×</button><?php endif; ?>
        <div class="cesar-grid-site">
          <div class="fld">
            <label>Site / contract name</label>
            <select name="cs_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
              <?= siteOptions($sites, $cs['site_id'] ?? '') ?>
            </select>
          </div>
          <div class="fld">
            <label>Or type name</label>
            <input type="text" name="cs_custom_name[]" value="<?= htmlspecialchars($cs['custom_name'] ?? '') ?>"
                   placeholder="Custom contract name..."
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
          <div class="fld">
            <label>Total hours</label>
            <input type="number" name="cs_hours[]" value="<?= htmlspecialchars($cs['hours'] ?? '0.0') ?>"
                   step="0.5" min="0"
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php if ($editable): ?><button type="button" class="add-row-btn" onclick="addRow('contracts-started')">+ Add contract started</button><?php endif; ?>
  </div>

  <!-- ═══ HOURS PIPELINE — CONTRACTS LOST ═════════════════════════════════ -->
  <div class="cesar-section">
    <h3>Hours Pipeline — Contracts Lost</h3>
    <div id="contracts-lost-list">
      <?php foreach ($contractsLost as $cl): ?>
      <div class="cesar-row">
        <?php if ($editable): ?><button type="button" class="remove-row" onclick="removeRow(this)">×</button><?php endif; ?>
        <div class="cesar-grid-site" style="margin-bottom:14px;">
          <div class="fld">
            <label>Site / contract name</label>
            <select name="cl_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
              <?= siteOptions($sites, $cl['site_id'] ?? '') ?>
            </select>
          </div>
          <div class="fld">
            <label>Or type name</label>
            <input type="text" name="cl_custom_name[]" value="<?= htmlspecialchars($cl['custom_name'] ?? '') ?>"
                   placeholder="Custom contract name..."
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
          <div class="fld">
            <label>Total hours</label>
            <input type="number" name="cl_hours[]" value="<?= htmlspecialchars($cl['hours'] ?? '0.0') ?>"
                   step="0.5" min="0"
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
        </div>
        <div class="fld">
          <label>Comments</label>
          <textarea name="cl_comments[]" rows="2" placeholder="Reason for loss, notes..."
                    style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;" <?= $editable ? '' : 'disabled' ?>><?= htmlspecialchars($cl['comments'] ?? '') ?></textarea>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php if ($editable): ?><button type="button" class="add-row-btn" onclick="addRow('contracts-lost')">+ Add contract lost</button><?php endif; ?>

    <div style="margin-top:20px;">
      <div class="fld" style="max-width:200px;">
        <label>Net hours change (auto)</label>
        <div class="auto-field" id="net-hours-display">—</div>
        <div style="font-size:11px;color:var(--text-muted);margin-top:4px;">Contract started minus lost</div>
      </div>
    </div>
  </div>

  <!-- ═══ POST ORDER UPDATES ═══════════════════════════════════════════════ -->
  <div class="cesar-section">
    <h3>Post Order Updates</h3>
    <p class="cesar-subtitle">Add one entry per site that had a post order update.</p>
    <div id="post-orders-list">
      <?php foreach ($postOrders as $po): ?>
      <div class="cesar-row">
        <?php if ($editable): ?><button type="button" class="remove-row" onclick="removeRow(this)">×</button><?php endif; ?>
        <div class="cesar-grid-2">
          <div class="fld">
            <label>Site</label>
            <select name="po_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
              <?= siteOptions($sites, $po['site_id'] ?? '') ?>
            </select>
          </div>
          <div class="fld">
            <label>Comments / what changed</label>
            <textarea name="po_comments[]" rows="2" placeholder="What was updated in the post order..."
                      style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;" <?= $editable ? '' : 'disabled' ?>><?= htmlspecialchars($po['comments'] ?? '') ?></textarea>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-top:4px;">
      <?php if ($editable): ?><button type="button" class="add-row-btn" onclick="addRow('post-orders')">+ Add site</button><?php else: ?><span></span><?php endif; ?>
      <span style="font-size:12.5px;color:var(--text-muted);" id="po-count">Post orders updated: 0</span>
    </div>
  </div>

  <!-- ═══ CLIENT MEETINGS ══════════════════════════════════════════════════ -->
  <div class="cesar-section">
    <h3>Client Meetings</h3>
    <div id="meetings-list">
      <?php foreach ($meetings as $m): ?>
      <div class="cesar-row">
        <?php if ($editable): ?><button type="button" class="remove-row" onclick="removeRow(this)">×</button><?php endif; ?>
        <div class="cesar-grid-2" style="margin-bottom:14px;">
          <div class="fld">
            <label>Site visited</label>
            <select name="mt_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
              <?= siteOptions($sites, $m['site_id'] ?? '') ?>
            </select>
          </div>
          <div class="fld">
            <label>Client name</label>
            <input type="text" name="mt_client_name[]" value="<?= htmlspecialchars($m['client_name'] ?? '') ?>"
                   placeholder="Client name..."
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
        </div>
        <div style="display:grid;grid-template-columns:1fr 1fr 160px;gap:14px;align-items:start;">
          <div class="fld">
            <label>Meeting notes</label>
            <textarea name="mt_notes[]" rows="3" placeholder="What was discussed..."
                      style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;" <?= $editable ? '' : 'disabled' ?>><?= htmlspecialchars($m['meeting_notes'] ?? '') ?></textarea>
          </div>
          <div class="fld">
            <label>Open notes / follow-up</label>
            <textarea name="mt_open_notes[]" rows="3" placeholder="Action items, follow-ups..."
                      style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;" <?= $editable ? '' : 'disabled' ?>><?= htmlspecialchars($m['open_notes'] ?? '') ?></textarea>
          </div>
          <div>
            <div class="fld" style="margin-bottom:12px;">
              <label>Satisfaction</label>
              <select name="mt_satisfaction[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
                <option value="">—</option>
                <?php foreach (['Very Satisfied','Satisfied','Neutral','Dissatisfied','Very Dissatisfied'] as $opt): ?>
                  <option <?= ($m['satisfaction'] ?? '') === $opt ? 'selected' : '' ?>><?= $opt ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="fld">
              <label>Risk level</label>
              <select name="mt_risk_level[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
                <option value="">—</option>
                <?php foreach (['Low','Medium','High','Critical'] as $opt): ?>
                  <option <?= ($m['risk_level'] ?? '') === $opt ? 'selected' : '' ?>><?= $opt ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php if ($editable): ?><button type="button" class="add-row-btn" onclick="addRow('meetings')">+ Add meeting</button><?php endif; ?>
  </div>

  <!-- ═══ SITE VISIT SCORES ════════════════════════════════════════════════ -->
  <div class="cesar-section">
    <h3>Site Visit Scores</h3>
    <p class="cesar-subtitle">Select each site visited and enter a score (1–5) with reason.</p>
    <div id="site-scores-list">
      <?php foreach ($siteScores as $ss): ?>
      <div class="cesar-row">
        <?php if ($editable): ?><button type="button" class="remove-row" onclick="removeRow(this)">×</button><?php endif; ?>
        <div style="display:grid;grid-template-columns:1.6fr 100px 1fr;gap:14px;align-items:start;">
          <div class="fld">
            <label>Site</label>
            <select name="ss_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
              <?= siteOptions($sites, $ss['site_id'] ?? '') ?>
            </select>
          </div>
          <div class="fld">
            <label>Score (1–5)</label>
            <input type="number" name="ss_score[]" value="<?= htmlspecialchars($ss['score'] ?? '0.0') ?>"
                   step="0.5" min="1" max="5"
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
          <div class="fld">
            <label>Reason / comments</label>
            <textarea name="ss_reason[]" rows="2" placeholder="Why this score..."
                      style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;" <?= $editable ? '' : 'disabled' ?>><?= htmlspecialchars($ss['reason'] ?? '') ?></textarea>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php if ($editable): ?><button type="button" class="add-row-btn" onclick="addRow('site-scores')">+ Add site score</button><?php endif; ?>
  </div>

  <!-- ═══ NEW CLIENT REACH OUT ═════════════════════════════════════════════ -->
  <div class="cesar-section">
    <h3>New Client Reach Out</h3>
    <div id="reachouts-list">
      <?php foreach ($reachouts as $ro): ?>
      <div class="cesar-row">
        <?php if ($editable): ?><button type="button" class="remove-row" onclick="removeRow(this)">×</button><?php endif; ?>
        <div class="cesar-grid-3" style="margin-bottom:14px;">
          <div class="fld">
            <label>Client / company name</label>
            <input type="text" name="ro_company[]" value="<?= htmlspecialchars($ro['company_name'] ?? '') ?>"
                   placeholder="Company name..."
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
          <div class="fld">
            <label>Contact name</label>
            <input type="text" name="ro_contact[]" value="<?= htmlspecialchars($ro['contact_name'] ?? '') ?>"
                   placeholder="Contact person..."
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
          <div class="fld">
            <label>Phone number</label>
            <input type="text" name="ro_phone[]" value="<?= htmlspecialchars($ro['phone'] ?? '') ?>"
                   placeholder="(XXX) XXX-XXXX"
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
        </div>
        <div class="fld">
          <label>What happened / next steps</label>
          <textarea name="ro_notes[]" rows="3" placeholder="How the conversation went, what was discussed, follow-up actions..."
                    style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;" <?= $editable ? '' : 'disabled' ?>><?= htmlspecialchars($ro['notes'] ?? '') ?></textarea>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php if ($editable): ?><button type="button" class="add-row-btn" onclick="addRow('reachouts')">+ Add client</button><?php endif; ?>
  </div>

  <!-- ═══ CONTRACT RENEWALS ════════════════════════════════════════════════ -->
  <div class="cesar-section">
    <h3>Contract Renewals</h3>
    <div id="renewals-list">
      <?php foreach ($renewals as $rn): ?>
      <div class="cesar-row">
        <?php if ($editable): ?><button type="button" class="remove-row" onclick="removeRow(this)">×</button><?php endif; ?>
        <div class="cesar-grid-2" style="margin-bottom:14px;">
          <div class="fld">
            <label>Site</label>
            <select name="rn_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
              <?= siteOptions($sites, $rn['site_id'] ?? '') ?>
            </select>
          </div>
          <div class="fld">
            <label>Client name</label>
            <input type="text" name="rn_client_name[]" value="<?= htmlspecialchars($rn['client_name'] ?? '') ?>"
                   placeholder="Client / company name..."
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
        </div>
        <div style="display:flex;gap:14px;align-items:center;">
          <div class="fld">
            <label>Rate increase?</label>
            <select name="rn_rate_increase[]" style="width:120px;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
              <option value="">—</option>
              <option <?= ($rn['rate_increase'] ?? '') === 'Yes' ? 'selected' : '' ?>>Yes</option>
              <option <?= ($rn['rate_increase'] ?? '') === 'No'  ? 'selected' : '' ?>>No</option>
            </select>
          </div>
          <div class="fld" style="flex:1;">
            <label>Notes</label>
            <input type="text" name="rn_notes[]" value="<?= htmlspecialchars($rn['notes'] ?? '') ?>"
                   placeholder="Renewal details..."
                   style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php if ($editable): ?><button type="button" class="add-row-btn" onclick="addRow('renewals')">+ Add renewal</button><?php endif; ?>
  </div>

  <!-- ═══ OT VS BUDGET ═════════════════════════════════════════════════════ -->
  <div class="cesar-section">
    <h3>OT vs Budget</h3>
    <div style="display:grid;grid-template-columns:180px 180px 180px;gap:20px;align-items:end;">
      <div class="fld">
        <label>Budgeted OT hours</label>
        <input type="number" name="ot_budgeted" id="ot_budgeted" value="<?= htmlspecialchars($otBudgeted) ?>"
               step="0.5" min="0" onchange="calcOtVariance()" oninput="calcOtVariance()"
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
      </div>
      <div class="fld">
        <label>Actual OT hours</label>
        <input type="number" name="ot_actual" id="ot_actual" value="<?= htmlspecialchars($otActual) ?>"
               step="0.5" min="0" onchange="calcOtVariance()" oninput="calcOtVariance()"
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
      </div>
      <div class="fld">
        <label>Variance (auto)</label>
        <div class="auto-field" id="ot-variance-display">—</div>
        <div style="font-size:11px;color:var(--text-muted);margin-top:4px;">Negative = over budget</div>
      </div>
    </div>
  </div>

  <!-- ═══ ESCALATIONS & OPEN INVESTIGATIONS ════════════════════════════════ -->
  <div class="cesar-section">
    <h3>Escalations &amp; Open Investigations</h3>
    <div style="display:grid;grid-template-columns:160px 1fr 160px 1fr;gap:14px;align-items:start;">
      <div class="fld">
        <label>Open investigations (count)</label>
        <input type="number" name="open_investigations" value="<?= (int)$openInv ?>"
               min="0" step="1"
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
      </div>
      <div class="fld">
        <label>Investigation description</label>
        <input type="text" name="investigation_desc" value="<?= htmlspecialchars($invDesc) ?>"
               placeholder="Brief description..."
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
      </div>
      <div class="fld">
        <label>Escalations received (count)</label>
        <input type="number" name="escalations_received" value="<?= (int)$escalCount ?>"
               min="0" step="1"
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
      </div>
      <div class="fld">
        <label>From who + summary</label>
        <input type="text" name="escalations_from_summary" value="<?= htmlspecialchars($escalFrom) ?>"
               placeholder="From who — what happened..."
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;" <?= $editable ? '' : 'disabled' ?>>
      </div>
    </div>
  </div>

  <!-- ═══ Hidden JSON fields (built before submit) ═════════════════════════ -->
  <input type="hidden" name="contracts_started"    id="f_contracts_started">
  <input type="hidden" name="contracts_lost"        id="f_contracts_lost">
  <input type="hidden" name="post_order_updates"    id="f_post_orders">
  <input type="hidden" name="client_meetings"       id="f_meetings">
  <input type="hidden" name="site_visit_scores"     id="f_site_scores">
  <input type="hidden" name="new_client_reachouts"  id="f_reachouts">
  <input type="hidden" name="contract_renewals"     id="f_renewals">

  <!-- ═══ ACTION BUTTONS ══════════════════════════════════════════════════ -->
  <?php if ($editable): ?>
  <div style="display:flex;justify-content:flex-end;gap:14px;padding:8px 0 32px;max-width:960px;">
    <?php if ($isModalMode): ?>
      <button type="button" class="btn-secondary" style="padding:12px 24px;"
              onclick="window.parent.postMessage({type:'kpi-cancel'},'>*')">Cancel</button>
    <?php else: ?>
      <a href="/projects/cesar-kpi/my-records" class="btn-secondary" style="text-decoration:none;padding:12px 24px;">Cancel</a>
    <?php endif; ?>
    <button type="submit" class="btn-secondary" onclick="buildJson()">💾 Save Draft</button>
    <button type="submit" name="then_submit" value="1" class="btn-primary"
            onclick="buildJson();return confirm('Submit this week\'s KPI for review? You will not be able to edit it after submitting.');">
      Submit Weekly KPIs →
    </button>
  </div>
  <?php endif; ?>
</form>

<script>
// ─── Row templates ────────────────────────────────────────────────────────────

const SITE_OPTIONS = `<?php
$opts = '<option value="">— select site —</option>';
foreach ($sites as $s) $opts .= '<option value="' . $s['id'] . '">' . htmlspecialchars($s['name']) . '</option>';
echo addslashes($opts);
?>`;

const TEMPLATES = {
  'contracts-started': () => `
    <div class="cesar-row">
      <button type="button" class="remove-row" onclick="removeRow(this)">×</button>
      <div class="cesar-grid-site">
        <div class="fld"><label>Site / contract name</label>
          <select name="cs_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">${SITE_OPTIONS}</select>
        </div>
        <div class="fld"><label>Or type name</label>
          <input type="text" name="cs_custom_name[]" placeholder="Custom contract name..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
        <div class="fld"><label>Total hours</label>
          <input type="number" name="cs_hours[]" value="0.0" step="0.5" min="0" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
      </div>
    </div>`,
  'contracts-lost': () => `
    <div class="cesar-row">
      <button type="button" class="remove-row" onclick="removeRow(this)">×</button>
      <div class="cesar-grid-site" style="margin-bottom:14px;">
        <div class="fld"><label>Site / contract name</label>
          <select name="cl_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">${SITE_OPTIONS}</select>
        </div>
        <div class="fld"><label>Or type name</label>
          <input type="text" name="cl_custom_name[]" placeholder="Custom contract name..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
        <div class="fld"><label>Total hours</label>
          <input type="number" name="cl_hours[]" value="0.0" step="0.5" min="0" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
      </div>
      <div class="fld"><label>Comments</label>
        <textarea name="cl_comments[]" rows="2" placeholder="Reason for loss, notes..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;"></textarea>
      </div>
    </div>`,
  'post-orders': () => `
    <div class="cesar-row">
      <button type="button" class="remove-row" onclick="removeRow(this)">×</button>
      <div class="cesar-grid-2">
        <div class="fld"><label>Site</label>
          <select name="po_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">${SITE_OPTIONS}</select>
        </div>
        <div class="fld"><label>Comments / what changed</label>
          <textarea name="po_comments[]" rows="2" placeholder="What was updated in the post order..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;"></textarea>
        </div>
      </div>
    </div>`,
  'meetings': () => `
    <div class="cesar-row">
      <button type="button" class="remove-row" onclick="removeRow(this)">×</button>
      <div class="cesar-grid-2" style="margin-bottom:14px;">
        <div class="fld"><label>Site visited</label>
          <select name="mt_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">${SITE_OPTIONS}</select>
        </div>
        <div class="fld"><label>Client name</label>
          <input type="text" name="mt_client_name[]" placeholder="Client name..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr 160px;gap:14px;">
        <div class="fld"><label>Meeting notes</label>
          <textarea name="mt_notes[]" rows="3" placeholder="What was discussed..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;"></textarea>
        </div>
        <div class="fld"><label>Open notes / follow-up</label>
          <textarea name="mt_open_notes[]" rows="3" placeholder="Action items, follow-ups..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;"></textarea>
        </div>
        <div>
          <div class="fld" style="margin-bottom:12px;"><label>Satisfaction</label>
            <select name="mt_satisfaction[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
              <option value="">—</option><option>Very Satisfied</option><option>Satisfied</option><option>Neutral</option><option>Dissatisfied</option><option>Very Dissatisfied</option>
            </select>
          </div>
          <div class="fld"><label>Risk level</label>
            <select name="mt_risk_level[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
              <option value="">—</option><option>Low</option><option>Medium</option><option>High</option><option>Critical</option>
            </select>
          </div>
        </div>
      </div>
    </div>`,
  'site-scores': () => `
    <div class="cesar-row">
      <button type="button" class="remove-row" onclick="removeRow(this)">×</button>
      <div style="display:grid;grid-template-columns:1.6fr 100px 1fr;gap:14px;">
        <div class="fld"><label>Site</label>
          <select name="ss_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">${SITE_OPTIONS}</select>
        </div>
        <div class="fld"><label>Score (1–5)</label>
          <input type="number" name="ss_score[]" value="0.0" step="0.5" min="1" max="5" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
        <div class="fld"><label>Reason / comments</label>
          <textarea name="ss_reason[]" rows="2" placeholder="Why this score..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;"></textarea>
        </div>
      </div>
    </div>`,
  'reachouts': () => `
    <div class="cesar-row">
      <button type="button" class="remove-row" onclick="removeRow(this)">×</button>
      <div class="cesar-grid-3" style="margin-bottom:14px;">
        <div class="fld"><label>Client / company name</label>
          <input type="text" name="ro_company[]" placeholder="Company name..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
        <div class="fld"><label>Contact name</label>
          <input type="text" name="ro_contact[]" placeholder="Contact person..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
        <div class="fld"><label>Phone number</label>
          <input type="text" name="ro_phone[]" placeholder="(XXX) XXX-XXXX" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
      </div>
      <div class="fld"><label>What happened / next steps</label>
        <textarea name="ro_notes[]" rows="3" placeholder="How the conversation went, what was discussed, follow-up actions..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;resize:vertical;"></textarea>
      </div>
    </div>`,
  'renewals': () => `
    <div class="cesar-row">
      <button type="button" class="remove-row" onclick="removeRow(this)">×</button>
      <div class="cesar-grid-2" style="margin-bottom:14px;">
        <div class="fld"><label>Site</label>
          <select name="rn_site_id[]" style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">${SITE_OPTIONS}</select>
        </div>
        <div class="fld"><label>Client name</label>
          <input type="text" name="rn_client_name[]" placeholder="Client / company name..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
      </div>
      <div style="display:flex;gap:14px;align-items:center;">
        <div class="fld"><label>Rate increase?</label>
          <select name="rn_rate_increase[]" style="width:120px;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
            <option value="">—</option><option>Yes</option><option>No</option>
          </select>
        </div>
        <div class="fld" style="flex:1;"><label>Notes</label>
          <input type="text" name="rn_notes[]" placeholder="Renewal details..." style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
        </div>
      </div>
    </div>`,
};

function addRow(type) {
  const list = document.getElementById(type + '-list');
  const tmp  = document.createElement('div');
  tmp.innerHTML = TEMPLATES[type]();
  list.appendChild(tmp.firstElementChild);
  updatePoCount();
  calcNetHours();
}

function removeRow(btn) {
  btn.closest('.cesar-row').remove();
  updatePoCount();
  calcNetHours();
}

// ─── Auto-calculations ────────────────────────────────────────────────────────

function calcNetHours() {
  const startedHours = [...document.querySelectorAll('[name="cs_hours[]"]')]
    .reduce((s, el) => s + (parseFloat(el.value) || 0), 0);
  const lostHours = [...document.querySelectorAll('[name="cl_hours[]"]')]
    .reduce((s, el) => s + (parseFloat(el.value) || 0), 0);
  const net = startedHours - lostHours;
  document.getElementById('net-hours-display').textContent = net.toFixed(1);
}

function calcOtVariance() {
  const budgeted = parseFloat(document.getElementById('ot_budgeted').value) || 0;
  const actual   = parseFloat(document.getElementById('ot_actual').value)   || 0;
  document.getElementById('ot-variance-display').textContent = (actual - budgeted).toFixed(1);
}

function updatePoCount() {
  const n = document.querySelectorAll('#post-orders-list .cesar-row').length;
  document.getElementById('po-count').textContent = 'Post orders updated: ' + n;
}

// ─── Build JSON before form submit ────────────────────────────────────────────

function buildJson() {
  // Contracts started
  const cs = [], csSites = [...document.querySelectorAll('[name="cs_site_id[]"]')],
    csNames = [...document.querySelectorAll('[name="cs_custom_name[]"]')],
    csHours = [...document.querySelectorAll('[name="cs_hours[]"]')];
  csSites.forEach((el,i) => cs.push({site_id:el.value, site_name:el.options[el.selectedIndex]?.text||'', custom_name:csNames[i]?.value||'', hours:parseFloat(csHours[i]?.value)||0}));
  document.getElementById('f_contracts_started').value = JSON.stringify(cs);

  // Contracts lost
  const cl = [], clSites = [...document.querySelectorAll('[name="cl_site_id[]"]')],
    clNames = [...document.querySelectorAll('[name="cl_custom_name[]"]')],
    clHours = [...document.querySelectorAll('[name="cl_hours[]"]')],
    clComments = [...document.querySelectorAll('[name="cl_comments[]"]')];
  clSites.forEach((el,i) => cl.push({site_id:el.value, site_name:el.options[el.selectedIndex]?.text||'', custom_name:clNames[i]?.value||'', hours:parseFloat(clHours[i]?.value)||0, comments:clComments[i]?.value||''}));
  document.getElementById('f_contracts_lost').value = JSON.stringify(cl);

  // Post orders
  const po = [], poSites = [...document.querySelectorAll('[name="po_site_id[]"]')],
    poComments = [...document.querySelectorAll('[name="po_comments[]"]')];
  poSites.forEach((el,i) => po.push({site_id:el.value, site_name:el.options[el.selectedIndex]?.text||'', comments:poComments[i]?.value||''}));
  document.getElementById('f_post_orders').value = JSON.stringify(po);

  // Meetings
  const mt = [], mtSites = [...document.querySelectorAll('[name="mt_site_id[]"]')],
    mtClients = [...document.querySelectorAll('[name="mt_client_name[]"]')],
    mtNotes = [...document.querySelectorAll('[name="mt_notes[]"]')],
    mtOpen = [...document.querySelectorAll('[name="mt_open_notes[]"]')],
    mtSat = [...document.querySelectorAll('[name="mt_satisfaction[]"]')],
    mtRisk = [...document.querySelectorAll('[name="mt_risk_level[]"]')];
  mtSites.forEach((el,i) => mt.push({site_id:el.value, site_name:el.options[el.selectedIndex]?.text||'', client_name:mtClients[i]?.value||'', meeting_notes:mtNotes[i]?.value||'', open_notes:mtOpen[i]?.value||'', satisfaction:mtSat[i]?.value||'', risk_level:mtRisk[i]?.value||''}));
  document.getElementById('f_meetings').value = JSON.stringify(mt);

  // Site scores
  const ss = [], ssSites = [...document.querySelectorAll('[name="ss_site_id[]"]')],
    ssScores = [...document.querySelectorAll('[name="ss_score[]"]')],
    ssReasons = [...document.querySelectorAll('[name="ss_reason[]"]')];
  ssSites.forEach((el,i) => ss.push({site_id:el.value, site_name:el.options[el.selectedIndex]?.text||'', score:parseFloat(ssScores[i]?.value)||0, reason:ssReasons[i]?.value||''}));
  document.getElementById('f_site_scores').value = JSON.stringify(ss);

  // Reachouts
  const ro = [], roCompany = [...document.querySelectorAll('[name="ro_company[]"]')],
    roContact = [...document.querySelectorAll('[name="ro_contact[]"]')],
    roPhone = [...document.querySelectorAll('[name="ro_phone[]"]')],
    roNotes = [...document.querySelectorAll('[name="ro_notes[]"]')];
  roCompany.forEach((el,i) => ro.push({company_name:el.value, contact_name:roContact[i]?.value||'', phone:roPhone[i]?.value||'', notes:roNotes[i]?.value||''}));
  document.getElementById('f_reachouts').value = JSON.stringify(ro);

  // Renewals
  const rn = [], rnSites = [...document.querySelectorAll('[name="rn_site_id[]"]')],
    rnClients = [...document.querySelectorAll('[name="rn_client_name[]"]')],
    rnRate = [...document.querySelectorAll('[name="rn_rate_increase[]"]')],
    rnNotes = [...document.querySelectorAll('[name="rn_notes[]"]')];
  rnSites.forEach((el,i) => rn.push({site_id:el.value, site_name:el.options[el.selectedIndex]?.text||'', client_name:rnClients[i]?.value||'', rate_increase:rnRate[i]?.value||'', notes:rnNotes[i]?.value||''}));
  document.getElementById('f_renewals').value = JSON.stringify(rn);
}

// Sync week_starting when week_ending changes (auto = ending minus 6 days)
function syncWeekStart(endVal) {
  if (!endVal) return;
  const end = new Date(endVal);
  const start = new Date(end);
  start.setDate(start.getDate() - 6);
  const iso = start.toISOString().slice(0, 10);
  const ws = document.getElementById('week_starting');
  if (ws && !ws._manuallySet) ws.value = iso;
}
document.getElementById('week_starting')?.addEventListener('change', function() {
  this._manuallySet = true;
});

// Listen for changes on repeatable hour inputs
document.addEventListener('input', e => {
  if (e.target.matches('[name="cs_hours[]"],[name="cl_hours[]"]')) calcNetHours();
});

// Init on load
calcNetHours();
calcOtVariance();
updatePoCount();

<?php if ($isModalMode): ?>
// In modal mode: intercept form submit to notify parent after POST redirect
// The controller redirects to entry?id=X&modal=1&saved=1 on draft save,
// or to my-records on submit. Either way parent reloads.
(function() {
  const f = document.getElementById('cesar-kpi-form');
  if (!f) return;
  // After any submit, the iframe navigates. The parent watches for message.
  // We also auto-resize on any content change.
  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});
})();
<?php endif; ?>

// ── Auto-select on focus for all number inputs ──────────────────────────────
// This mirrors the scheduling form's UX: clicking/tabbing into a number field
// immediately selects the default "0" / "0.0" so the user can type straight
// away without having to manually clear the placeholder value first.
(function() {
  function attachSelectOnFocus(el) {
    if (el.type !== 'number') return;
    el.addEventListener('focus', function() { this.select(); });
  }
  // Attach to all number inputs already in the DOM
  document.querySelectorAll('input[type="number"]').forEach(attachSelectOnFocus);
  // Attach to dynamically added rows (add contract, add meeting, etc.)
  new MutationObserver(function(mutations) {
    mutations.forEach(function(m) {
      m.addedNodes.forEach(function(node) {
        if (node.nodeType !== 1) return;
        if (node.matches('input[type="number"]')) attachSelectOnFocus(node);
        node.querySelectorAll && node.querySelectorAll('input[type="number"]').forEach(attachSelectOnFocus);
      });
    });
  }).observe(document.body, {childList: true, subtree: true});
})();
</script>

<?php if (!$isModalMode): ?>
<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
<?php else: ?>
</div></main></div></body></html>
<?php endif; ?>
