<?php
declare(strict_types=1);

session_start();
require_once 'config.php';

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

/*
 * FIX #1 (undercount): the old query only matched
 * LOWER(u.reporting_manager) = LOWER($manager_username).
 * Some employees have reporting_manager stored as the manager's
 * FULL NAME instead of their username, so they were silently
 * excluded. We now match on username OR full name, same as the
 * logic already used in dashboard_manager.php, and we build this
 * condition in ONE place so every query below (list, count,
 * division breakdown, export) stays consistent.
 *
 * FIX #2 (duplicate row): the LEFT JOINs to divisions/designations
 * had no GROUP BY, so if either lookup table had more than one
 * matching row for a given id, one employee could appear twice in
 * the results while pushing the real headcount display out of
 * sync. Added GROUP BY u.id everywhere to make each employee
 * appear exactly once no matter what the joined tables contain.
 */
$manager_id       = (string)$_SESSION['user_id'];
$manager_username = trim($_SESSION['username'] ?? '');

$mgr_stmt = $conn->prepare("SELECT CONCAT(COALESCE(first_name,''),' ',COALESCE(last_name,'')) AS name FROM users WHERE id = ?");
$mgr_stmt->bind_param("s", $manager_id);
$mgr_stmt->execute();
$manager_name = trim($mgr_stmt->get_result()->fetch_assoc()['name'] ?? '') ?: 'Manager';
$mgr_stmt->close();

// Reusable match condition: reporting_manager equals the manager's
// username OR their full name (case-insensitive, whitespace-safe).
const MGR_MATCH_SQL = "(LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)) OR LOWER(TRIM(u.reporting_manager)) = LOWER(TRIM(?)))";

/**
 * Binds the two manager-match params ($manager_username, $manager_name)
 * onto the front of whatever other params a given statement needs.
 */
function bindManagerMatch(mysqli_stmt $stmt, string $extraTypes, array $extraParams, string $manager_username, string $manager_name): void {
    $types  = "ss" . $extraTypes;
    $params = array_merge([$manager_username, $manager_name], $extraParams);
    $stmt->bind_param($types, ...$params);
}

// =============================================
//          EXPORT TO EXCEL
// =============================================
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    header("Content-Type: application/vnd.ms-excel; charset=utf-8");
    header("Content-Disposition: attachment; filename=team_" . date('Y-m-d') . ".xls");

    $search = trim($_GET['search'] ?? '');
    $search_param = '%' . $search . '%';

    $sql = "
        SELECT u.first_name, u.last_name, u.email, u.mobileno,
               d.division_name, des.designation_name
        FROM users u
        LEFT JOIN divisions d ON u.division_id = d.id
        LEFT JOIN designations des ON u.designation_id = des.id
        WHERE " . MGR_MATCH_SQL . " AND u.status = 'active'
        AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR
             u.mobileno LIKE ? OR d.division_name LIKE ? OR des.designation_name LIKE ?)
        GROUP BY u.id
        ORDER BY u.first_name ASC
    ";
    $stmt = $conn->prepare($sql);
    bindManagerMatch(
        $stmt, "ssssss",
        [$search_param, $search_param, $search_param, $search_param, $search_param, $search_param],
        $manager_username, $manager_name
    );
    $stmt->execute();
    $result = $stmt->get_result();

    echo "\xEF\xBB\xBF";
    echo "Name\tEmail\tMobile\tDivision\tDesignation\n";
    while ($row = $result->fetch_assoc()) {
        echo implode("\t", [
            $row['first_name'] . " " . $row['last_name'],
            $row['email'],
            $row['mobileno'] ?: '-',
            $row['division_name'] ?: 'N/A',
            $row['designation_name'] ?: 'N/A'
        ]) . "\n";
    }
    exit;
}

// =============================================
//          SEARCH
// =============================================
$search = trim($_GET['search'] ?? '');
$search_param = '%' . $search . '%';

$sql = "
    SELECT u.id, u.first_name, u.last_name, u.email, u.mobileno,
           d.division_name, des.designation_name
    FROM users u
    LEFT JOIN divisions d ON u.division_id = d.id
    LEFT JOIN designations des ON u.designation_id = des.id
    WHERE " . MGR_MATCH_SQL . " AND u.status = 'active'
    AND (u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ? OR
         u.mobileno LIKE ? OR d.division_name LIKE ? OR des.designation_name LIKE ?)
    GROUP BY u.id
    ORDER BY u.first_name ASC
";
$stmt = $conn->prepare($sql);
bindManagerMatch(
    $stmt, "ssssss",
    [$search_param, $search_param, $search_param, $search_param, $search_param, $search_param],
    $manager_username, $manager_name
);
$stmt->execute();
$result = $stmt->get_result();

// Total active team count (distinct employees, no join so no dup risk,
// but kept consistent with the same manager-match condition).
$count_sql = "SELECT COUNT(*) as total FROM (
                SELECT u.id FROM users u
                WHERE " . MGR_MATCH_SQL . " AND u.status='active'
                GROUP BY u.id
              ) t";
$count_stmt = $conn->prepare($count_sql);
$count_stmt->bind_param("ss", $manager_username, $manager_name);
$count_stmt->execute();
$total_team = $count_stmt->get_result()->fetch_assoc()['total'] ?? 0;
$count_stmt->close();

// Top division — GROUP BY u.id first (via subquery) so a duplicate
// divisions/designations row can't inflate a division's count.
$div_sql = "
    SELECT division_name, COUNT(*) as cnt FROM (
        SELECT u.id, d.division_name
        FROM users u
        LEFT JOIN divisions d ON u.division_id = d.id
        WHERE " . MGR_MATCH_SQL . " AND u.status='active'
        GROUP BY u.id
    ) per_user
    GROUP BY division_name
    ORDER BY cnt DESC
    LIMIT 1
";
$div_stmt = $conn->prepare($div_sql);
$div_stmt->bind_param("ss", $manager_username, $manager_name);
$div_stmt->execute();
$top_division = $div_stmt->get_result()->fetch_assoc();
$div_stmt->close();

function h($str) { return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>MPC · My Team</title>
<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=DM+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --ink:#0f172a;--ink-2:#334155;--muted:#64748b;--border:#e2e8f0;
  --surface:#ffffff;--bg:#f0f4f8;--sidebar-bg:#111827;--sidebar-w:260px;
  --accent:#4f46e5;--accent-2:#06b6d4;--green:#059669;--red:#dc2626;--amber:#d97706;
  --radius:14px;--radius-sm:8px;
  --shadow:0 1px 3px rgba(15,23,42,.06),0 4px 16px rgba(15,23,42,.07);
  --shadow-md:0 4px 6px rgba(15,23,42,.07),0 12px 32px rgba(15,23,42,.10);
  font-family:'DM Sans',system-ui,sans-serif;
}
html,body{height:100%}
body{background:var(--bg);color:var(--ink);font-size:14px;-webkit-font-smoothing:antialiased}

/* ─── LAYOUT ─── */
.layout{display:flex;min-height:100vh}
.sidebar{width:var(--sidebar-w);background:var(--sidebar-bg);position:fixed;inset:0 auto 0 0;z-index:200;display:flex;flex-direction:column;overflow-y:auto;transition:transform .3s ease;scrollbar-width:none}
.sidebar::-webkit-scrollbar{display:none}
.sidebar.hidden{transform:translateX(-100%)}
.sidebar-brand{padding:22px 18px 14px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.07);margin-bottom:6px}
.brand-logo{width:34px;height:34px;background:linear-gradient(135deg,var(--accent),var(--accent-2));border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;font-size:15px;flex-shrink:0}
.brand-name{font-size:14px;font-weight:700;color:#fff;letter-spacing:-.2px}
.brand-sub{font-size:9px;color:rgba(255,255,255,.35);letter-spacing:1.8px;text-transform:uppercase;margin-top:1px}
.nav-group-label{font-size:9px;font-weight:600;letter-spacing:1.8px;text-transform:uppercase;color:rgba(255,255,255,.25);padding:12px 18px 4px}
.nav-item{list-style:none}
.nav-link{display:flex;align-items:center;gap:9px;padding:8px 14px;margin:1px 8px;border-radius:8px;color:rgba(255,255,255,.6);text-decoration:none;font-size:13px;font-weight:500;transition:all .15s}
.nav-link:hover{background:rgba(255,255,255,.07);color:#fff}
.nav-link.active{background:rgba(79,70,229,.25);color:#a5b4fc}
.nav-link i{width:15px;text-align:center;font-size:12px;flex-shrink:0}
.nav-link.danger{color:#f87171}.nav-link.danger:hover{background:rgba(248,113,113,.1);color:#fca5a5}
.sidebar-footer{margin-top:auto;padding:10px 8px;border-top:1px solid rgba(255,255,255,.06)}

/* ─── CONTENT ─── */
.content{flex:1;margin-left:var(--sidebar-w);min-width:0;display:flex;flex-direction:column;transition:margin .3s ease}
.content.expanded{margin-left:0}

/* ─── TOPBAR ─── */
.topbar{height:58px;background:var(--surface);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:12px;padding:0 22px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--border)}
.hamburger-btn{width:34px;height:34px;border-radius:8px;border:1px solid var(--border);background:transparent;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink-2);font-size:14px;flex-shrink:0;transition:background .15s}
.hamburger-btn:hover{background:var(--bg)}
.topbar-breadcrumb{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted)}
.topbar-breadcrumb .current{color:var(--ink);font-weight:600;font-size:13px}
.topbar-spacer{flex:1}
.topbar-user{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--ink-2);font-weight:500}
.topbar-avatar{width:30px;height:30px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--accent-2));display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0}

/* ─── PAGE ─── */
.page{padding:22px;flex:1}
.page-header{margin-bottom:22px}
.page-title{font-size:20px;font-weight:700;color:var(--ink);letter-spacing:-.4px}
.page-subtitle{font-size:13px;color:var(--muted);margin-top:2px}

/* ─── STAT CARDS ─── */
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px;margin-bottom:22px}
.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:20px;box-shadow:var(--shadow);display:flex;align-items:flex-start;justify-content:space-between;gap:12px;position:relative;overflow:hidden;transition:transform .2s,box-shadow .2s}
.stat-card:hover{transform:translateY(-3px);box-shadow:var(--shadow-md)}
.stat-card::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:3px 3px 0 0}
.stat-card.blue::before{background:var(--accent)}
.stat-card.teal::before{background:var(--accent-2)}
.stat-card.amber::before{background:var(--amber)}
.stat-icon{width:42px;height:42px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:17px;flex-shrink:0}
.stat-icon.blue{background:#ede9fe;color:var(--accent)}
.stat-icon.teal{background:#cffafe;color:#0891b2}
.stat-icon.amber{background:#fef3c7;color:var(--amber)}
.stat-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--muted);margin-bottom:6px}
.stat-value{font-size:28px;font-weight:800;color:var(--ink);line-height:1;letter-spacing:-1px}
.stat-value.sm{font-size:16px;letter-spacing:-.3px;padding-top:4px}
.stat-sub{font-size:12px;color:var(--muted);margin-top:5px}

/* ─── DASH CARDS ─── */
.dash-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow);margin-bottom:18px}
.dash-card-header{padding:16px 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--border)}
.dash-card-title{font-size:14px;font-weight:700;color:var(--ink);display:flex;align-items:center;gap:7px}
.dash-card-title i{color:var(--accent);font-size:13px}
.dash-card-body{padding:16px 18px}

/* ─── SEARCH ─── */
.search-bar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}
.search-wrap{flex:1;min-width:240px;position:relative}
.search-wrap i{position:absolute;left:12px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:13px}
.search-input{width:100%;padding:9px 12px 9px 36px;border:1px solid var(--border);border-radius:9px;font-size:13px;color:var(--ink);background:var(--surface);outline:none;transition:border-color .2s,box-shadow .2s;font-family:inherit}
.search-input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(79,70,229,.1)}
.search-input::placeholder{color:var(--muted)}

/* ─── BUTTONS ─── */
.btn-custom{display:inline-flex;align-items:center;gap:7px;padding:8px 16px;border-radius:9px;font-size:13px;font-weight:600;border:none;cursor:pointer;transition:all .2s;text-decoration:none;font-family:inherit}
.btn-primary-c{background:var(--accent);color:#fff;box-shadow:0 2px 8px rgba(79,70,229,.25)}
.btn-primary-c:hover{background:#4338ca;color:#fff}
.btn-success-c{background:var(--green);color:#fff;box-shadow:0 2px 8px rgba(5,150,105,.2)}
.btn-success-c:hover{background:#047857;color:#fff}
.btn-outline-c{background:var(--surface);color:var(--ink-2);border:1px solid var(--border)}
.btn-outline-c:hover{border-color:var(--accent);color:var(--accent)}
.btn-sm-c{padding:6px 12px;font-size:12px;border-radius:7px}

/* ─── TABLE ─── */
.tbl-wrap{overflow-x:auto}
.dash-table{width:100%;border-collapse:collapse;font-size:13px}
.dash-table thead th{background:#f8fafc;color:var(--muted);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.6px;padding:10px 16px;text-align:left;white-space:nowrap;border-bottom:2px solid var(--border)}
.dash-table tbody td{padding:12px 16px;border-bottom:1px solid var(--border);color:var(--ink-2);vertical-align:middle}
.dash-table tbody tr:last-child td{border-bottom:none}
.dash-table tbody tr:hover td{background:#fafbfc}

/* ─── MEMBER CELL ─── */
.member-cell{display:flex;align-items:center;gap:12px}
.member-avatar{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:13px;color:#fff;flex-shrink:0}
.member-name{font-weight:600;color:var(--ink);font-size:13px}
.member-email{font-size:11px;color:var(--muted);font-family:'DM Mono',monospace;margin-top:2px}

/* ─── BADGES ─── */
.badge-custom{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
.badge-info   {background:#dbeafe;color:#1e40af}
.badge-purple {background:#ede9fe;color:#5b21b6}
.badge-orange {background:#fff7ed;color:#c2410c}
.badge-success{background:#d1fae5;color:#065f46}

/* ─── EMPTY STATE ─── */
.empty-state{text-align:center;padding:60px 20px}
.empty-state .es-icon{width:68px;height:68px;border-radius:50%;background:#ede9fe;display:flex;align-items:center;justify-content:center;font-size:28px;color:var(--accent);margin:0 auto 16px}
.empty-state h5{font-size:16px;font-weight:700;color:var(--ink-2)}
.empty-state p{font-size:13px;color:var(--muted);margin-top:5px}

/* ─── FOOTER ─── */
.page-footer{margin-top:20px;display:flex;align-items:center;justify-content:space-between;font-size:12px;color:var(--muted);flex-wrap:wrap;gap:8px;padding:0 2px}

/* ─── RESPONSIVE ─── */
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}.sidebar:not(.hidden){transform:none}
  .content{margin-left:0}.page{padding:14px}
  .stats-grid{grid-template-columns:repeat(2,1fr)}
}


/* ═══ MOBILE SIDEBAR FIX - SAME AS DASHBOARD_MANAGER ═══ */
.sidebar-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:290;backdrop-filter:blur(2px);opacity:0;transition:opacity .28s}
.sidebar-overlay.active{display:block;opacity:1}
@media(max-width:768px){
  body{overflow-x:hidden}
  .layout{min-width:0;width:100%}
  .sidebar{transform:translateX(-100%) !important;left:0;top:0;bottom:0;height:100vh;z-index:300}
  .sidebar.open{transform:translateX(0) !important}
  .content{margin-left:0 !important;width:100%;max-width:100%;min-width:0}
  .content.expanded{margin-left:0 !important}
  .topbar{padding:0 12px;gap:8px}
  .page{padding:13px !important}
  .topbar-user span{max-width:115px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
}
@media(min-width:769px){
  .sidebar{transform:translateX(0) !important}
  .sidebar-overlay.active{display:none !important;opacity:0 !important}
  .content{margin-left:var(--sidebar-w)}
}

</style>
</head>
<body>

<!-- OVERLAY -->
<div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

<div class="layout">

<!-- ═══ SIDEBAR ═══ -->
<nav class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-logo">M</div>
    <div>
      <div class="brand-name">MPC Portal</div>
      <div class="brand-sub">Manager</div>
    </div>
  </div>

  <div class="nav-group-label">Main</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="dashboard_manager.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a></li>
    <li class="nav-item"><a href="myteam.php" class="nav-link active"><i class="fas fa-sitemap"></i> My Team</a></li>
  </ul>

  <div class="nav-group-label">Work</div>
  <ul style="list-style:none;padding:0">
    <li class="nav-item"><a href="manager_daily_report.php" class="nav-link"><i class="fas fa-calendar-check"></i> Attendance</a></li>
    <li class="nav-item"><a href="daily_reports_manager.php" class="nav-link"><i class="fas fa-file-alt"></i> Daily Reports</a></li>
    <li class="nav-item"><a href="leave_dashboard_manager.php" class="nav-link"><i class="fas fa-umbrella-beach"></i> Team Leaves</a></li>
    <li class="nav-item"><a href="manager_hr_leave_apply.php" class="nav-link"><i class="fas fa-plane-departure"></i> Apply Leave</a></li>
    <li class="nav-item"><a href="tasks_manager.php" class="nav-link"><i class="fas fa-tasks"></i> Tasks</a></li>
    <li class="nav-item"><a href="manager_expenses.php" class="nav-link"><i class="fas fa-receipt"></i> Claims</a></li>
   <li class="nav-item"><a href="apply_grievance_manager.php" class="nav-link"><i class="fas fa-exclamation-circle"></i> Grievance</a></li>
  </ul>

  <div class="sidebar-footer">
    <ul style="list-style:none;padding:0">
      <li class="nav-item"><a href="logout.php" class="nav-link danger" onclick="return confirm('Are you sure you want to logout?')"><i class="fas fa-right-from-bracket"></i> Logout</a></li>
    </ul>
  </div>
</nav>

<!-- ═══ CONTENT ═══ -->
<div class="content" id="content">
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>Manager</span>
      <i class="fas fa-chevron-right" style="font-size:9px;margin:0 2px"></i>
      <span class="current">My Team</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?= strtoupper(substr($manager_name, 0, 1)) ?></div>
      <span><?= h(explode(' ', $manager_name)[0]) ?></span>
    </div>
  </div>

  <div class="page">
    <div class="page-header">
      <div class="page-title">My Team</div>
      <div class="page-subtitle"><?= date('l, F j, Y') ?> · Manage and view active direct reports</div>
    </div>

    <!-- ─── STAT CARDS ─── -->
    <div class="stats-grid">
      <div class="stat-card blue">
        <div>
          <div class="stat-label">Total Members</div>
          <div class="stat-value"><?= number_format((int)$total_team) ?></div>
          <div class="stat-sub" style="display:flex;align-items:center;gap:5px;margin-top:8px">
            <span style="display:inline-flex;align-items:center;gap:4px;background:#d1fae5;color:#065f46;padding:2px 8px;border-radius:20px;font-size:11px;font-weight:700"><i class="fas fa-circle" style="font-size:6px"></i>Active</span>
          </div>
        </div>
        <div class="stat-icon blue"><i class="fas fa-users"></i></div>
      </div>

      <div class="stat-card teal">
        <div>
          <div class="stat-label">Search Results</div>
          <div class="stat-value"><?= $result->num_rows ?></div>
          <div class="stat-sub"><?= $search ? 'Matching "'.h($search).'"' : 'All members shown' ?></div>
        </div>
        <div class="stat-icon teal"><i class="fas fa-search"></i></div>
      </div>

      <div class="stat-card amber">
        <div>
          <div class="stat-label">Top Division</div>
          <div class="stat-value sm"><?= h($top_division['division_name'] ?? '—') ?></div>
          <div class="stat-sub"><?= ($top_division['cnt'] ?? 0) ?> member<?= ($top_division['cnt'] ?? 0) != 1 ? 's' : '' ?></div>
        </div>
        <div class="stat-icon amber"><i class="fas fa-building"></i></div>
      </div>
    </div>

    <!-- ─── TEAM TABLE ─── -->
    <div class="dash-card">
      <div class="dash-card-header">
        <div class="dash-card-title"><i class="fas fa-users"></i> Team Members</div>
        <div style="display:flex;gap:8px;align-items:center">
          <span class="badge-custom badge-info"><?= $result->num_rows ?> record<?= $result->num_rows !== 1 ? 's' : '' ?></span>
          <a href="?export=excel<?= $search ? '&search='.urlencode($search) : '' ?>"
             class="btn-custom btn-success-c btn-sm-c">
            <i class="fas fa-download"></i> Export Excel
          </a>
        </div>
      </div>
      <div class="dash-card-body" style="padding:0">

        <!-- Search Bar -->
        <div style="padding:14px 18px;border-bottom:1px solid var(--border)">
          <form method="GET" class="search-bar">
            <div class="search-wrap">
              <i class="fas fa-search"></i>
              <input type="text" name="search" class="search-input"
                     placeholder="Search name, email, mobile, division…"
                     value="<?= h($search) ?>">
            </div>
            <button type="submit" class="btn-custom btn-primary-c">
              <i class="fas fa-search"></i> Search
            </button>
            <?php if ($search): ?>
              <a href="myteam.php" class="btn-custom btn-outline-c">
                <i class="fas fa-times"></i> Clear
              </a>
            <?php endif; ?>
          </form>
        </div>

        <div class="tbl-wrap">
          <?php
          $palette = ['#4f46e5','#0891b2','#7c3aed','#d97706','#059669','#db2777','#0891b2','#c2410c'];
          $pi = 0;
          ?>
          <table class="dash-table">
            <thead>
              <tr>
                <th>Member</th>
                <th>Mobile</th>
                <th>Division</th>
                <th>Designation</th>
              </tr>
            </thead>
            <tbody>
            <?php if ($result->num_rows > 0):
              while ($row = $result->fetch_assoc()):
                $initials = strtoupper(substr($row['first_name'],0,1).substr($row['last_name'],0,1));
                $color = $palette[$pi % count($palette)];
                $pi++;
            ?>
              <tr>
                <td>
                  <div class="member-cell">
                    <div class="member-avatar" style="background:<?= $color ?>"><?= $initials ?></div>
                    <div>
                      <div class="member-name"><?= h($row['first_name'].' '.$row['last_name']) ?></div>
                      <div class="member-email"><?= h($row['email']) ?></div>
                    </div>
                  </div>
                </td>
                <td style="font-family:'DM Mono',monospace;font-size:12px;color:var(--ink-2)"><?= h($row['mobileno'] ?: '—') ?></td>
                <td>
                  <?php if ($row['division_name']): ?>
                    <span class="badge-custom badge-purple"><?= h($row['division_name']) ?></span>
                  <?php else: ?><span style="color:var(--muted);font-size:12px">N/A</span><?php endif; ?>
                </td>
                <td>
                  <?php if ($row['designation_name']): ?>
                    <span class="badge-custom badge-orange"><?= h($row['designation_name']) ?></span>
                  <?php else: ?><span style="color:var(--muted);font-size:12px">N/A</span><?php endif; ?>
                </td>
              </tr>
            <?php endwhile; else: ?>
              <tr>
                <td colspan="4" style="padding:0;border:none">
                  <div class="empty-state">
                    <div class="es-icon">
                      <i class="fas fa-<?= $search ? 'search' : 'users' ?>"></i>
                    </div>
                    <h5><?= $search ? 'No results found' : 'No team members yet' ?></h5>
                    <p><?= $search
                        ? 'No one matches "'.h($search).'". Try a different keyword.'
                        : 'Active direct reports will appear here once assigned.' ?></p>
                  </div>
                </td>
              </tr>
            <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div class="page-footer">
      <span>Manager Portal &nbsp;·&nbsp; Team View</span>
      <span><?= number_format((int)$total_team) ?> active member<?= $total_team != 1 ? 's' : '' ?> &nbsp;·&nbsp; <?= date('d M Y, h:i A') ?></span>
    </div>

  </div><!-- /page -->
</div><!-- /content -->
</div><!-- /layout -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (!sb || !ov) return;
  const isOpen = sb.classList.contains('open');
  sb.classList.toggle('open', !isOpen);
  ov.classList.toggle('active', !isOpen);
}
function closeSidebar() {
  const sb = document.getElementById('sidebar');
  const ov = document.getElementById('sidebarOverlay');
  if (sb) sb.classList.remove('open');
  if (ov) ov.classList.remove('active');
}
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') closeSidebar();
});
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('#sidebar .nav-link').forEach(function(a) {
    a.addEventListener('click', function() {
      if (window.innerWidth <= 768) closeSidebar();
    });
  });
});
</script>
</body>
</html>