<?php
/** @var array $user, string $pageTitle, string $crumbs */

// ── Per-user notification computation ─────────────────────────────────────
$_notifs = [];

if (!empty($user)) {
    $username     = $user['username'] ?? '';
    $isSuperAdmin = (bool)($user['is_super_admin'] ?? false);
    // sara.lasher has full KPI oversight equivalent to super admin for notification purposes
    $isSaraManager = ($user['user_type'] ?? '') === 'manager' && ($user['username'] ?? '') === 'sara.lasher';
    $hasFullKpiAccess = $isSuperAdmin || $isSaraManager;
    $userType     = $user['user_type'] ?? '';
    $userId       = (int)($user['user_id'] ?? 0);

    try { $db = \App\Core\Database::connection(); } catch (\Throwable $e) { $db = null; }

    // ── Karan / Harpreet: returned own KPI (red) + show latest review outcome ─
    if (in_array($username, ['karan.kumar', 'harpreet.singh'], true) && $db) {
        try {
            $stmt = $db->prepare(
                "SELECT id, week_ending, review_score, review_comment, reviewer_name, status
                 FROM kpi_scheduling_entries
                 WHERE status IN ('returned','locked') AND submitter_id=:uid
                 ORDER BY week_ending DESC LIMIT 2"
            );
            $stmt->execute(['uid' => $userId]);
            $recentReviewed = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            foreach ($recentReviewed as $row) {
                if ($row['status'] === 'returned') {
                    $_notifs[] = ['count'=>1,'label'=>'Your KPI was returned — click to edit',
                                  'link'=>'/projects/kpi/entry?id='.$row['id'],'type'=>'red'];
                } elseif ($row['status'] === 'locked' && ($row['review_score'] ?? 0)) {
                    $scoreText = $row['review_score'] . '/10';
                    $_notifs[] = ['count'=>0,'label'=>'KPI reviewed: '.$scoreText.' — '.date('m/d/Y',strtotime($row['week_ending'])).' — click to view',
                                  'link'=>'/projects/kpi/view?id='.$row['id'],'type'=>'amber'];
                    break;
                }
            }
        } catch (\Throwable $e) {}

        // ── Review comment / reply awaiting the submitter's response ────────
        // Additive chip: the existing "KPI reviewed: x/10" chip above is
        // untouched. This one specifically tells the submitter that a review
        // comment was left for them and links straight to the reply box.
        try {
            $stmt = $db->prepare(
                "SELECT id, week_ending, reviewer_name, review_comment
                   FROM kpi_scheduling_entries
                  WHERE submitter_id = :uid
                    AND status IN ('reviewed','locked')
                    AND review_comment IS NOT NULL AND review_comment <> ''
               ORDER BY week_ending DESC LIMIT 1"
            );
            $stmt->execute(['uid' => $userId]);
            $withComment = $stmt->fetch(\PDO::FETCH_ASSOC);
            if ($withComment) {
                $lastMine  = \App\Models\KpiDiscussion::latestByRole((int)$withComment['id'], 'submitter');
                $lastTheir = \App\Models\KpiDiscussion::latestByRole((int)$withComment['id'], 'reviewer');
                $needsMe   = !$lastMine
                    || ($lastTheir && strtotime($lastTheir['created_at']) > strtotime($lastMine['created_at']));
                if ($needsMe) {
                    $who = $withComment['reviewer_name'] ?: 'Your reviewer';
                    // Version the key on the newest reviewer activity, so a NEW
                    // comment later produces a new key and the chip reappears.
                    $ver = $lastTheir['id'] ?? 'root';
                    $_notifs[] = ['count'=>0,
                                  'label'=>$who.' added a review comment — click to respond',
                                  'link'=>'/projects/kpi/view?id='.$withComment['id'].'#kpi-discussion',
                                  'key'=>'cmt:'.(int)$withComment['id'].':'.$ver,
                                  'type'=>'amber'];
                }
            }
        } catch (\Throwable $e) {}
    }

    // ── Cesar: (a) own returned KPI, (b) scheduling team KPIs pending review ─
    if ($username === 'cesar.saona') {
        // (a) Own returned KPI
        try {
            $returnedOwn = \App\Models\CesarKpi::all(['status'=>'returned']);
            if (!empty($returnedOwn)) {
                $_notifs[] = ['count'=>count($returnedOwn),
                              'label'=>'Your KPI was returned — click to edit',
                              'link'=>'/projects/cesar-kpi/entry?id='.$returnedOwn[0]['id'],
                              'type'=>'red'];
            }
        } catch (\Throwable $e) {}

        // (a2) Sara reviewed/approved/scored Cesar's own KPI — show the latest
        try {
            $latestReviewed = \App\Models\CesarKpi::all(['status'=>'locked']);
            foreach ($latestReviewed as $row) {
                if ($row['review_score'] ?? 0) {
                    $_notifs[] = ['count'=>0,
                                  'label'=>'Your KPI reviewed: '.$row['review_score'].'/10 — '.date('m/d/Y',strtotime($row['week_ending'])).' — click to view',
                                  'link'=>'/projects/cesar-kpi/view?id='.$row['id'],
                                  'type'=>'amber'];
                    break;
                }
            }
        } catch (\Throwable $e) {}

        // (b) Scheduling KPIs submitted for Cesar's review (from direct reports)
        if ($db) {
            try {
                $reviewable = \App\Models\KpiScheduling::reviewableSubmitters($userId);
                if (!empty($reviewable)) {
                    $ids = implode(',', array_map('intval', array_column($reviewable, 'id')));
                    $n = (int)$db->query(
                        "SELECT COUNT(*) FROM kpi_scheduling_entries
                         WHERE status='submitted' AND submitter_id IN ($ids)"
                    )->fetchColumn();
                    if ($n > 0) {
                        $_notifs[] = ['count'=>$n,
                                      'label'=>$n.' KPI'.($n===1?'':'s').' pending your review',
                                      'link'=>'/projects/kpi/review','type'=>'amber'];
                    }

                    // (c) Team members who have responded to a review comment
                    // and are waiting on Cesar. Additive — the chip above is
                    // unchanged.
                    $entryIds = $db->query(
                        "SELECT id FROM kpi_scheduling_entries WHERE submitter_id IN ($ids)"
                    )->fetchAll(\PDO::FETCH_COLUMN);
                    $awaitingIds = \App\Models\KpiDiscussion::entryIdsAwaitingResponse(
                        array_map('intval', $entryIds), 'submitter'
                    );
                    $awaiting = count($awaitingIds);
                    // Accounts KPI (Jatinder) responses awaiting Cesar's reply.
                    try {
                        $accIds = $db->query("SELECT id FROM kpi_accounts_entries")->fetchAll(\PDO::FETCH_COLUMN);
                        $accAwait = \App\Models\KpiDiscussion::entryIdsAwaitingResponse(
                            array_map('intval', $accIds), 'submitter', 'accounts'
                        );
                        if (!empty($accAwait)) {
                            $na = count($accAwait);
                            $_notifs[] = ['count'=>$na,
                                          'label'=>$na.' Accounts KPI response'.($na===1?'':'s').' awaiting your reply',
                                          'link'=>'/projects/jatinder-kpi/view?id='.$accAwait[0].'#kpi-discussion',
                                          'key'=>'acc-resp:'.implode('-', $accAwait),
                                          'type'=>'amber'];
                        }
                    } catch (\Throwable $e) {}

                    if ($awaiting > 0) {
                        // Land on the review queue with the relevant row
                        // highlighted, so it is clear which record the
                        // notification refers to. With several waiting, the
                        // newest one is highlighted.
                        $awaitLink = '/projects/kpi/review?highlight=' . $awaitingIds[0];
                        // Key on the exact set of waiting records, so a new
                        // response from anyone brings the chip back.
                        $_notifs[] = ['count'=>$awaiting,
                                      'label'=>$awaiting.' KPI response'.($awaiting===1?'':'s').' awaiting your reply',
                                      'link'=>$awaitLink,
                                      'key'=>'resp:'.implode('-', $awaitingIds),
                                      'type'=>'amber'];
                    }
                }
            } catch (\Throwable $e) {}
        }
    }

    // ── Jatinder: returned KPI + latest reviewed notification ────────────────
    if ($username === 'jatinder.kumar') {
        try {
            $retStmt = $db->prepare(
                "SELECT id, week_ending FROM kpi_accounts_entries
                 WHERE status='returned' AND submitter_id=:uid ORDER BY week_ending DESC LIMIT 1"
            );
            $retStmt->execute(['uid' => $userId]);
            $ret = $retStmt->fetch(\PDO::FETCH_ASSOC);
            if ($ret) {
                $_notifs[] = ['count'=>1,'label'=>'Your KPI was returned — click to edit',
                              'link'=>'/projects/jatinder-kpi/entry?id='.$ret['id'],'type'=>'red'];
            }
        } catch (\Throwable $e) {}
        try {
            $revStmt = $db->prepare(
                "SELECT id, week_ending, review_score FROM kpi_accounts_entries
                 WHERE status='locked' AND submitter_id=:uid AND review_score IS NOT NULL
                 ORDER BY week_ending DESC LIMIT 1"
            );
            $revStmt->execute(['uid' => $userId]);
            $rev = $revStmt->fetch(\PDO::FETCH_ASSOC);
            if ($rev) {
                $_notifs[] = ['count'=>0,'label'=>'KPI reviewed: '.$rev['review_score'].'/10 — '.date('m/d/Y',strtotime($rev['week_ending'])).' — click to view',
                              'link'=>'/projects/jatinder-kpi/view?id='.$rev['id'],'type'=>'amber'];
            }
        } catch (\Throwable $e) {}

        // ── Review comment awaiting Jatinder's response ──────────────────
        // Additive chip: mirrors the Scheduling KPI behaviour. Existing
        // chips above are untouched.
        try {
            $jStmt = $db->prepare(
                "SELECT id, week_ending, reviewer_name, review_comment
                   FROM kpi_accounts_entries
                  WHERE submitter_id = :uid
                    AND status IN ('reviewed','locked','approved')
                    AND review_comment IS NOT NULL AND review_comment <> ''
               ORDER BY week_ending DESC LIMIT 1"
            );
            $jStmt->execute(['uid' => $userId]);
            $jRow = $jStmt->fetch(\PDO::FETCH_ASSOC);
            if ($jRow) {
                $jMine  = \App\Models\KpiDiscussion::latestByRole((int)$jRow['id'], 'submitter', 'accounts');
                $jTheir = \App\Models\KpiDiscussion::latestByRole((int)$jRow['id'], 'reviewer', 'accounts');
                $jNeeds = !$jMine || ($jTheir && strtotime($jTheir['created_at']) > strtotime($jMine['created_at']));
                if ($jNeeds) {
                    $jWho = $jRow['reviewer_name'] ?: 'Your reviewer';
                    $_notifs[] = ['count'=>0,
                                  'label'=>$jWho.' added a review comment — click to respond',
                                  'link'=>'/projects/jatinder-kpi/view?id='.$jRow['id'].'#kpi-discussion',
                                  'key'=>'acc-cmt:'.(int)$jRow['id'].':'.($jTheir['id'] ?? 'root'),
                                  'type'=>'amber'];
                }
            }
        } catch (\Throwable $e) {}
    }

    // ── Cesar: Jatinder KPI pending review ───────────────────────────────────
    if ($username === 'cesar.saona' && $db) {
        try {
            $jatManagerRow = $db->prepare("SELECT id FROM managers WHERE username='jatinder.kumar' LIMIT 1");
            $jatManagerRow->execute();
            $jatRow = $jatManagerRow->fetch(\PDO::FETCH_ASSOC);
            if ($jatRow) {
                $n = (int)$db->query(
                    "SELECT COUNT(*) FROM kpi_accounts_entries WHERE status='submitted'"
                )->fetchColumn();
                if ($n > 0) {
                    $_notifs[] = ['count'=>$n,
                                  'label'=>$n.' Accounts KPI'.($n===1?'':'s').' pending your review',
                                  'link'=>'/projects/jatinder-kpi/review','type'=>'amber'];
                }
            }
        } catch (\Throwable $e) {}
    }

    // ── Sara / Super Admin: Jatinder KPIs + Cesar KPIs + Scheduling KPIs ────
    if ($hasFullKpiAccess) {
        // Jatinder (Accounts) KPIs pending
        if ($db) {
            try {
                $n = (int)$db->query(
                    "SELECT COUNT(*) FROM kpi_accounts_entries WHERE status='submitted'"
                )->fetchColumn();
                if ($n > 0) {
                    $_notifs[] = ['count'=>$n,
                                  'label'=>$n.' Accounts KPI'.($n===1?'':'s').' pending review',
                                  'link'=>'/projects/jatinder-kpi/review','type'=>'amber'];
                }
            } catch (\Throwable $e) {}
        }
        // Cesar's submitted Operations Manager KPIs
        try {
            $cesarPending = \App\Models\CesarKpi::all(['status'=>'submitted']);
            if (!empty($cesarPending)) {
                $n = count($cesarPending);
                $_notifs[] = ['count'=>$n,
                              'label'=>$n.' Operations Manager KPI'.($n===1?'':'s').' pending review',
                              'link'=>'/projects/cesar-kpi/review','type'=>'amber'];
            }
        } catch (\Throwable $e) {}

        // Scheduling KPIs (Karan/Harpreet) submitted — Sara can see all
        if ($db) {
            try {
                $n = (int)$db->query(
                    "SELECT COUNT(*) FROM kpi_scheduling_entries WHERE status='submitted'"
                )->fetchColumn();
                if ($n > 0) {
                    $_notifs[] = ['count'=>$n,
                                  'label'=>$n.' Scheduling KPI'.($n===1?'':'s').' pending review',
                                  'link'=>'/projects/kpi/review','type'=>'amber'];
                }
            } catch (\Throwable $e) {}
        }
    }

    // ── Other managers: scheduling KPIs from their direct reports ────────
    if ($userType === 'manager' && !$hasFullKpiAccess
        && !in_array($username, ['karan.kumar','harpreet.singh','cesar.saona'], true)
        && $db) {
        try {
            $reviewable = \App\Models\KpiScheduling::reviewableSubmitters($userId);
            if (!empty($reviewable)) {
                $ids = implode(',', array_map('intval', array_column($reviewable, 'id')));
                $n = (int)$db->query(
                    "SELECT COUNT(*) FROM kpi_scheduling_entries
                     WHERE status='submitted' AND submitter_id IN ($ids)"
                )->fetchColumn();
                if ($n > 0) {
                    $_notifs[] = ['count'=>$n,
                                  'label'=>$n.' KPI'.($n===1?'':'s').' pending your review',
                                  'link'=>'/projects/kpi/review','type'=>'amber'];
                }
            }
        } catch (\Throwable $e) {}
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= isset($pageTitle) ? htmlspecialchars($pageTitle) . ' · ' : '' ?>Hammerhead Workspace</title>
<link rel="stylesheet" href="/assets/css/app.css?v=<?= defined('ASSET_VERSION') ? ASSET_VERSION : time() ?>">
<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>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script>
// Apply Flatpickr to all date inputs after DOM loads — enforces MM/DD/YYYY everywhere
document.addEventListener('DOMContentLoaded', function() {
  function applyFP(el) {
    if (el._fp) return;
    var savedVal = el.getAttribute('data-saved') || el.value || '';
    var defDate = null;
    if (savedVal) {
      var p = savedVal.split('-');
      if (p.length === 3) defDate = new Date(p[0], p[1]-1, p[2]);
    }
    el.value = ''; // Always start blank visually
    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);
});
  });
});
</script>
<style>
.notif-chip {
  display:inline-flex;align-items:center;gap:8px;
  border-radius:30px;padding:7px 14px 7px 10px;
  font-size:13px;font-weight:700;
  text-decoration:none;white-space:nowrap;cursor:pointer;
  transition:box-shadow .2s;
}
.notif-chip.amber {
  background:#fff3cd;border:1.5px solid #f59e0b;color:#92400e;
  box-shadow:0 0 0 3px rgba(245,158,11,0.15);
}
.notif-chip.amber:hover { box-shadow:0 0 0 5px rgba(245,158,11,0.25); }
.notif-chip.red {
  background:#fef2f2;border:1.5px solid #dc2626;color:#991b1b;
  box-shadow:0 0 0 3px rgba(220,38,38,0.12);
}
.notif-chip.red:hover { box-shadow:0 0 0 5px rgba(220,38,38,0.22); }
.notif-dot-pulse {
  width:10px;height:10px;border-radius:50%;flex-shrink:0;
}
.amber .notif-dot-pulse {
  background:#f59e0b;
  animation:pulse-amber 1.5s ease-in-out infinite;
}
.red .notif-dot-pulse {
  background:#dc2626;
  animation:pulse-red 1.5s ease-in-out infinite;
}
@keyframes pulse-amber {
  0%,100% { box-shadow:0 0 0 0 rgba(245,158,11,0.7); }
  50%      { box-shadow:0 0 0 6px rgba(245,158,11,0); }
}
@keyframes pulse-red {
  0%,100% { box-shadow:0 0 0 0 rgba(220,38,38,0.7); }
  50%      { box-shadow:0 0 0 6px rgba(220,38,38,0); }
}
.notif-badge {
  color:#fff;border-radius:20px;font-size:11px;padding:1px 8px;margin-left:2px;
}
.amber .notif-badge { background:#f59e0b; }
.red   .notif-badge { background:#dc2626; }
/* Highlight rows needing action in tables */
tr.needs-action { background:rgba(245,158,11,0.07) !important; }
tr.needs-action td:first-child { border-left:3px solid #f59e0b; }
tr.needs-action-red { background:rgba(220,38,38,0.06) !important; }
tr.needs-action-red td:first-child { border-left:3px solid #dc2626; }
</style>
</head>
<body>
<div class="admin-shell">
  <aside class="sidebar">
    <div class="brand">
      <span class="logo-chip"><img src="/assets/img/hh_logo.png" alt="Hammerhead"></span>
      <span>HH WORKSPACE</span>
    </div>
    <nav>
      <a href="/workspace" class="<?= ($active ?? '') === 'home' ? 'active' : '' ?>">🏠 Workspace Home</a>
      <a href="/profile" class="<?= ($active ?? '') === 'profile' ? 'active' : '' ?>">🔐 My Profile &amp; Security</a>
    </nav>
    <div class="profile-block">
      <div class="role-badge">Logged in as<br><strong style="color:#fff;"><?= htmlspecialchars($user['name']) ?></strong><br><?= htmlspecialchars($user['roles'][0]['name'] ?? ucfirst($user['user_type'])) ?></div>
      <a href="/logout" class="logout-btn">🚪 Logout</a>
    </div>
  </aside>
  <main class="main"><div class="main-inner">
<?php if (\App\Core\Auth::isImpersonating()):
  $impInfo = \App\Core\Auth::impersonatorInfo(); ?>
<div style="background:#1e3a8a;color:#fff;padding:10px 20px;display:flex;align-items:center;
            justify-content:space-between;font-size:13px;font-weight:600;
            border-radius:12px;margin-bottom:12px;gap:12px;">
  <span style="display:flex;align-items:center;gap:8px;">
    <span style="background:#facc15;color:#1e3a8a;border-radius:20px;padding:2px 10px;font-size:11px;font-weight:800;letter-spacing:.06em;">
      🔧 TEST / VIEW MODE
    </span>
    Viewing as <strong style="color:#facc15;"><?= htmlspecialchars($user['name']) ?></strong>
    — all write actions are disabled
  </span>
  <a href="/dev/impersonate/stop"
     style="background:#fff;color:#1e3a8a;border-radius:8px;padding:5px 14px;
            text-decoration:none;font-size:12px;font-weight:800;white-space:nowrap;">
    ✕ Exit View Mode
  </a>
</div>
<?php endif; ?>
<?php
// ── Employee Onboarding: real notifications from the shared table ─────────
// Additive only — does not touch any KPI notification logic above.
try {
    $_onbDb = \App\Core\Database::connection();
    $_onbStmt = $_onbDb->prepare(
        "SELECT id, title, message, link FROM notifications
         WHERE user_type = :t AND user_id = :id AND is_read = 0 AND link LIKE '/onboarding%'
         ORDER BY created_at DESC LIMIT 5"
    );
    $_onbStmt->execute(['t' => $user['user_type'] ?? '', 'id' => $user['user_id'] ?? 0]);
    $_onbRows = $_onbStmt->fetchAll();
    if ($_onbRows) {
        $_notifs[] = [
            'count' => count($_onbRows),
            'label' => (count($_onbRows) === 1 ? $_onbRows[0]['message'] : count($_onbRows) . ' onboarding updates — click to review') . ' — click to view',
            'link' => '/onboarding/notif-open?ids=' . implode(',', array_map(fn($r) => (int)$r['id'], $_onbRows)) . '&to=' . urlencode($_onbRows[0]['link']),
            'type' => 'amber',
        ];
    }
} catch (\Throwable $_onbErr) { /* never break the header if this fails */ }
?>

<?php
// ── Hide chips this user has already opened ───────────────────────────────
// The chips are derived from live KPI state and had no read/unread concept,
// so they persisted after being viewed. Each chip gets a versioned key; once
// the user clicks through, that key is recorded and the chip is filtered out
// here. Genuinely new activity produces a different key, so the chip returns.
//
// The onboarding chip is left exactly as it was — it already has its own
// read-tracking via the notifications table.
if (!empty($_notifs) && !empty($user)) {
    $_seenType = !empty($user['is_super_admin']) ? 'superadmin' : ($user['user_type'] ?? '');
    $_seenKeys = \App\Models\KpiNotifSeen::seenKeys($_seenType, (int)($user['user_id'] ?? 0));

    $_visible = [];
    foreach ($_notifs as $_n) {
        $_isOnboarding = str_starts_with($_n['link'] ?? '', '/onboarding');
        if ($_isOnboarding) { $_visible[] = $_n; continue; }

        // Fall back to a key derived from the chip itself. Counts and scores
        // are part of the label, so a change in either yields a new key.
        $_key = $_n['key'] ?? ('auto:' . md5(($_n['label'] ?? '') . '|' . ($_n['link'] ?? '')));

        if (\App\Models\KpiNotifSeen::isSeen($_seenKeys, $_key)) continue;

        $_n['key'] = $_key;
        $_n['link'] = '/projects/kpi/notif-open?key=' . rawurlencode($_key)
                    . '&to=' . rawurlencode($_n['link'] ?? '/workspace');
        $_visible[] = $_n;
    }
    $_notifs = $_visible;
}
?>
<?php if (!empty($_notifs)): ?>
<div style="display:flex;flex-wrap:wrap;gap:8px;padding:0 0 14px;">
  <?php foreach ($_notifs as $_n): ?>
  <a href="<?= htmlspecialchars($_n['link']) ?>" class="notif-chip <?= $_n['type'] ?>">
    <span class="notif-dot-pulse"></span>
    <?= htmlspecialchars($_n['label']) ?>
    <span class="notif-badge"><?= (int)$_n['count'] ?></span>
  </a>
  <?php endforeach; ?>
</div>
<?php endif; ?>
