<?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);
        }
    }
}
$active      = 'home';
$pageTitle   = 'KPI Record';
$isAdminView = $user['is_super_admin'];
$isModalMode = !empty($_GET['modal']);

if (!$isModalMode) {
    require __DIR__ . ($isAdminView ? '/../layout/admin_header.php' : '/../layout/workspace_header.php');
} else {
    ?><!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="stylesheet" href="/assets/css/app.css?v=<?= defined('ASSET_VERSION') ? ASSET_VERSION : time() ?>">
    <style>body,.admin-shell{background:#fff!important;}.main-inner{padding:20px 24px 32px!important;}.sidebar{display:none!important;}.main{margin:0!important;}</style>
    </head><body><div class="admin-shell"><main class="main"><div class="main-inner">
    <?php
}
if ($isAdminView) { $admin = $user; }
$statusColors = ['draft'=>'badge-role-default','submitted'=>'badge-role-manager','reviewed'=>'badge-role-director','approved'=>'badge-role-employee','returned'=>'badge-role-ceo','locked'=>'badge-role-super'];
$displayGroups = \App\Core\KpiFieldLabels::groups();
// Detail fields shown in the main grid exclude submission/review/history
// groups, which already have their own dedicated sections on this page.
unset($displayGroups['Submission'], $displayGroups['Review & Approval'], $displayGroups['History'], $displayGroups['Backup Employees for Weekend']);
?>
<div class="topbar">
  <div>
    <h1>Weekly KPI — <?= htmlspecialchars($entry['submitter_name']) ?> — <?= fmtDate($entry['week_ending']) ?></h1>
    <div class="crumbs">Workspace → Projects → KPI Tracker → Record #<?= $entry['id'] ?></div>
  </div>
  <span class="badge <?= $statusColors[$entry['status']] ?? '' ?>" style="font-size:13px;padding:8px 16px;"><?= ucfirst($entry['status']) ?></span>
</div>

<?php if ($flash): ?>
  <div class="alert alert-<?= $flash['type'] === 'error' ? 'error' : 'success' ?>"><?= htmlspecialchars($flash['msg']) ?></div>
<?php endif; ?>

<?php if ($entry['status'] === 'returned' && $entry['return_reason']): ?>
  <div class="alert alert-error"><strong>Return reason:</strong> <?= htmlspecialchars($entry['return_reason']) ?></div>
<?php endif; ?>

<?php if ($canReview && in_array($entry['status'], ['submitted','reviewed'], true)): ?>
<div class="card" style="background:linear-gradient(120deg,rgba(79,110,247,0.04),rgba(124,58,224,0.03));border-color:#c7d2fe;">
  <h3 style="margin:0 0 14px;">Review Actions</h3>
  <form method="POST" action="/projects/kpi/review-action"
        onsubmit="return validateApprove(this);">
    <input type="hidden" name="id" value="<?= $entry['id'] ?>">
    <input type="hidden" name="action" value="approve">
    <?php if ($isModalMode): ?><input type="hidden" name="modal" value="1"><?php endif; ?>
    <div style="display:grid;grid-template-columns:140px 1fr;gap:12px;margin-bottom:14px;">
      <div>
        <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted);display:block;margin-bottom:6px;">Score (1–10) <span style="color:#dc2626;">*</span></label>
        <input type="number" name="review_score" id="rs_<?= $entry['id'] ?>" min="1" max="10" step="1" placeholder="8"
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
      </div>
      <div>
        <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted);display:block;margin-bottom:6px;">Review comments <span style="color:#dc2626;">*</span></label>
        <input type="text" name="review_comment_approve" id="rc_<?= $entry['id'] ?>" placeholder="What went well, areas to improve..."
               style="width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;">
      </div>
    </div>
    <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
      <button type="submit" class="btn-primary">✅ Approve &amp; Lock</button>
      <span style="color:var(--text-muted);font-size:13px;">— or —</span>
    </div>
  </form>
  <form method="POST" action="/projects/kpi/review-action" style="display:flex;gap:8px;align-items:center;margin-top:10px;flex-wrap:wrap;"
        onsubmit="if(!document.getElementById('returnReason_<?= $entry['id'] ?>').value.trim()){alert('Please enter a return reason.');return false;}return true;">
    <input type="hidden" name="id" value="<?= $entry['id'] ?>">
    <input type="hidden" name="action" value="return">
    <?php if ($isModalMode): ?><input type="hidden" name="modal" value="1"><?php endif; ?>
    <input type="text" id="returnReason_<?= $entry['id'] ?>" name="return_reason" placeholder="Return reason (required)" required
           style="flex:1;min-width:260px;padding:10px 14px;border:1px solid var(--border);border-radius:10px;font-size:13px;">
    <button type="submit" class="btn-danger">↩ Return for Edits</button>
  </form>
  <form method="POST" action="/projects/kpi/review-action" style="margin-top:8px;">
    <input type="hidden" name="id" value="<?= $entry['id'] ?>">
    <input type="hidden" name="action" value="comment">
    <?php if ($isModalMode): ?><input type="hidden" name="modal" value="1"><?php endif; ?>
    <input type="hidden" name="comment" id="commentVal_<?= $entry['id'] ?>">
    <button type="button" class="btn-secondary"
            onclick="var c=prompt('Add a comment:');if(c&&c.trim()){document.getElementById('commentVal_<?= $entry['id'] ?>').value=c;this.form.submit();}">
      💬 Add Comment
    </button>
  </form>
</div>
<script>
function validateApprove(form) {
  var score = form.querySelector('[name="review_score"]').value;
  var comment = form.querySelector('[name="review_comment_approve"]').value.trim();
  if (!score || score < 1 || score > 10) { alert('Please enter a score between 1 and 10 before approving.'); return false; }
  if (!comment) { alert('Please enter review comments before approving.'); return false; }
  return confirm('Approve and lock this KPI record?');
}
</script>
<?php endif; ?>

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

<?php
// ── Review discussion thread ──────────────────────────────────────────────
// The reviewer's comment (still stored on the KPI row itself) is the root of
// the chain. Every reply after it lives in `kpi_discussion`. Posting here
// never alters the KPI record's status, score, or lock state.
$reviewRoot   = trim((string)($entry['review_comment'] ?? ''));
$threadMsgs   = \App\Models\KpiDiscussion::forEntry((int)$entry['id']);
$showThread   = ($reviewRoot !== '') || !empty($threadMsgs);
// Only the KPI owner (the concerned person whose KPI this is) may post a
// response. Reviewers and senior oversight (Cesar, Sara, super admins) are
// view-only on the thread — they see the full history but get no reply box.
$canPostReply = ($isOwner ?? false);
$rootWhen     = $entry['approved_at'] ?: ($entry['reviewed_at'] ?: $entry['locked_at']);
?>
<?php if ($showThread): ?>
<div class="card" id="kpi-discussion">
  <h3 style="margin:0 0 4px;">💬 Review Discussion</h3>
  <p style="font-size:12.5px;color:var(--text-muted);margin:0 0 18px;">
    The full conversation on this KPI, oldest first. Everything stays attached to this record.
  </p>

  <?php if ($reviewRoot !== ''): ?>
    <div style="display:flex;gap:12px;margin-bottom:16px;">
      <div style="flex:0 0 4px;background:#3B6D11;border-radius:2px;"></div>
      <div style="flex:1;background:#F6FAF1;border:1px solid #DCEAC9;border-radius:10px;padding:12px 14px;">
        <div style="display:flex;justify-content:space-between;align-items:baseline;gap:10px;flex-wrap:wrap;">
          <div style="font-size:13px;font-weight:700;color:#3B6D11;">
            <?= htmlspecialchars($entry['reviewer_name'] ?? 'Reviewer') ?>
            <span style="font-size:11px;font-weight:600;background:#EAF3DE;color:#3B6D11;padding:2px 8px;border-radius:20px;margin-left:6px;">Reviewer</span>
          </div>
          <div style="font-size:11.5px;color:var(--text-muted);"><?= $rootWhen ? fmtDate($rootWhen, true) : '' ?></div>
        </div>
        <div style="font-size:14px;margin-top:8px;line-height:1.55;"><?= nl2br(htmlspecialchars($reviewRoot)) ?></div>
      </div>
    </div>
  <?php endif; ?>

  <?php foreach ($threadMsgs as $m): ?>
    <?php
      $isReviewerMsg = $m['author_role'] === 'reviewer';
      $accent  = $isReviewerMsg ? '#3B6D11' : '#4F6EF7';
      $bg      = $isReviewerMsg ? '#F6FAF1' : '#F5F7FF';
      $bd      = $isReviewerMsg ? '#DCEAC9' : '#D8E0FD';
      $pillBg  = $isReviewerMsg ? '#EAF3DE' : '#E5EAFE';
      $indent  = $isReviewerMsg ? '0' : '28px';
    ?>
    <div style="display:flex;gap:12px;margin-bottom:16px;margin-left:<?= $indent ?>;">
      <div style="flex:0 0 4px;background:<?= $accent ?>;border-radius:2px;"></div>
      <div style="flex:1;background:<?= $bg ?>;border:1px solid <?= $bd ?>;border-radius:10px;padding:12px 14px;">
        <div style="display:flex;justify-content:space-between;align-items:baseline;gap:10px;flex-wrap:wrap;">
          <div style="font-size:13px;font-weight:700;color:<?= $accent ?>;">
            <?= htmlspecialchars($m['author_name']) ?>
            <span style="font-size:11px;font-weight:600;background:<?= $pillBg ?>;color:<?= $accent ?>;padding:2px 8px;border-radius:20px;margin-left:6px;">
              <?= $isReviewerMsg ? 'Reviewer' : 'Response' ?>
            </span>
          </div>
          <div style="font-size:11.5px;color:var(--text-muted);"><?= fmtDate($m['created_at'], true) ?></div>
        </div>
        <div style="font-size:14px;margin-top:8px;line-height:1.55;"><?= nl2br(htmlspecialchars($m['body'])) ?></div>
      </div>
    </div>
  <?php endforeach; ?>

  <?php if ($canPostReply): ?>
    <form method="POST" action="/projects/kpi/reply" style="margin-top:18px;border-top:1px solid var(--border);padding-top:16px;"
          onsubmit="var b=document.getElementById('replyBody_<?= $entry['id'] ?>');if(!b.value.trim()){alert('Please write a response before saving.');b.focus();return false;}return true;">
      <input type="hidden" name="id" value="<?= $entry['id'] ?>">
      <?php if ($isModalMode): ?><input type="hidden" name="modal" value="1"><?php endif; ?>
      <label style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--text-muted);display:block;margin-bottom:6px;">
        Your response / explanation
      </label>
      <textarea name="reply_body" id="replyBody_<?= $entry['id'] ?>" rows="4"
                placeholder="Explain the numbers, respond to the reviewer's points, or add context..."
                style="width:100%;padding:11px 14px;border:1px solid var(--border);border-radius:10px;font-size:14px;font-family:inherit;line-height:1.5;resize:vertical;"></textarea>
      <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-top:10px;flex-wrap:wrap;">
        <span style="font-size:12px;color:var(--text-muted);">
          Saved against this KPI record and visible to your reviewer. Your KPI figures and its approved status are not affected.
        </span>
        <button type="submit" class="btn-primary">Save Response</button>
      </div>
    </form>
  <?php endif; ?>
</div>
<?php endif; ?>

<div style="display:flex;gap:8px;margin-bottom:20px;">
  <a href="/projects/kpi/export.csv?employee=<?= $entry['submitter_id'] ?>" class="btn-secondary" style="text-decoration:none;">⬇ CSV</a>
  <a href="/projects/kpi/export.xlsx?employee=<?= $entry['submitter_id'] ?>" class="btn-secondary" style="text-decoration:none;">⬇ Excel</a>
  <a href="/projects/kpi/export.pdf?employee=<?= $entry['submitter_id'] ?>" class="btn-secondary" style="text-decoration:none;">⬇ PDF</a>
</div>

<div class="card">
  <?php foreach ($displayGroups as $groupName => $fields): ?>
    <h3 style="<?= $groupName === array_key_first($displayGroups) ? '' : 'margin-top:24px;' ?>"><?= htmlspecialchars($groupName) ?></h3>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;">
      <?php foreach ($fields as $key => $label): ?>
        <div>
          <div style="font-size:11px;color:var(--text-muted);font-weight:700;text-transform:uppercase;margin-bottom:4px;"><?= htmlspecialchars($label) ?></div>
          <div style="font-weight:600;"><?= htmlspecialchars(\App\Core\KpiFieldLabels::formatValue($key, $entry[$key] ?? null)) ?></div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endforeach; ?>

  <?php $backups = json_decode($entry['backup_employees'] ?? '[]', true) ?: []; ?>
  <?php if (!empty($backups)): ?>
    <h3 style="margin-top:24px;">Backup Employees</h3>
    <table>
      <thead><tr><th>Name</th><th>Shifts</th><th>Days Available</th><th>Date</th></tr></thead>
      <tbody>
        <?php foreach ($backups as $b): ?>
          <tr><td><?= htmlspecialchars($b['name'] ?? '') ?></td><td><?= htmlspecialchars($b['shifts'] ?? '') ?></td><td><?= htmlspecialchars($b['days'] ?? '') ?></td><td><?= htmlspecialchars($b['date'] ?? '') ?></td></tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</div>

<?php if ($isAdminView && $entry['status'] === 'locked'): ?>
<div class="card" style="max-width:600px;">
  <h3>🔓 Unlock Record (Super Admin only)</h3>
  <p style="font-size:12.5px;color:var(--text-muted);">This is a locked/approved record. Unlocking requires a reason and is permanently logged in the audit trail below.</p>
  <form method="POST" action="/projects/kpi/unlock" onsubmit="return confirm('Unlock this approved record for edits? This action is audited.');">
    <input type="hidden" name="id" value="<?= $entry['id'] ?>">
    <div class="field"><label>Unlock Reason (required)</label><input type="text" name="unlock_reason" required></div>
    <button type="submit" class="btn-danger">Unlock Record</button>
  </form>
</div>
<?php endif; ?>

<div class="card">
  <h3>Audit History</h3>
  <table>
    <thead><tr><th>When</th><th>Who</th><th>Action</th><th>Reason / Comment</th></tr></thead>
    <tbody>
      <?php foreach ($history as $h): ?>
        <tr>
          <td style="color:var(--text-muted);font-size:12px;"><?= htmlspecialchars($h['created_at']) ?></td>
          <td><?= htmlspecialchars($h['actor_name']) ?></td>
          <td><span class="badge badge-role-manager"><?= ucfirst(str_replace('_',' ',$h['action'])) ?></span></td>
          <td><?= htmlspecialchars($h['reason'] ?? '—') ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

<?php if ($isModalMode): ?>
<script>
// After a review action in modal, the controller redirects back to view?id=X&modal=1
// Notify parent to refresh the review queue
(function() {
  function autoResize() {
    try { window.parent.postMessage({type:'kpi-resize', height: document.body.scrollHeight}, '*'); } catch(e) {}
  }
  window.addEventListener('load', autoResize);
})();
</script>
</div></main></div></body></html>
<?php else: ?>
<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
<?php endif; ?>
