<?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 = 'Workspace Home';
require __DIR__ . '/../layout/workspace_header.php';
?>
<div class="topbar">
  <div>
    <h1>Welcome back, <?= htmlspecialchars(explode(' ', $user['name'])[0]) ?> 👋</h1>
    <div class="crumbs">Workspace Home</div>
  </div>
  <div class="user-chip"><span class="dot"></span> <?= htmlspecialchars($user['name']) ?></div>
</div>

<?php
// ── Pending actions panel (super admin / Cesar) ───────────────────────────
$pendingActions = [];
if ($user['is_super_admin'] || (($user['user_type'] ?? '') === 'manager' && ($user['username'] ?? '') === 'sara.lasher')) {
    try {
        $db2 = \App\Core\Database::connection();
        // Scheduling KPIs pending review
        $n = (int)$db2->query("SELECT COUNT(*) FROM kpi_scheduling_entries WHERE status='submitted'")->fetchColumn();
        if ($n > 0) $pendingActions[] = [
            'label' => $n . ' Scheduling KPI' . ($n===1?'':'s') . ' pending your review',
            'link'  => '/projects/kpi/review',
            'type'  => 'amber',
            'icon'  => '📊',
        ];
        // Cesar's KPIs pending review
        $cesarPending = \App\Models\CesarKpi::all(['status'=>'submitted']);
        if (!empty($cesarPending)) {
            $n2 = count($cesarPending);
            $pendingActions[] = [
                'label' => $n2 . ' Operations Manager KPI' . ($n2===1?'':'s') . ' pending your review',
                'link'  => '/projects/cesar-kpi/review',
                'type'  => 'amber',
                'icon'  => '📋',
            ];
        }
    } catch (\Throwable $e) {}
} elseif (($user['username'] ?? '') === 'cesar.saona') {
    try {
        $db2 = \App\Core\Database::connection();
        $reviewable = \App\Models\KpiScheduling::reviewableSubmitters($user['user_id']);
        if (!empty($reviewable)) {
            $ids = implode(',', array_map('intval', array_column($reviewable, 'id')));
            $n = (int)$db2->query("SELECT COUNT(*) FROM kpi_scheduling_entries WHERE status='submitted' AND submitter_id IN ($ids)")->fetchColumn();
            if ($n > 0) $pendingActions[] = [
                'label' => $n . ' KPI' . ($n===1?'':'s') . ' pending your review',
                'link'  => '/projects/kpi/review',
                'type'  => 'amber',
                'icon'  => '📊',
            ];
        }
        $returnedOwn = \App\Models\CesarKpi::all(['status'=>'returned']);
        if (!empty($returnedOwn)) {
            $pendingActions[] = [
                'label' => 'Your KPI was returned — edit and resubmit',
                'link'  => '/projects/cesar-kpi/entry?id=' . $returnedOwn[0]['id'],
                'type'  => 'red',
                'icon'  => '↩',
            ];
        }
    } catch (\Throwable $e) {}
} elseif (in_array($user['username'] ?? '', ['karan.kumar','harpreet.singh'], true)) {
    try {
        $db2 = \App\Core\Database::connection();
        $row = $db2->prepare("SELECT id FROM kpi_scheduling_entries WHERE status='returned' AND submitter_id=:uid ORDER BY week_ending DESC LIMIT 1");
        $row->execute(['uid' => $user['user_id']]);
        $ret = $row->fetch(\PDO::FETCH_ASSOC);
        if ($ret) $pendingActions[] = [
            'label' => 'Your KPI was returned — edit and resubmit',
            'link'  => '/projects/kpi/entry?id=' . $ret['id'],
            'type'  => 'red',
            'icon'  => '↩',
        ];
    } catch (\Throwable $e) {}
}

if (!empty($pendingActions)):
?>
<div style="margin-bottom:20px;">
  <div style="font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted);margin-bottom:10px;">Action Required</div>
  <div style="display:flex;flex-wrap:wrap;gap:10px;">
    <?php foreach ($pendingActions as $pa):
      $bg   = $pa['type']==='red' ? '#fef2f2' : '#fff8ed';
      $bdr  = $pa['type']==='red' ? '#fca5a5' : '#fcd34d';
      $col  = $pa['type']==='red' ? '#991b1b' : '#92400e';
      $dot  = $pa['type']==='red' ? '#dc2626' : '#f59e0b';
    ?>
    <a href="<?= htmlspecialchars($pa['link']) ?>"
       style="display:inline-flex;align-items:center;gap:10px;padding:12px 18px;
              background:<?= $bg ?>;border:1.5px solid <?= $bdr ?>;color:<?= $col ?>;
              border-radius:14px;text-decoration:none;font-size:13px;font-weight:700;
              box-shadow:0 2px 8px <?= $dot ?>22;transition:box-shadow .2s;"
       onmouseover="this.style.boxShadow='0 4px 16px <?= $dot ?>44'"
       onmouseout="this.style.boxShadow='0 2px 8px <?= $dot ?>22'">
      <span style="width:10px;height:10px;border-radius:50%;background:<?= $dot ?>;display:inline-block;
                   animation:pulse-dot 1.5s ease-in-out infinite;flex-shrink:0;"></span>
      <span><?= $pa['icon'] ?> <?= htmlspecialchars($pa['label']) ?></span>
      <span style="background:<?= $dot ?>;color:#fff;border-radius:20px;font-size:11px;padding:1px 8px;">→</span>
    </a>
    <?php endforeach; ?>
  </div>
</div>
<style>
@keyframes pulse-dot {
  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);}
}
</style>
<?php endif; ?>

<div class="card">
  <h3>Your Departments</h3>
  <?php if (empty($departments)): ?>
    <p style="color:var(--text-muted);font-size:13px;">You haven't been assigned to any departments yet. Contact your administrator.</p>
  <?php else: ?>
    <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:14px;">
      <?php foreach ($departments as $d): ?>
        <a href="/department?id=<?= $d['id'] ?>" style="display:block;border:1px solid var(--border);border-radius:12px;padding:16px;transition:box-shadow .15s;">
          <div style="font-weight:700;margin-bottom:4px;"><?= htmlspecialchars($d['name']) ?></div>
          <div style="color:var(--text-muted);font-size:12.5px;"><?= (int)$d['project_count'] ?> Project<?= (int)$d['project_count'] === 1 ? '' : 's' ?></div>
        </a>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>

<div style="display:grid;grid-template-columns:1.3fr 1fr;gap:22px;">
  <div class="card">
    <h3>Your Projects</h3>
    <?php if (empty($projects)): ?>
      <p style="color:var(--text-muted);font-size:13px;">No project assignments yet.</p>
    <?php else: ?>
      <table>
        <thead><tr><th>Project</th><th>Department</th><th>Status</th></tr></thead>
        <tbody>
          <?php foreach ($projects as $p): ?>
            <tr>
              <td><a href="/project?id=<?= $p['id'] ?>" style="font-weight:600;color:var(--blue-600);"><?= htmlspecialchars($p['name']) ?></a></td>
              <td><?= htmlspecialchars($p['department_name']) ?></td>
              <td><span class="badge badge-manager"><?= htmlspecialchars($p['status'] ?? 'active') ?></span></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>

  <div class="card">
    <h3>Recent Activity</h3>
    <?php if (empty($recentActivity)): ?>
      <p style="color:var(--text-muted);font-size:13px;">Nothing yet.</p>
    <?php else: ?>
      <?php foreach ($recentActivity as $a): ?>
        <div style="padding:10px 0;border-bottom:1px solid var(--border);font-size:13px;">
          <div style="font-weight:600;"><?= htmlspecialchars($a['description'] ?: $a['action']) ?></div>
          <div style="color:var(--text-muted);font-size:11.5px;"><?= htmlspecialchars($a['user_name'] ?? '') ?> · <?= fmtDate($a['created_at'], true) ?></div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<?php require __DIR__ . '/../layout/admin_footer.php'; ?>
