<?php
$pageTitle   = 'Weekly KPI Entry — Accounts';
$isModalMode = !empty($_GET['modal']);
if (!$isModalMode) {
    $active = 'home';
    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="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;}.sidebar{display:none!important;}.main{margin:0!important;}</style>
</head><body><div class="admin-shell"><main class="main"><div class="main-inner">
<?php } ?>

<?php
$v       = fn($k) => htmlspecialchars((string)($entry[$k] ?? ''));
$editable = !$entry || in_array($entry['status'] ?? '', ['draft','returned']);

$sites = ["AG Spanos - Residence","Allen Distribution - Stockton","Arch Airport Business Park","ASM - Marina Multiplex","Blossom Hill Estates","Blue Oaks Town Center","BMW of San Francisco","Brimstone Energy Inc","Brookside - Lake Communities","Brookside Reclamation District","Camera Aivres - Milpitas","CBRE - 400 E. Main","CBRE - French Camp","CBRE ARCO","Crestwood Behavioral Center","East Ghilloti Construction","El Rancho Mobile Park","Enviroplex INC","F4L - Hammer Lane","F4L - March Lane","F4L - RSM Lodi","F4L - RSM Stockton","F4L - Weston Ranch","F4L - Wilson Way","FAA-Static","Fremont Aivres - Camera","Fremont Aivres - Gate","Fremont Aivres - Warehouse 2","Fresh Innovations","Front Office - Aivres Milpitas","George Weaver","Ghilloti Construction Company","Gill Medical","Goodlife Building - RCM","Goodwill Alitalia Way","Greene Property - RCM","Gross Holmes Building - RCM","Hillcrest Professional Center","In-Shape - Bianchi","India Office","InShape - Vallejo","KSTJV - 28th Street","KSTJV - 30th Street","KSTJV - Chase Building","KSTJV - Goldrock Building","KSTJV - Orientation Office","Michels - Crocker Spcl Project","Monte Vista Crossings","Office Hours","Omni Medical Plaza","Pardee Drive Property","PCC - DIV 1","PCC - DIV 1 - Rover","PCC - DIV 30 - Shipping Hours","PCC - DIV 30 -Non Shipping Hrs","PCC - DIV 5/9","PCC - DIV 5/9 - Rover","Power Ridge Rd - Sacramento","Quail Lakes Business Park","Quail Lakes Homeowners Associa","Ripon Community Center","Rosemarie Pet Hospital","Rover - Taylor Farms","Rover Position","Satallite-Stockton","Spanos Park East","Stockton Airport - RCM","Stockton Emergency Food Bank","Suite #500 - Taylor Farms","Suite #500 - TF - Night","Suite #700 - Taylor Farms","Suite #700 - TF - Night","Sunpointe Condominium HOA","The Bridge at Emeryville","United Site - RCM","Vehicle Patrol Aivres - SJ","Vehicle Patrol Aivres-Milpitas","Vulcan Construction - Stockton","Warehouse Aivres - Milpitas","Warehouse Aivres - San Jose","Westcore Woodland"];

$savedSites = json_decode($entry['sites_visited'] ?? '[]', true) ?: [];
?>
<style>
.jat-section{background:#fff;border:1px solid var(--border);border-radius:16px;padding:24px 28px;margin-bottom:18px;}
.jat-section h3{font-size:11px;font-weight:700;letter-spacing:.07em;text-transform:uppercase;color:var(--text-muted);margin:0 0 16px;}
.jat-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:14px;}
.jat-grid-wide{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;margin-top:10px;}
.fld label{font-size:12px;font-weight:600;color:var(--text-muted);display:block;margin-bottom:5px;}
.fld input,.fld select,.fld textarea{width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:10px;font-size:13px;font-family:inherit;}
.fld textarea{resize:vertical;min-height:72px;}
.shift-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-bottom:12px;}
.shift-box{background:var(--bg);border:1px solid var(--border);border-radius:10px;padding:14px;}
.shift-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted);margin-bottom:10px;}
.totals-row{display:flex;gap:20px;background:#f0f9ff;border-radius:10px;padding:12px 16px;margin-bottom:10px;}
.totals-row strong{font-size:18px;font-weight:800;}
.totals-row span{font-size:12px;color:var(--text-muted);}
.dyn-entry{background:var(--bg);border:1px solid var(--border);border-radius:10px;padding:14px;margin-bottom:10px;position:relative;}
.dyn-entry .remove-btn{position:absolute;top:8px;right:10px;background:none;border:none;cursor:pointer;color:var(--text-muted);font-size:16px;}
.dyn-entry .remove-btn:hover{color:#dc2626;}
.add-btn{background:none;border:1.5px dashed var(--border);color:var(--blue-600);border-radius:10px;padding:8px 18px;cursor:pointer;font-size:13px;font-weight:600;width:100%;margin-top:6px;}
.add-btn:hover{background:#eff6ff;}
</style>

<?php if (!$isModalMode): ?>
<div class="topbar">
  <div>
    <h1>Weekly KPI Entry — Accounts</h1>
    <div class="crumbs"><a href="/workspace" style="color:var(--blue-600);">Workspace</a> → <a href="/projects/jatinder-kpi/my-records" style="color:var(--blue-600);">My KPI Records</a> → <?= $entry?'Edit':'New Entry' ?></div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($user['name']) ?></div>
</div>
<?php endif; ?>

<?php if ($entry && $entry['status']==='returned'): ?>
<div class="alert alert-error" style="margin-bottom:16px;"><strong>Returned for edits:</strong> <?= htmlspecialchars($entry['return_reason'] ?? '') ?></div>
<?php endif; ?>

<form method="POST" action="/projects/jatinder-kpi/save-draft<?= $isModalMode?'?modal=1':'' ?>" style="max-width:960px;">
  <input type="hidden" name="entry_id" value="<?= $entry['id'] ?? '' ?>">
  <input type="hidden" name="modal"    value="<?= $isModalMode?'1':'' ?>">

  <!-- Week -->
  <div class="jat-section">
    <h3>Week</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
      <div class="fld"><label>Week Starting</label>
        <input type="date" name="week_starting"
               value="" data-saved="<?= htmlspecialchars($entry['week_starting'] ?? '') ?>"
               <?= $editable?'':'disabled' ?>>
      </div>
      <div class="fld"><label>Week Ending</label>
        <input type="date" name="week_ending"
               value="" data-saved="<?= htmlspecialchars($entry['week_ending'] ?? '') ?>" required
               <?= $editable?'':'disabled' ?>>
      </div>
    </div>
  </div>

  <!-- Staffing & Training -->
  <div class="jat-section">
    <h3>Staffing &amp; Training</h3>
    <div class="jat-grid">
      <div class="fld"><label>New hires this week</label><input type="number" name="new_hires" value="<?= $v('new_hires') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>New hire name(s)</label><input type="text" name="new_hire_names" value="<?= $v('new_hire_names') ?>" placeholder="Names" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>New hire training hours</label><input type="number" name="new_hire_training_hrs" value="<?= $v('new_hire_training_hrs') ?>" step="0.1" placeholder="0.0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>New contract total hours</label><input type="number" name="new_contract_hrs" value="<?= $v('new_contract_hrs') ?>" step="0.1" placeholder="0.0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Site name (new contract)</label><input type="text" name="new_contract_site" value="<?= $v('new_contract_site') ?>" placeholder="Site name..." <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Lost contract total hours</label><input type="number" name="lost_contract_hrs" value="<?= $v('lost_contract_hrs') ?>" step="0.1" placeholder="0.0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Site name (lost contract)</label><input type="text" name="lost_contract_site" value="<?= $v('lost_contract_site') ?>" placeholder="Site name..." <?= $editable?'':'disabled' ?>></div>
    </div>
  </div>

  <!-- Violations -->
  <div class="jat-section">
    <h3>Violations</h3>
    <div class="jat-grid">
      <div class="fld"><label>Guards found sleeping</label><input type="number" name="guards_sleeping" value="<?= $v('guards_sleeping') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Serious violations found</label><input type="number" name="serious_violations" value="<?= $v('serious_violations') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Failed re-inspections</label><input type="number" name="failed_reinspections" value="<?= $v('failed_reinspections') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Avg score per site (1–5)</label><input type="number" name="avg_score_per_site" value="<?= $v('avg_score_per_site') ?>" step="0.1" min="0" max="5" placeholder="0.0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Uniform compliance %</label><input type="number" name="uniform_compliance_pct" value="<?= $v('uniform_compliance_pct') ?>" placeholder="0" min="0" max="100" <?= $editable?'':'disabled' ?>></div>
    </div>
    <div class="jat-grid-wide">
      <div class="fld"><label>Violation description</label><textarea name="violation_desc" placeholder="Describe each violation..." <?= $editable?'':'disabled' ?>><?= $v('violation_desc') ?></textarea></div>
      <div class="fld"><label>How violations were handled</label><textarea name="violation_handled" placeholder="Actions taken..." <?= $editable?'':'disabled' ?>><?= $v('violation_handled') ?></textarea></div>
      <div class="fld"><label>Improvements from last inspection</label><textarea name="improvements" placeholder="What was fixed since last week..." <?= $editable?'':'disabled' ?>><?= $v('improvements') ?></textarea></div>
    </div>
  </div>

  <!-- Client Activity -->
  <div class="jat-section">
    <h3>Client Activity</h3>
    <div class="jat-grid">
      <div class="fld"><label>Client meetings held</label><input type="number" name="client_meetings" value="<?= $v('client_meetings') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Client names met</label><input type="text" name="client_names_met" value="<?= $v('client_names_met') ?>" placeholder="Client names..." <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Client complaints received</label><input type="number" name="client_complaints" value="<?= $v('client_complaints') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Client compliments received</label><input type="number" name="client_compliments" value="<?= $v('client_compliments') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Avg response time to client calls (hrs)</label><input type="number" name="avg_response_time_hrs" value="<?= $v('avg_response_time_hrs') ?>" step="0.1" placeholder="0.0" <?= $editable?'':'disabled' ?>></div>
    </div>
  </div>

  <!-- Sites Visited -->
  <div class="jat-section">
    <h3>Sites Visited This Week</h3>
    <div class="fld">
      <select name="sites_visited[]" multiple style="height:120px;width:100%;padding:6px;border:1px solid var(--border);border-radius:10px;font-size:13px;" <?= $editable?'':'disabled' ?>>
        <?php foreach ($sites as $s): ?>
          <option value="<?= htmlspecialchars($s) ?>" <?= in_array($s,$savedSites)?'selected':'' ?>><?= htmlspecialchars($s) ?></option>
        <?php endforeach; ?>
      </select>
      <small style="color:var(--text-muted);font-size:12px;margin-top:4px;display:block;">Hold Ctrl/Cmd to select multiple</small>
    </div>
  </div>

  <!-- Guard Recognition -->
  <div class="jat-section">
    <h3>Guard Recognition</h3>
    <div class="jat-grid">
      <div class="fld"><label>Guards recommended for recognition</label><input type="number" name="recognition_count" value="<?= $v('recognition_count') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Name(s) and reason</label><input type="text" name="recognition_names" value="<?= $v('recognition_names') ?>" placeholder="Name — reason..." <?= $editable?'':'disabled' ?>></div>
    </div>
  </div>

  <!-- Site Inspections -->
  <div class="jat-section">
    <h3>📋 Site Inspections — Failed Inspection Details</h3>
    <div class="shift-grid">
      <div class="shift-box">
        <div class="shift-label">🌤 Day Shift</div>
        <div class="fld"><label>Total inspections</label><input type="number" name="insp_day_total" id="insp_day_total" value="<?= $v('insp_day_total') ?>" min="0" placeholder="0" oninput="updateInspTotals()" <?= $editable?'':'disabled' ?>></div>
        <div class="fld"><label>Failed inspections</label><input type="number" name="insp_day_failed" id="insp_day_failed" value="<?= $v('insp_day_failed') ?>" min="0" placeholder="0" oninput="updateInspTotals()" <?= $editable?'':'disabled' ?>></div>
      </div>
      <div class="shift-box">
        <div class="shift-label">🌆 Swing Shift</div>
        <div class="fld"><label>Total inspections</label><input type="number" name="insp_swing_total" id="insp_swing_total" value="<?= $v('insp_swing_total') ?>" min="0" placeholder="0" oninput="updateInspTotals()" <?= $editable?'':'disabled' ?>></div>
        <div class="fld"><label>Failed inspections</label><input type="number" name="insp_swing_failed" id="insp_swing_failed" value="<?= $v('insp_swing_failed') ?>" min="0" placeholder="0" oninput="updateInspTotals()" <?= $editable?'':'disabled' ?>></div>
      </div>
      <div class="shift-box">
        <div class="shift-label">🌙 Grave Shift</div>
        <div class="fld"><label>Total inspections</label><input type="number" name="insp_grave_total" id="insp_grave_total" value="<?= $v('insp_grave_total') ?>" min="0" placeholder="0" oninput="updateInspTotals()" <?= $editable?'':'disabled' ?>></div>
        <div class="fld"><label>Failed inspections</label><input type="number" name="insp_grave_failed" id="insp_grave_failed" value="<?= $v('insp_grave_failed') ?>" min="0" placeholder="0" oninput="updateInspTotals()" <?= $editable?'':'disabled' ?>></div>
      </div>
    </div>
    <input type="hidden" name="insp_total"        id="insp_total_val"  value="<?= $v('insp_total') ?>">
    <input type="hidden" name="insp_failed_total"  id="insp_failed_val" value="<?= $v('insp_failed_total') ?>">
    <div class="totals-row">
      <div><strong id="tot_total">0</strong><br><span>Total Inspections</span></div>
      <div><strong id="tot_failed" style="color:#dc2626;">0</strong><br><span>Failed</span></div>
      <div><strong id="tot_pass" style="color:#059669;">—</strong><br><span>Pass Rate</span></div>
    </div>
    <input type="hidden" name="failed_inspections_detail" id="failed_inspections_detail" value="<?= $v('failed_inspections_detail') ?>">
  </div>

  <!-- Refresher Training -->
  <div class="jat-section">
    <h3>🎓 Refresher Training</h3>
    <div style="display:grid;grid-template-columns:200px 1fr;gap:14px;align-items:start;">
      <div class="fld">
        <label>Refresher training done this week?</label>
        <select name="refresher_done" id="refresher_done_sel" onchange="toggleJatSection('refresher_detail_box',this.value==='Yes')" <?= $editable?'':'disabled' ?>>
          <option value="">— select —</option>
          <option value="Yes" <?= ($entry['refresher_done']??'')==='Yes'?'selected':'' ?>>Yes</option>
          <option value="No"  <?= ($entry['refresher_done']??'')==='No'?'selected':'' ?>>No</option>
        </select>
      </div>
      <div id="refresher_detail_box" style="<?= ($entry['refresher_done']??'')==='Yes'?'':'display:none' ?>">
        <div class="fld"><label>Details</label><textarea name="refresher_detail" placeholder="Employee name, topic, date..." <?= $editable?'':'disabled' ?>><?= $v('refresher_detail') ?></textarea></div>
      </div>
    </div>
  </div>

  <!-- Site Improvement Work -->
  <div class="jat-section">
    <h3>🔧 Site Improvement Work with Employees</h3>
    <div class="notice" style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:10px 14px;margin-bottom:12px;font-size:13px;color:#1e40af;">
      ℹ️ Add one entry per employee you worked with on site improvement this week.
    </div>
    <div id="jat-improvement-list"></div>
    <?php if ($editable): ?>
    <button type="button" class="add-btn" onclick="addJatImprovement()">+ Add employee / site improvement</button>
    <?php endif; ?>
    <input type="hidden" name="site_improvements" id="jat_site_improvements_json" value="<?= $v('site_improvements') ?>">
  </div>

  <!-- MSU -->
  <div class="jat-section">
    <h3>📹 Mobile Surveillance Unit (MSU)</h3>
    <div class="jat-grid">
      <div class="fld"><label>Units picked up this week</label><input type="number" name="msu_pickup" value="<?= $v('msu_pickup') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld"><label>Units dropped off this week</label><input type="number" name="msu_dropoff" value="<?= $v('msu_dropoff') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
      <div class="fld">
        <label>Troubleshooting done?</label>
        <select name="msu_troubleshoot" onchange="toggleJatSection('msu_trouble_detail',this.value.startsWith('Yes'))" <?= $editable?'':'disabled' ?>>
          <option value="">— select —</option>
          <option value="No issues" <?= ($entry['msu_troubleshoot']??'')==='No issues'?'selected':'' ?>>No issues</option>
          <option value="Yes — minor, resolved on site" <?= ($entry['msu_troubleshoot']??'')==='Yes — minor, resolved on site'?'selected':'' ?>>Yes — minor, resolved on site</option>
          <option value="Yes — escalated for repair" <?= ($entry['msu_troubleshoot']??'')==='Yes — escalated for repair'?'selected':'' ?>>Yes — escalated for repair</option>
        </select>
      </div>
      <div class="fld">
        <label>After-hours response?</label>
        <select name="afterhours_response" onchange="toggleJatSection('afterhours_detail',this.value==='Yes')" <?= $editable?'':'disabled' ?>>
          <option value="">— select —</option>
          <option value="No"  <?= ($entry['afterhours_response']??'')==='No'?'selected':'' ?>>No</option>
          <option value="Yes" <?= ($entry['afterhours_response']??'')==='Yes'?'selected':'' ?>>Yes</option>
        </select>
      </div>
    </div>
    <div id="msu_trouble_detail" style="<?= (($entry['msu_troubleshoot']??'')?str_starts_with($entry['msu_troubleshoot']??'','Yes'):'false')?'':'display:none' ?>;margin-top:10px;">
      <div class="fld"><label>Troubleshooting details</label><textarea name="msu_trouble_notes" placeholder="Describe the issue and what was done..." <?= $editable?'':'disabled' ?>><?= $v('msu_trouble_notes') ?></textarea></div>
    </div>
    <div id="afterhours_detail" style="<?= ($entry['afterhours_response']??'')==='Yes'?'':'display:none' ?>;margin-top:10px;">
      <div class="jat-grid">
        <div class="fld"><label>Site responded to</label>
          <select name="afterhours_site" <?= $editable?'':'disabled' ?>>
            <option value="">— select site —</option>
            <?php foreach ($sites as $s): ?><option value="<?= htmlspecialchars($s) ?>" <?= ($entry['afterhours_site']??'')===$s?'selected':'' ?>><?= htmlspecialchars($s) ?></option><?php endforeach; ?>
          </select>
        </div>
        <div class="fld"><label>Time of response</label><input type="time" name="afterhours_time" value="<?= $v('afterhours_time') ?>" <?= $editable?'':'disabled' ?>></div>
        <div class="fld"><label>What happened / action taken</label><textarea name="afterhours_notes" placeholder="Describe the situation and what you did..." <?= $editable?'':'disabled' ?>><?= $v('afterhours_notes') ?></textarea></div>
      </div>
    </div>
    <div style="margin-top:10px;"><div class="fld"><label>MSU general notes</label><textarea name="msu_notes" placeholder="Any other MSU activity, issues, or updates..." <?= $editable?'':'disabled' ?>><?= $v('msu_notes') ?></textarea></div></div>
  </div>

  <!-- Phone Audit -->
  <div class="jat-section">
    <h3>📱 Phone Audit (Apple Business)</h3>
    <div class="jat-grid">
      <div class="fld"><label>Phone audit done this week?</label>
        <select name="phone_audit_done" <?= $editable?'':'disabled' ?>>
          <option value="">— select —</option>
          <option value="Yes — all phones checked" <?= ($entry['phone_audit_done']??'')==='Yes — all phones checked'?'selected':'' ?>>Yes — all phones checked</option>
          <option value="Partial — some phones checked" <?= ($entry['phone_audit_done']??'')==='Partial — some phones checked'?'selected':'' ?>>Partial — some phones checked</option>
          <option value="No — not this week" <?= ($entry['phone_audit_done']??'')==='No — not this week'?'selected':'' ?>>No — not this week</option>
        </select>
      </div>
      <div class="fld"><label>All necessary items saved?</label>
        <select name="phone_items_saved" <?= $editable?'':'disabled' ?>>
          <option value="">— select —</option>
          <option value="Yes — all phones compliant" <?= ($entry['phone_items_saved']??'')==='Yes — all phones compliant'?'selected':'' ?>>Yes — all phones compliant</option>
          <option value="No — issues found (see notes)" <?= ($entry['phone_items_saved']??'')==='No — issues found (see notes)'?'selected':'' ?>>No — issues found (see notes)</option>
          <option value="N/A" <?= ($entry['phone_items_saved']??'')==='N/A'?'selected':'' ?>>N/A</option>
        </select>
      </div>
      <div class="fld"><label>Unauthorized apps found?</label>
        <select name="phone_unauth_apps" onchange="toggleJatSection('phone_apps_detail',this.value==='Yes')" <?= $editable?'':'disabled' ?>>
          <option value="">— select —</option>
          <option value="No" <?= ($entry['phone_unauth_apps']??'')==='No'?'selected':'' ?>>No — all clear</option>
          <option value="Yes" <?= ($entry['phone_unauth_apps']??'')==='Yes'?'selected':'' ?>>Yes — removed</option>
        </select>
      </div>
      <div class="fld"><label>Number of phones audited</label><input type="number" name="phone_count" value="<?= $v('phone_count') ?>" placeholder="0" min="0" <?= $editable?'':'disabled' ?>></div>
    </div>
    <div id="phone_apps_detail" style="<?= ($entry['phone_unauth_apps']??'')==='Yes'?'':'display:none' ?>;margin-top:10px;">
      <div class="fld"><label>Apps found / action taken</label><textarea name="phone_apps_notes" placeholder="Which apps were found, what was done..." <?= $editable?'':'disabled' ?>><?= $v('phone_apps_notes') ?></textarea></div>
    </div>
    <div style="margin-top:10px;"><div class="fld"><label>Phone audit notes</label><textarea name="phone_notes" placeholder="Any issues, follow-ups, or general notes..." <?= $editable?'':'disabled' ?>><?= $v('phone_notes') ?></textarea></div></div>
  </div>

  <!-- General Notes -->
  <div class="jat-section">
    <h3>📝 General Notes</h3>
    <div class="jat-grid-wide">
      <div class="fld"><label>Highlights this week</label><textarea name="highlights" placeholder="What went well..." <?= $editable?'':'disabled' ?>><?= $v('highlights') ?></textarea></div>
      <div class="fld"><label>Concerns / challenges</label><textarea name="concerns" placeholder="Any issues or blockers..." <?= $editable?'':'disabled' ?>><?= $v('concerns') ?></textarea></div>
      <div class="fld"><label>Remarks</label><textarea name="remarks" placeholder="Anything else..." <?= $editable?'':'disabled' ?>><?= $v('remarks') ?></textarea></div>
    </div>
  </div>

  <!-- Actions -->
  <?php if ($editable): ?>
  <div style="display:flex;justify-content:flex-end;gap:14px;padding:8px 0 32px;">
    <?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/jatinder-kpi/my-records" class="btn-secondary" style="text-decoration:none;padding:12px 24px;">Cancel</a>
    <?php endif; ?>
    <button type="submit" class="btn-secondary" style="padding:12px 24px;">💾 Save Draft</button>
    <button type="submit" name="then_submit" value="1" class="btn-primary" style="padding:12px 28px;"
            onclick="return confirm('Submit this week\'s KPI for review? You will not be able to edit it after submitting.');">
      ✅ Submit for Review
    </button>
  </div>
  <?php endif; ?>
</form>

<script>
function toggleJatSection(id, show){
  var el = document.getElementById(id);
  if(el) el.style.display = show ? 'block' : 'none';
}
function updateInspTotals(){
  var gi = function(id){ return parseInt(document.getElementById(id)?.value)||0; };
  var total  = gi('insp_day_total')+gi('insp_swing_total')+gi('insp_grave_total');
  var failed = gi('insp_day_failed')+gi('insp_swing_failed')+gi('insp_grave_failed');
  var pass   = total>0 ? Math.round(((total-failed)/total)*100) : null;
  document.getElementById('tot_total').textContent  = total;
  document.getElementById('tot_failed').textContent = failed;
  document.getElementById('tot_pass').textContent   = pass!==null ? pass+'%' : '—';
  document.getElementById('insp_total_val').value   = total;
  document.getElementById('insp_failed_val').value  = failed;
}
// ── Site Improvement Work — dynamic entries ──────────────────────────────
var jatImprovements = [];
try { jatImprovements = JSON.parse(document.getElementById('jat_site_improvements_json').value || '[]'); } catch(e){}

var jatImpCount = 0;
var jatEmpNames = <?= json_encode($allPeopleNames ?? []) ?>;
var jatSites = <?= json_encode($sites) ?>;
var jatAreaOptions = ['Uniform compliance','Post orders','Professionalism','Equipment check','Patrol procedures','Report writing','Customer service','Emergency response','Other'];
var jatStatusOptions = ['In progress','Completed','Follow-up needed','Escalated'];

function jatSiteOpts(selected) {
  return '<option value="">— select site —</option>' + jatSites.map(function(s){
    return '<option value="'+s+'"'+(s===selected?' selected':'')+'>'+s+'</option>';
  }).join('');
}
function jatAreaOpts(selected) {
  return '<option value="">— select —</option>' + jatAreaOptions.map(function(a){
    return '<option value="'+a+'"'+(a===selected?' selected':'')+'>'+a+'</option>';
  }).join('');
}
function jatStatusOpts(selected) {
  return '<option value="">— select —</option>' + jatStatusOptions.map(function(a){
    return '<option value="'+a+'"'+(a===selected?' selected':'')+'>'+a+'</option>';
  }).join('');
}

function addJatImprovement(data) {
  data = data || {};
  jatImpCount++;
  var id = 'jimp' + jatImpCount;
  var div = document.createElement('div');
  div.className = 'dyn-entry';
  div.id = id;
  // Build employee options from PHP
  var empOptions = '<option value="">— select employee —</option>' + jatEmpNames.map(function(n){
    return '<option value="'+n+'"'+(n===data.employee?' selected':'')+'>'+n+'</option>';
  }).join('');
  div.innerHTML =
    '<button type="button" class="remove-btn" onclick="this.parentElement.remove();saveJatImprovements()">×</button>' +
    '<div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr 1fr;gap:12px;margin-bottom:10px;">' +
      '<div class="fld"><label>Employee</label><select onchange="saveJatImprovements()">'+empOptions+'</select></div>' +
      '<div class="fld"><label>Site</label><select onchange="saveJatImprovements()">'+jatSiteOpts(data.site||'')+'</select></div>' +
      '<div class="fld"><label>Area of improvement</label><select onchange="saveJatImprovements()">'+jatAreaOpts(data.area||'')+'</select></div>' +
      '<div class="fld"><label>Score before (1–5)</label><input type="number" min="1" max="5" step="0.1" placeholder="e.g. 2.5" value="'+(data.score_before||'')+'" oninput="saveJatImprovements()"></div>' +
      '<div class="fld"><label>Score this week (1–5)</label><input type="number" min="1" max="5" step="0.1" placeholder="e.g. 4.0" value="'+(data.score_this_week||'')+'" oninput="saveJatImprovements()"></div>' +
    '</div>' +
    '<div style="display:grid;grid-template-columns:200px 1fr;gap:12px;margin-bottom:10px;">' +
      '<div class="fld"><label>Recertified with signed ROT?</label><select onchange="saveJatImprovements()">' +
        '<option value="">— select —</option><option value="Yes"'+(data.recertified_rot==='Yes'?' selected':'')+'>Yes</option><option value="No"'+(data.recertified_rot==='No'?' selected':'')+'>No</option>' +
      '</select></div>' +
      '<div class="fld"><label>ROT signed description</label><textarea placeholder="Describe what was covered when ROT was signed..." oninput="saveJatImprovements()">'+(data.rot_signed_desc||'')+'</textarea></div>' +
    '</div>' +
    '<div style="display:grid;grid-template-columns:200px 1fr;gap:12px;">' +
      '<div class="fld"><label>Improvement status</label><select onchange="saveJatImprovements()">'+jatStatusOpts(data.improvement_status||'')+'</select></div>' +
      '<div class="fld"><label>Improvement notes</label><textarea placeholder="What was worked on, what changed, what still needs attention..." oninput="saveJatImprovements()">'+(data.improvement_notes||'')+'</textarea></div>' +
    '</div>';
  document.getElementById('jat-improvement-list').appendChild(div);
}

function saveJatImprovements() {
  var entries = [];
  document.querySelectorAll('#jat-improvement-list .dyn-entry').forEach(function(div) {
    var inputs = div.querySelectorAll('input,select,textarea');
    entries.push({
      employee: inputs[0].value,
      site: inputs[1].value,
      area: inputs[2].value,
      score_before: inputs[3].value,
      score_this_week: inputs[4].value,
      recertified_rot: inputs[5].value,
      rot_signed_desc: inputs[6].value,
      improvement_status: inputs[7].value,
      improvement_notes: inputs[8].value
    });
  });
  document.getElementById('jat_site_improvements_json').value = JSON.stringify(entries);
}

// Pre-populate saved entries
(function(){
  if (jatImprovements && jatImprovements.length) {
    jatImprovements.forEach(function(d){ addJatImprovement(d); });
  }
  <?php if (!$editable): ?>
  // Disable all inputs in improvement section if not editable
  document.querySelectorAll('#jat-improvement-list input,#jat-improvement-list select,#jat-improvement-list textarea').forEach(function(el){ el.disabled=true; });
  document.querySelectorAll('#jat-improvement-list .remove-btn').forEach(function(el){ el.style.display='none'; });
  <?php endif; ?>
})();
// Resize in modal
<?php if ($isModalMode): ?>
(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});
})();
<?php endif; ?>
// Auto-select on focus for all number inputs
window.addEventListener('load', function(){
  document.querySelectorAll('input[type="number"]').forEach(function(el){
    el.addEventListener('focus', function(){ this.select(); });
  });
  new MutationObserver(function(muts){
    muts.forEach(function(m){
      m.addedNodes.forEach(function(n){
        if(n.nodeType!==1) return;
        (n.matches('input[type="number"]')?[n]:[...n.querySelectorAll('input[type="number"]')]).forEach(function(el){
          el.addEventListener('focus',function(){this.select();});
        });
      });
    });
  }).observe(document.body,{childList:true,subtree:true});
});
</script>

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