<?php
$active      = 'home';
$pageTitle   = 'Weekly KPI Entry';
$isModalMode = !empty($_GET['modal']);

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="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
}

$v = fn($k) => htmlspecialchars((string)($entry[$k] ?? ''));
?>
<?php if (!$isModalMode): ?>
<div class="topbar">
  <div>
    <h1>Weekly KPI Entry — Scheduling</h1>
    <div class="crumbs">
      <a href="/workspace" style="color:var(--blue-600);">Workspace</a> →
      <a href="/projects/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"><strong>Returned for edits:</strong> <?= htmlspecialchars($entry['return_reason']) ?></div>
<?php endif; ?>

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

  <div class="card">
    <h3>Week</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
      <div class="field">
        <label>Week Starting</label>
        <input type="date" name="week_starting" id="kpi_week_starting"
               value="" data-saved="<?= htmlspecialchars($entry['week_starting'] ?? '') ?>"
               onchange="this._manual=true">
      </div>
      <div class="field">
        <label>Week Ending</label>
        <input type="date" name="week_ending" id="kpi_week_ending"
               value="" data-saved="<?= htmlspecialchars($entry['week_ending'] ?? '') ?>" required
               onchange="if(!document.getElementById('kpi_week_starting')._manual){var d=new Date(this.value);d.setDate(d.getDate()-6);document.getElementById('kpi_week_starting').value=d.toISOString().slice(0,10);}">
      </div>
      <div class="field"><label>Total Hours Worked</label><input type="number" step="0.1" name="total_hours" value="<?= $v('total_hours') ?>" placeholder="0.0"></div>
    </div>
  </div>

  <div class="card">
    <h3>Hours Breakdown</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:16px;">
      <div class="field"><label>Static Hours</label><input type="number" step="0.1" id="static_hours_input" name="static_hours" value="<?= $v('static_hours') ?>" placeholder="0.0" oninput="calcHrsCheck()"></div>
      <div class="field"><label>Patrol Hours</label><input type="number" step="0.1" id="patrol_hours_input" name="patrol_hours" value="<?= $v('patrol_hours') ?>" placeholder="0.0" oninput="calcHrsCheck()"></div>
      <div class="field"><label>Event Hours</label><input type="number" step="0.1" id="event_hours_input" name="event_hours" value="<?= $v('event_hours') ?>" placeholder="0.0" oninput="calcHrsCheck()"></div>
      <div class="field">
        <label>Hours Check (auto)</label>
        <input type="text" id="hrs_check_display" readonly placeholder="—">
        <small style="color:var(--text-muted);display:block;margin-top:4px;">Static + Patrol + Event</small>
      </div>
    </div>
  </div>

  <div class="card">
    <h3>OT / DT Hours</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:16px;">
      <div class="field"><label>OT Hours</label><input type="number" step="0.1" name="ot_hours" value="<?= $v('ot_hours') ?>" placeholder="0.0"></div>
      <div class="field"><label>OT % (auto)</label><input type="text" id="ot_pct_display" name="ot_pct" value="<?= $v('ot_pct') ?>" placeholder="—"></div>
      <div class="field"><label>DT Hours</label><input type="number" step="0.1" name="dt_hours" value="<?= $v('dt_hours') ?>" placeholder="0.0"></div>
      <div class="field"><label>DT % (auto)</label><input type="text" id="dt_pct_display" name="dt_pct" value="<?= $v('dt_pct') ?>" placeholder="—"></div>
    </div>
    <div class="field" style="margin-top:4px;">
      <label>OT / DT Hours — Notes / Explanation</label>
      <textarea name="ot_notes" rows="3" placeholder="Why was OT high or low this week? e.g. fire event coverage, call-offs, open posts..."><?= $v('ot_notes') ?></textarea>
      <small style="color:var(--text-muted);display:block;margin-top:4px;">Optional. Shown to your reviewer next to the OT numbers above.</small>
    </div>
  </div>

  <div class="card">
    <h3>Coverage &amp; Staffing</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
      <div class="field"><label>Open Post Hours</label><input type="number" step="0.1" name="open_post_hours" value="<?= $v('open_post_hours') ?>" placeholder="0.0"></div>
      <div class="field"><label>New Hires</label><input type="number" name="new_hires" value="<?= $v('new_hires') ?>" placeholder="0"></div>
      <div class="field"><label>Terminations</label><input type="number" name="terminations" value="<?= $v('terminations') ?>" placeholder="0"></div>
      <div class="field"><label>Open Requisition Hours</label><input type="number" step="0.1" name="open_requisition_hours" value="<?= $v('open_requisition_hours') ?>" placeholder="0.0"></div>
      <div class="field" style="grid-column:span 2;"><label>Open Job Sites</label><input type="text" name="open_sites" value="<?= $v('open_sites') ?>" placeholder="e.g. Harbor North, Westfield East"></div>
    </div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:4px;">
      <div class="field">
        <label>Coverage — Notes / Explanation</label>
        <textarea name="coverage_notes" rows="3" placeholder="Open posts, uncovered shifts, how coverage was arranged..."><?= $v('coverage_notes') ?></textarea>
      </div>
      <div class="field">
        <label>Staffing — Notes / Explanation</label>
        <textarea name="staffing_notes" rows="3" placeholder="Openings unfilled, hiring status, short-staffed sites..."><?= $v('staffing_notes') ?></textarea>
      </div>
    </div>
    <small style="color:var(--text-muted);display:block;margin-top:4px;">Optional. Shown to your reviewer next to the coverage and staffing numbers above.</small>
  </div>

  <div class="card">
    <h3>Inspections &amp; Incidents</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
      <div class="field"><label>Guard Inspections</label><input type="number" name="guard_inspections" value="<?= $v('guard_inspections') ?>" placeholder="0"></div>
      <div class="field"><label>Failed Inspections</label><input type="number" name="failed_inspections" value="<?= $v('failed_inspections') ?>" placeholder="0"></div>
      <div class="field"><label>Incident Reports</label><input type="number" name="incidents" value="<?= $v('incidents') ?>" placeholder="0"></div>
      <div class="field"><label>Avg Response Time (hrs)</label><input type="number" step="0.1" name="avg_response_hours" value="<?= $v('avg_response_hours') ?>" placeholder="0.0"></div>
      <div class="field"><label>Client Complaints</label><input type="number" name="client_complaints" value="<?= $v('client_complaints') ?>" placeholder="0"></div>
      <div class="field"><label>Employee Complaints</label><input type="number" name="employee_complaints" value="<?= $v('employee_complaints') ?>" placeholder="0"></div>
    </div>
  </div>

  <div class="card">
    <h3>Time Off &amp; Call-Offs</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
      <div class="field"><label>Time Off Requests</label><input type="number" name="pto_requests" value="<?= $v('pto_requests') ?>" placeholder="0"></div>
      <div class="field"><label>Weekly Call-Off Hours</label><input type="number" step="0.1" name="call_off_hours" value="<?= $v('call_off_hours') ?>" placeholder="0.0"></div>
    </div>
    <div class="field" style="margin-top:4px;">
      <label>Time-Off Requests — Notes / Explanation</label>
      <textarea name="time_off_notes" rows="3" placeholder="Who requested time off, approved/denied, impact on coverage..."><?= $v('time_off_notes') ?></textarea>
      <small style="color:var(--text-muted);display:block;margin-top:4px;">Optional. Shown to your reviewer next to the time-off numbers above.</small>
    </div>
  </div>

  <div class="card">
    <h3>Scheduling &amp; Audits</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
      <div class="field"><label>Hours on Scheduling</label><input type="number" step="0.1" name="scheduled_hours" value="<?= $v('scheduled_hours') ?>" placeholder="0.0"></div>
      <div class="field"><label>Time on Employee Audit (hrs)</label><input type="number" step="0.1" name="audit_hours" value="<?= $v('audit_hours') ?>" placeholder="0.0"></div>
    </div>
  </div>

  <div class="card">
    <h3>Backup Employee for Weekend</h3>
    <div id="backupList"></div>
    <button type="button" class="btn-secondary" onclick="addBackupRow()">+ Add Employee</button>
    <input type="hidden" name="backup_employees" id="backup_employees_json" value="<?= $v('backup_employees') ?>">
  </div>

  <div class="card">
    <h3>Training Information</h3>
    <div class="field">
      <label>Did you receive any training from Cesar?</label>
      <div style="display:flex;gap:24px;">
        <label style="display:inline-flex;align-items:center;font-weight:500;text-transform:none;"><input type="radio" name="cesar_training" value="Yes" <?= ($entry['cesar_training'] ?? '') === 'Yes' ? 'checked' : '' ?>> Yes</label>
        <label style="display:inline-flex;align-items:center;font-weight:500;text-transform:none;"><input type="radio" name="cesar_training" value="No" <?= ($entry['cesar_training'] ?? '') === 'No' ? 'checked' : '' ?>> No</label>
      </div>
    </div>
    <div class="field"><label>Training Details</label><textarea name="cesar_training_details" rows="4"><?= $v('cesar_training_details') ?></textarea></div>
  </div>

  <div class="card">
    <h3>Notes</h3>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
      <div class="field"><label>Team Learning / Development</label><textarea name="learning_development" rows="4" placeholder="Trainings, certs, SOP updates..."><?= $v('learning_development') ?></textarea></div>
      <div class="field"><label>Employee Concern / Feedback</label><textarea name="employee_concerns" rows="4" placeholder="Any concerns or feedback..."><?= $v('employee_concerns') ?></textarea></div>
      <div class="field"><label>Remarks</label><textarea name="remarks" rows="4" placeholder="Anything else..."><?= $v('remarks') ?></textarea></div>
    </div>
  </div>

  <div class="card" style="display:flex;gap:12px;justify-content:flex-end;">
    <?php if ($isModalMode): ?>
      <button type="button" class="btn-secondary" style="padding:11px 20px;"
              onclick="window.parent.postMessage({type:'kpi-cancel'},'*')">Cancel</button>
    <?php else: ?>
      <a href="/projects/kpi/my-records" class="btn-secondary" style="text-decoration:none;padding:11px 20px;">Cancel</a>
    <?php endif; ?>
    <button type="submit" class="btn-secondary">💾 Save Draft</button>
    <button type="submit" name="then_submit" value="1" class="btn-primary" 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>
</form>

<script>
let totalHoursManuallyEdited = document.querySelector('[name=total_hours]').value.trim() !== '';
document.querySelector('[name=total_hours]').addEventListener('input', () => { totalHoursManuallyEdited = true; });

function calcHrsCheck(){
  const s = parseFloat(document.getElementById('static_hours_input').value) || 0;
  const p = parseFloat(document.getElementById('patrol_hours_input').value) || 0;
  const e = parseFloat(document.getElementById('event_hours_input').value) || 0;
  const sum = s + p + e;
  document.getElementById('hrs_check_display').value = sum.toFixed(1);

  if (!totalHoursManuallyEdited) {
    document.querySelector('[name=total_hours]').value = sum ? sum.toFixed(1) : '';
  }
  calcPct();
}
function calcPct(){
  const s = parseFloat(document.getElementById('static_hours_input').value) || 0;
  const p = parseFloat(document.getElementById('patrol_hours_input').value) || 0;
  const e = parseFloat(document.getElementById('event_hours_input').value) || 0;
  const ot = parseFloat(document.querySelector('[name=ot_hours]').value) || 0;
  const dt = parseFloat(document.querySelector('[name=dt_hours]').value) || 0;
  const typedTotal = parseFloat(document.querySelector('[name=total_hours]').value) || 0;
  const breakdownSum = s + p + e;
  // Use total_hours if typed; else breakdown sum; else OT+DT as minimum denominator
  const total = typedTotal || breakdownSum || (ot + dt);
  document.getElementById('ot_pct_display').value = (total && ot) ? ((ot/total)*100).toFixed(1) : '';
  document.getElementById('dt_pct_display').value = (total && dt) ? ((dt/total)*100).toFixed(1) : '';
}
['total_hours','ot_hours','dt_hours'].forEach(n => {
  document.querySelector(`[name=${n}]`).addEventListener('input', calcPct);
});

const DAYS = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
const ALL_PEOPLE_NAMES = <?= json_encode($allPeopleNames ?? []) ?> || [];

function wireTypeahead(input){
  const box = input.nextElementSibling; // .be-suggest
  function close(){ box.innerHTML=''; box.style.display='none'; }
  function render(matches){
    if (!matches.length){ close(); return; }
    box.innerHTML = matches.slice(0,50).map(n =>
      `<div class="be-suggest-item">${n}</div>`
    ).join('');
    box.style.display = 'block';
    box.querySelectorAll('.be-suggest-item').forEach(item => {
      item.addEventListener('mousedown', e => {
        e.preventDefault();
        input.value = item.textContent;
        close();
        syncBackup();
      });
    });
  }
  input.addEventListener('input', () => {
    const q = input.value.trim().toLowerCase();
    render(q ? ALL_PEOPLE_NAMES.filter(n => n.toLowerCase().includes(q)) : ALL_PEOPLE_NAMES);
  });
  input.addEventListener('focus', () => {
    const q = input.value.trim().toLowerCase();
    render(q ? ALL_PEOPLE_NAMES.filter(n => n.toLowerCase().includes(q)) : ALL_PEOPLE_NAMES);
  });
  input.addEventListener('blur', () => setTimeout(close, 120));
}

function renderBackupRows(rows){
  const list = document.getElementById('backupList');
  list.innerHTML = '';
  rows.forEach((r, i) => {
    const shifts = (r.shifts || '').split(',').map(s => s.trim()).filter(Boolean);
    const days = (r.days || '').split(',').map(s => s.trim()).filter(Boolean);

    const wrap = document.createElement('div');
    wrap.className = 'backup-emp-entry';
    wrap.style = 'border:1px solid var(--border);border-radius:14px;padding:18px 20px;margin-bottom:16px;position:relative;background:#fbfcfe;';

    const dayCheckboxes = DAYS.map(d => `
      <label style="display:inline-flex;align-items:center;gap:5px;font-weight:500;text-transform:none;margin-right:14px;font-size:13px;">
        <input type="checkbox" class="be-day" value="${d}" ${days.includes(d) ? 'checked' : ''}> ${d}
      </label>`).join('');

    const shiftOptions = ['Day Shift','Swing Shift','Grave Shift'].map(s =>
      `<option value="${s}" ${shifts.includes(s) ? 'selected' : ''}>${s}</option>`
    ).join('');

    wrap.innerHTML = `
      <button type="button" onclick="this.closest('.backup-emp-entry').remove(); syncBackup();"
        style="position:absolute;top:14px;right:16px;background:none;border:none;color:var(--text-muted);cursor:pointer;font-size:16px;">✕</button>
      <div style="display:grid;grid-template-columns:2fr 1.4fr 1fr;gap:20px;margin-bottom:14px;">
        <div class="field" style="margin-bottom:0;position:relative;">
          <label>Employee Name</label>
          <input type="text" class="be-name" autocomplete="off" value="${(r.name||'').replace(/"/g,'&quot;')}" placeholder="Search employee name...">
          <div class="be-suggest"></div>
        </div>
        <div class="field" style="margin-bottom:0;">
          <label>Shift Availability</label>
          <select class="be-shifts" multiple size="3" style="width:100%;padding:8px;border:1px solid var(--border);border-radius:10px;">${shiftOptions}</select>
          <small style="color:var(--text-muted);">Hold Ctrl/Cmd to select multiple</small>
        </div>
        <div class="field" style="margin-bottom:0;">
          <label>Date</label>
          <input type="date" class="be-date" value="${r.date||''}">
        </div>
      </div>
      <div class="field" style="margin-bottom:0;">
        <label>Day(s) Available</label><br>
        ${dayCheckboxes}
      </div>`;
    list.appendChild(wrap);
    wireTypeahead(wrap.querySelector('.be-name'));
  });
}
function addBackupRow(){
  const current = readBackup();
  current.push({name:'',shifts:'',days:'',date:''});
  renderBackupRows(current);
}
function readBackup(){
  return Array.from(document.querySelectorAll('.backup-emp-entry')).map(el => ({
    name: el.querySelector('.be-name').value,
    shifts: Array.from(el.querySelectorAll('.be-shifts option:checked')).map(o => o.value).join(', '),
    days: Array.from(el.querySelectorAll('.be-day:checked')).map(c => c.value).join(', '),
    date: el.querySelector('.be-date').value,
  }));
}
function syncBackup(){ document.getElementById('backup_employees_json').value = JSON.stringify(readBackup()); }
document.querySelector('form').addEventListener('submit', syncBackup);
document.getElementById('backupList').addEventListener('input', syncBackup);
document.getElementById('backupList').addEventListener('change', syncBackup);

try {
  const initial = JSON.parse(document.getElementById('backup_employees_json').value || '[]');
  renderBackupRows(initial);
} catch(e) { renderBackupRows([]); }
calcPct();
calcHrsCheck();

<?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; ?>
</script>

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