<?php
session_start();
require_once 'config.php';

/* ================= AUTH ================= */
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['md','superadmin'])) {
    header("Location: index.php");
    exit;
}

/* ================= HELPERS ================= */
function h($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function keyName($v){
    return mb_strtolower(trim(preg_replace('/\s+/', ' ', (string)$v)));
}

/* ================= CONFIG ================= */
$base_url     = 'https://pupa.mybelief.in/uploads';
$level_order  = ['L1','L2','L3','L4','L5'];
$username     = $_SESSION['username'] ?? '';

$valid_locations = ['karur','trichy','madurai','coimbatore','tirunelveli','salem'];
$location_labels = [
    'karur'       => 'Karur (HO)',
    'trichy'      => 'Trichy',
    'madurai'     => 'Madurai',
    'coimbatore'  => 'Coimbatore',
    'tirunelveli' => 'Tirunelveli',
    'salem'       => 'Salem',
];

/* ================= FETCH USERS ================= */
$q = $conn->query("
    SELECT first_name, last_name, designation, division, level,
           reporting_manager, photo, role,
           COALESCE(company,'')        AS company,
           COALESCE(dob,'')            AS dob,
           COALESCE(date_of_joining,'') AS date_of_joining,
           COALESCE(location,'karur')  AS location
    FROM users
    WHERE status='active' AND role!='superadmin'
");

$employees = [];
$md        = null;

while ($r = $q->fetch_assoc()) {
    $r['full_name'] = trim(($r['first_name'] ?? '').' '.($r['last_name'] ?? ''));
    $r['level']     = strtoupper(trim($r['level'] ?? 'L5'));
    $loc_key        = strtolower(trim($r['location'] ?? ''));
    if ($loc_key === '' || $loc_key === 'pending') $loc_key = 'karur';
    $r['location']  = $loc_key;

    if (strtolower($r['role']) === 'md') {
        $md = $r;
        continue;
    }
    $employees[] = $r;
}

if (!$md) {
    $md = [
        'full_name'       => 'Managing Director',
        'first_name'      => 'Managing',
        'last_name'       => 'Director',
        'designation'     => 'Managing Director',
        'level'           => 'L1',
        'location'        => 'karur',
        'photo'           => '',
        'company'         => '',
        'dob'             => '',
        'date_of_joining' => '',
        'division'        => 'Leadership',
        'role'            => 'md',
    ];
}

/* ================= STRENGTH MATRIX ================= */
$loc_keys_cap  = ['Karur','Trichy','Madurai','Coimbatore','Tirunelveli','Salem'];
$strength_tpl  = array_fill_keys(array_merge($loc_keys_cap, ['Total']), 0);
$employee_strength = [];
foreach (array_merge($level_order, ['Total']) as $lv) {
    $employee_strength[$lv] = $strength_tpl;
}

foreach (array_merge([$md], $employees) as $emp) {
    $lv  = strtoupper(trim($emp['level'] ?? ''));
    $lk  = $emp['location'] ?? 'karur';
    if (!in_array($lv, $level_order, true) || !in_array($lk, $valid_locations, true)) continue;
    $loc_strength_key = match($lk) {
        'karur'       => 'Karur',
        'trichy'      => 'Trichy',
        'madurai'     => 'Madurai',
        'coimbatore'  => 'Coimbatore',
        'tirunelveli' => 'Tirunelveli',
        'salem'       => 'Salem',
        default       => ''
    };
    if ($loc_strength_key !== '') {
        $employee_strength[$lv][$loc_strength_key]++;
        $employee_strength[$lv]['Total']++;
        $employee_strength['Total'][$loc_strength_key]++;
        $employee_strength['Total']['Total']++;
    }
}

/* ================= MANAGER MAP ================= */
$map = [];
foreach ($employees as $e) {
    $mgr = trim($e['reporting_manager'] ?? '');
    if ($mgr === '' || strtolower($mgr) === 'md') {
        $mgr = $md['full_name'];
    }
    $map[keyName($mgr)][] = $e;
}

/* ================= BIRTHDAY FOLKS ================= */
$today      = new DateTime();
$this_month = (int)$today->format('m');
$today_day  = (int)$today->format('d');

$birthday_folks = [];
$upcoming_bdays = [];
foreach (array_merge([$md], $employees) as $emp) {
    $dob = trim($emp['dob'] ?? '');
    if ($dob === '' || $dob === '0000-00-00') continue;
    try {
        $d = new DateTime($dob);
        $bday_month = (int)$d->format('m');
        $bday_day   = (int)$d->format('d');
        if ($bday_month === $this_month) {
            $emp['_bday_day'] = $bday_day;
            $emp['_dob_fmt']  = $d->format('d M');
            if ($bday_day === $today_day) {
                $birthday_folks[] = $emp;
            } else {
                $upcoming_bdays[] = $emp;
            }
        }
    } catch (Exception $e) {}
}
usort($upcoming_bdays, fn($a,$b) => $a['_bday_day'] <=> $b['_bday_day']);
$all_bdays = array_merge($birthday_folks, $upcoming_bdays);

/* ================= NEW HIRES ================= */
$new_hires       = [];
$ninety_days_ago = (new DateTime())->modify('-90 days');
foreach (array_merge([$md], $employees) as $emp) {
    $doj = trim($emp['date_of_joining'] ?? '');
    if ($doj === '' || $doj === '0000-00-00') continue;
    try {
        $d = new DateTime($doj);
        if ($d >= $ninety_days_ago) {
            $emp['_doj_fmt']  = $d->format('d M Y');
            $emp['_days_ago'] = (int)$today->diff($d)->days;
            $new_hires[]      = $emp;
        }
    } catch (Exception $e) {}
}
usort($new_hires, function($a,$b) {
    $da = new DateTime(trim($a['date_of_joining']));
    $db = new DateTime(trim($b['date_of_joining']));
    return $db <=> $da;
});

/* ================= ORG BUILDER ================= */
function orgCards($map, $manager, $base_url, $location_labels, $depth = 0){
    global $level_order;
    if ($depth > 20) return '';
    $key = keyName($manager);
    if (!isset($map[$key])) return '';

    $byLevel = [];
    foreach ($map[$key] as $e) {
        $lvl = in_array($e['level'], $level_order, true) ? $e['level'] : 'L5';
        $byLevel[$lvl][] = $e;
    }

    $html = '';
    foreach ($level_order as $lvl) {
        if (empty($byLevel[$lvl])) continue;

        $html .= "<div class='org-row'>";
        foreach ($byLevel[$lvl] as $e) {
            $name     = $e['full_name'];
            $photo    = !empty($e['photo']) ? $base_url.'/'.$e['photo'] : $base_url.'/default.jpg';
            $hasChild = isset($map[keyName($name)]);
            $childId  = 'team_'.md5($name.$depth);
            $lv_short = strtolower($lvl);
            $lv_num   = intval(substr($lvl,1));
            $lk       = strtolower(trim($e['location'] ?? ''));
            $dloc     = $location_labels[$lk] ?? ucfirst($lk);

            $html .= "<div class='org-card level-l{$lv_num}' style='position:relative'>";
            $html .= "<span class='node-badge level-badge-{$lv_short}'>".h($lvl)."</span>";
            $html .= "<div class='node-avatar-wrap'>";
            $html .= "<img src='".h($photo)."' alt='".h($name)."' class='node-avatar' onerror=\"this.src='https://ui-avatars.com/api/?name=".urlencode($name)."&background=e2e8f0&color=64748b&size=80';\">";
            $html .= "</div>";
            $html .= "<div class='node-info'>";
            $html .= "<p class='node-name'>".h($name)."</p>";
            $html .= "<p class='node-role'>".h($e['designation'])."</p>";
            if (!empty($e['division'])) $html .= "<p class='node-dept'><i class='fas fa-layer-group'></i> ".h($e['division'])."</p>";
            $html .= "<p class='node-loc'><span class='loc-dot'></span>".h($dloc)."</p>";
            $html .= "</div>";

            if ($hasChild) {
                $html .= "<button class='org-toggle-btn' onclick=\"toggleTeam('$childId')\"><i class='fas fa-users'></i> Team <i class='fas fa-chevron-down' id='arr_$childId'></i></button>";
            }
            $html .= "</div>";
        }
        $html .= "</div>";

        foreach ($byLevel[$lvl] as $e) {
            $name = $e['full_name'];
            if (isset($map[keyName($name)])) {
                $childId = 'team_'.md5($name.$depth);
                $html .= "<div id='$childId' class='org-children hidden'>";
                $html .= "<div class='org-connector'></div>";
                $html .= orgCards($map, $name, $base_url, $location_labels, $depth+1);
                $html .= "</div>";
            }
        }
    }
    return $html;
}

$md_photo_path = !empty($md['photo']) ? $base_url.'/'.$md['photo'] : $base_url.'/default.jpg';
$md_loc_key    = strtolower(trim($md['location'] ?? 'karur'));
$md_location   = $location_labels[$md_loc_key] ?? ucfirst($md_loc_key);
$md_level_val  = strtoupper($md['level'] ?? 'L1');
$md_level_short = strtolower($md_level_val);
?>
<!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 · MD Dashboard</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=Sora:wght@300;400;500;600;700&family=JetBrains+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">
<style>
/* ─── RESET & TOKENS ─────────────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
  --ink:        #0f172a;
  --ink-2:      #334155;
  --muted:      #94a3b8;
  --border:     #e2e8f0;
  --surface:    #ffffff;
  --bg:         #f1f5f9;
  --sidebar-bg: #0f172a;
  --sidebar-w:  260px;

  --l1: #0f172a;
  --l2: #1d4ed8;
  --l3: #059669;
  --l4: #d97706;
  --l5: #dc2626;

  --l1-light: #e2e8f0;
  --l2-light: #dbeafe;
  --l3-light: #d1fae5;
  --l4-light: #fef3c7;
  --l5-light: #fee2e2;

  --radius: 12px;
  --shadow: 0 1px 3px rgba(15,23,42,.06), 0 4px 16px rgba(15,23,42,.06);
  --shadow-md: 0 4px 6px rgba(15,23,42,.07), 0 12px 32px rgba(15,23,42,.10);

  font-family: 'Sora', system-ui, sans-serif;
}

html, body { height: 100%; }
body { background: var(--bg); color: var(--ink); font-size: 14px; line-height: 1.6; -webkit-font-smoothing: antialiased; }

/* ─── LAYOUT ─────────────────────────────────────────────────────────────── */
.layout { display: flex; min-height: 100vh; }

/* ─── SIDEBAR ────────────────────────────────────────────────────────────── */
.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; overflow-x: hidden;
  transition: transform .3s cubic-bezier(.4,0,.2,1); scrollbar-width: none;
}
.sidebar::-webkit-scrollbar { display: none; }
.sidebar.hidden { transform: translateX(-100%); }
.sidebar-brand {
  padding: 24px 20px 16px; display: flex; align-items: center; gap: 10px;
  border-bottom: 1px solid rgba(255,255,255,.06); margin-bottom: 8px;
}
.brand-logo {
  width: 36px; height: 36px; background: linear-gradient(135deg, #3b82f6, #6366f1);
  border-radius: 8px; display: flex; align-items: center; justify-content: center;
  font-size: 16px; font-weight: 700; color: #fff; flex-shrink: 0; letter-spacing: -.5px;
}
.brand-name { font-size: 15px; font-weight: 700; color: #fff; letter-spacing: .3px; }
.brand-sub  { font-size: 10px; color: rgba(255,255,255,.4); letter-spacing: 1.5px; text-transform: uppercase; margin-top: 1px; }
.nav-section { padding: 0 12px 6px; }
.nav-item    { list-style: none; }
.nav-link {
  display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px;
  color: rgba(255,255,255,.65); text-decoration: none; font-size: 13px; font-weight: 500;
  transition: background .15s, color .15s;
}
.nav-link:hover { background: rgba(255,255,255,.07); color: #fff; }
.nav-link.active { background: rgba(59,130,246,.2); color: #60a5fa; }
.nav-link i { width: 16px; text-align: center; font-size: 13px; }
.nav-link.danger { color: #f87171; }
.nav-link.danger:hover { background: rgba(248,113,113,.12); color: #fca5a5; }
.sidebar-footer { margin-top: auto; padding: 12px; 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 cubic-bezier(.4,0,.2,1); }
.content.expanded { margin-left: 0; }

/* ─── TOPBAR ─────────────────────────────────────────────────────────────── */
.topbar {
  height: 60px; background: var(--surface); border-bottom: 1px solid var(--border);
  display: flex; align-items: center; gap: 12px; padding: 0 24px;
  position: sticky; top: 0; z-index: 100;
}
.hamburger-btn {
  width: 36px; height: 36px; border-radius: 8px; border: 1px solid var(--border);
  background: var(--surface); display: flex; align-items: center; justify-content: center;
  cursor: pointer; color: var(--ink-2); font-size: 15px; flex-shrink: 0; transition: background .15s;
}
.hamburger-btn:hover { background: var(--bg); }
.topbar-breadcrumb { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--muted); }
.topbar-breadcrumb .current { color:var(--ink); font-weight:600; }
.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, #3b82f6, #6366f1);
  display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; font-weight: 700;
}

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

/* ─── STAT CARDS ─────────────────────────────────────────────────────────── */
.stat-grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 12px; margin-bottom: 20px; }
.stat-card {
  background: var(--surface); border-radius: var(--radius); padding: 16px;
  box-shadow: var(--shadow); position: relative; overflow: hidden; border: 1px solid var(--border);
}
.stat-card::before {
  content: ''; position: absolute; top: 0; left: 0; right: 0;
  height: 3px; border-radius: 3px 3px 0 0;
}
.stat-card.lv1::before { background: var(--l1); }
.stat-card.lv2::before { background: var(--l2); }
.stat-card.lv3::before { background: var(--l3); }
.stat-card.lv4::before { background: var(--l4); }
.stat-card.lv5::before { background: var(--l5); }
.stat-card.lvt::before { background: linear-gradient(90deg, var(--l2), var(--l3)); }
.stat-icon { width:32px; height:32px; border-radius:8px; display:flex; align-items:center; justify-content:center; font-size:14px; margin-bottom:10px; }
.stat-card.lv1 .stat-icon { background:var(--l1-light); color:var(--l1); }
.stat-card.lv2 .stat-icon { background:var(--l2-light); color:var(--l2); }
.stat-card.lv3 .stat-icon { background:var(--l3-light); color:var(--l3); }
.stat-card.lv4 .stat-icon { background:var(--l4-light); color:var(--l4); }
.stat-card.lv5 .stat-icon { background:var(--l5-light); color:var(--l5); }
.stat-card.lvt .stat-icon { background:#ede9fe; color:#7c3aed; }
.stat-num { font-size:26px; font-weight:700; letter-spacing:-.8px; color:var(--ink); line-height:1; margin-bottom:4px; font-family:'JetBrains Mono',monospace; }
.stat-lbl  { font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:.8px; color:var(--muted); }

/* ─── TABS ───────────────────────────────────────────────────────────────── */
.tabs-wrap {
  display: flex; gap: 4px; background: var(--surface); border: 1px solid var(--border);
  border-radius: 10px; padding: 4px; width: fit-content; margin-bottom: 20px; box-shadow: var(--shadow);
  flex-wrap: wrap;
}
.tab-btn {
  padding: 8px 16px; border: none; background: none; border-radius: 7px;
  font-size: 13px; font-weight: 600; font-family: 'Sora', sans-serif;
  color: var(--muted); cursor: pointer; display: flex; align-items: center; gap: 6px;
  transition: background .15s, color .15s;
}
.tab-btn:hover { color: var(--ink); background: var(--bg); }
.tab-btn.active { background: var(--ink); color: #fff; }

/* ─── PANELS ─────────────────────────────────────────────────────────────── */
.panel { display: none; }
.panel.active { display: block; animation: fadeUp .25s ease; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
.panel-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; flex-wrap:wrap; gap:10px; }
.panel-title  { font-size:16px; font-weight:700; color:var(--ink); letter-spacing:-.3px; }

/* ─── CARD ───────────────────────────────────────────────────────────────── */
.card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow); overflow:hidden; }

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

/* ─── LEVEL BADGE ────────────────────────────────────────────────────────── */
.lvbadge {
  display:inline-flex; align-items:center; justify-content:center;
  padding:2px 9px; border-radius:20px;
  font-size:11px; font-weight:700; font-family:'JetBrains Mono',monospace; letter-spacing:.5px;
}
.lvbadge.l1 { background:var(--l1-light); color:var(--l1); }
.lvbadge.l2 { background:var(--l2-light); color:var(--l2); }
.lvbadge.l3 { background:var(--l3-light); color:var(--l3); }
.lvbadge.l4 { background:var(--l4-light); color:var(--l4); }
.lvbadge.l5 { background:var(--l5-light); color:var(--l5); }

/* ─── MD SPOTLIGHT ───────────────────────────────────────────────────────── */
.md-spotlight {
  display: flex; justify-content: center; margin-bottom: 36px;
}
.md-card-hero {
  background: var(--ink); border-radius: 20px; padding: 28px 40px;
  display: flex; align-items: center; gap: 24px;
  box-shadow: var(--shadow-md); position: relative; overflow: hidden; min-width: 420px;
}
.md-card-hero::before {
  content: ''; position: absolute; inset: 0;
  background: linear-gradient(135deg, rgba(59,130,246,.15), rgba(99,102,241,.15));
  pointer-events: none;
}
.md-hero-avatar { position: relative; flex-shrink: 0; }
.md-hero-avatar img {
  width: 88px; height: 88px; border-radius: 50%; object-fit: cover;
  border: 3px solid rgba(255,255,255,.2); display: block;
}
.md-hero-badge {
  position: absolute; bottom: -4px; right: -4px;
  font-size: 10px; font-weight: 700; font-family: 'JetBrains Mono', monospace;
  border-radius: 20px; padding: 2px 8px; background: #3b82f6; color: #fff;
  border: 2px solid var(--ink);
}
.md-hero-info {}
.md-hero-label { font-size: 10px; font-weight: 700; letter-spacing: 2px; text-transform: uppercase; color: rgba(255,255,255,.4); margin-bottom: 4px; }
.md-hero-name  { font-size: 20px; font-weight: 700; color: #fff; letter-spacing: -.4px; }
.md-hero-desig { font-size: 13px; color: rgba(255,255,255,.6); margin-top: 2px; }
.md-hero-loc   { font-size: 12px; color: rgba(255,255,255,.45); margin-top: 6px; display: flex; align-items: center; gap: 5px; }
.md-hero-loc-dot { width: 5px; height: 5px; border-radius: 50%; background: #10b981; flex-shrink: 0; }

/* ─── ORG CHART ──────────────────────────────────────────────────────────── */
.org-canvas-wrap {
  overflow: auto; position: relative; background: var(--surface);
  border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow);
  min-height: 300px; padding: 30px;
}
.org-row { display: flex; justify-content: center; flex-wrap: wrap; gap: 20px; margin-bottom: 8px; }
.org-card {
  width: 178px; border-radius: 14px; padding: 16px 14px 14px; text-align: center;
  background: var(--surface); border: 1.5px solid var(--border);
  box-shadow: 0 2px 8px rgba(15,23,42,.06);
  transition: box-shadow .2s, transform .2s, border-color .2s;
  position: relative;
}
.org-card:hover { box-shadow: var(--shadow-md); transform: translateY(-3px); }
.org-card.level-l1 { border-left: 3px solid var(--l1); }
.org-card.level-l2 { border-left: 3px solid var(--l2); }
.org-card.level-l3 { border-left: 3px solid var(--l3); }
.org-card.level-l4 { border-left: 3px solid var(--l4); }
.org-card.level-l5 { border-left: 3px solid var(--l5); }
.node-avatar-wrap { position: relative; display: inline-block; margin-bottom: 10px; }
.node-avatar { width: 60px; height: 60px; border-radius: 50%; object-fit: cover; border: 2.5px solid var(--border); display: block; }
.node-badge {
  position: absolute; bottom: -4px; right: -4px; font-size: 10px; font-weight: 700;
  font-family: 'JetBrains Mono', monospace; border-radius: 20px; padding: 1px 6px;
  color: #fff; border: 1.5px solid var(--surface);
}
.level-badge-l1 { background: var(--l1); }
.level-badge-l2 { background: var(--l2); }
.level-badge-l3 { background: var(--l3); }
.level-badge-l4 { background: var(--l4); }
.level-badge-l5 { background: var(--l5); }
.node-info { width: 100%; }
.node-name { font-size: 12px; font-weight: 700; color: var(--ink); margin-bottom: 2px; line-height: 1.3; }
.node-role { font-size: 10.5px; color: var(--muted); margin-bottom: 2px; }
.node-dept { font-size: 10px; color: var(--muted); margin-bottom: 4px; display: flex; align-items: center; gap: 3px; justify-content: center; }
.node-dept i { font-size: 9px; }
.node-loc  { font-size: 10px; color: var(--muted); display: flex; align-items: center; gap: 4px; justify-content: center; }
.loc-dot   { width: 5px; height: 5px; border-radius: 50%; background: var(--l3); flex-shrink: 0; }
.org-toggle-btn {
  margin-top: 10px; padding: 5px 14px; border-radius: 20px;
  border: 1.5px solid var(--border); background: var(--bg);
  font-size: 11px; font-weight: 600; font-family: 'Sora', sans-serif;
  color: var(--ink-2); cursor: pointer; display: inline-flex; align-items: center; gap: 5px;
  transition: background .15s, border-color .15s, color .15s;
}
.org-toggle-btn:hover { background: var(--surface); border-color: #94a3b8; color: var(--ink); }
.org-children { margin-top: 10px; }
.org-connector {
  width: 2px; height: 24px; background: #cbd5e1; margin: 0 auto 0;
}
.hidden { display: none; }

/* ─── BIRTHDAY & NEW HIRES ───────────────────────────────────────────────── */
.people-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 14px; }
.people-card {
  background: var(--surface); border: 1px solid var(--border);
  border-radius: var(--radius); padding: 16px;
  display: flex; align-items: center; gap: 14px;
  box-shadow: var(--shadow); transition: box-shadow .2s, transform .2s;
  position: relative; overflow: hidden;
}
.people-card:hover { box-shadow: var(--shadow-md); transform: translateY(-2px); }
.people-card::before { content:''; position:absolute; top:0; left:0; right:0; height:3px; }
.people-card.bday-today::before    { background: linear-gradient(90deg, #f59e0b, #ef4444); }
.people-card.bday-upcoming::before { background: linear-gradient(90deg, #a78bfa, #6366f1); }
.people-card.new-hire::before      { background: linear-gradient(90deg, #10b981, #06b6d4); }
.people-avatar { width: 52px; height: 52px; border-radius: 50%; object-fit: cover; border: 2.5px solid var(--border); flex-shrink: 0; }
.people-info { flex: 1; min-width: 0; }
.people-name { font-size: 13px; font-weight: 700; color: var(--ink); margin-bottom: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.people-role { font-size: 11px; color: var(--muted); margin-bottom: 4px; }
.people-badge { display:inline-flex; align-items:center; gap:4px; font-size:10px; font-weight:700; padding:2px 8px; border-radius:20px; font-family:'JetBrains Mono',monospace; }
.badge-today    { background: #fef3c7; color: #b45309; }
.badge-upcoming { background: #ede9fe; color: #7c3aed; }
.badge-newhire  { background: #d1fae5; color: #059669; }
.section-sub-head {
  font-size: 11px; font-weight: 700; text-transform: uppercase;
  letter-spacing: .8px; color: var(--muted); margin: 20px 0 10px;
  display: flex; align-items: center; gap: 8px;
}
.section-sub-head::after { content:''; flex:1; height:1px; background:var(--border); }
.empty-state { text-align: center; padding: 48px 24px; color: var(--muted); }
.empty-state i { font-size: 36px; margin-bottom: 12px; opacity: .4; display: block; }
.empty-state p { font-size: 14px; }

/* ─── RESPONSIVE ─────────────────────────────────────────────────────────── */
@media (max-width: 1024px) { .stat-grid { grid-template-columns: repeat(3,1fr); } }
@media (max-width: 768px)  {
  .sidebar { transform: translateX(-100%); }
  .sidebar:not(.hidden) { transform: none; }
  .content { margin-left: 0; }
  .stat-grid { grid-template-columns: repeat(2,1fr); }
  .page { padding: 16px; }
  .md-card-hero { min-width: unset; flex-direction: column; text-align: center; }
  .md-hero-loc { justify-content: center; }
}
@media (max-width: 480px) { .stat-grid { grid-template-columns: 1fr 1fr; } }
</style>
</head>
<body>

<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</div>
      <div class="brand-sub">MD Portal</div>
    </div>
  </div>
  <nav class="nav-section">
    <ul style="list-style:none">
      <li class="nav-item">
        <a href="#" class="nav-link active" onclick="return false;">
          <i class="fas fa-sitemap"></i> Organisation
        </a>
      </li>
      <li class="nav-item">
        <a href="payroll_md_dashboard.php" class="nav-link">
          <i class="fas fa-money-bill"></i> Payroll
        </a>
      </li>
      <li class="nav-item">
        <a href="daily_reports_dashboard_md.php" class="nav-link">
          <i class="fas fa-chart-line"></i> Reports
        </a>
      </li>
      <li class="nav-item">
        <a href="md_leave_approval.php" class="nav-link">
          <i class="fas fa-umbrella-beach"></i> Leave Approval
        </a>
      </li>
      <li class="nav-item">
        <a href="mdmobile.php" class="nav-link">
          <i class="fas fa-mobile-alt"></i> Attendance
        </a>
      </li>
      <li class="nav-item">
        <a href="tasks_md.php" class="nav-link">
          <i class="fas fa-tasks"></i> Tasks
        </a>
      </li>
          </ul>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="nav-link danger">
      <i class="fas fa-sign-out-alt"></i> Logout
    </a>
  </div>
</nav>

<!-- ── CONTENT ───────────────────────────────────────────────────────────── -->
<div class="content" id="content">

  <!-- Topbar -->
  <div class="topbar">
    <button class="hamburger-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-breadcrumb">
      <span>Organisation</span>
      <i class="fas fa-chevron-right" style="font-size:10px;color:var(--border)"></i>
      <span class="current">MD Overview</span>
    </div>
    <div class="topbar-spacer"></div>
    <div class="topbar-user">
      <div class="topbar-avatar"><?php echo strtoupper(substr($username ?: 'M', 0, 1)); ?></div>
      <?php echo h($username ?: 'MD'); ?>
    </div>
  </div>

  <!-- Page -->
  <div class="page">

    <div class="page-header">
      <div class="page-title">Organization Overview</div>
      <div class="page-subtitle">Workforce structure, headcount analytics, and reporting hierarchy</div>
    </div>

    <!-- Stat Cards -->
    <div class="stat-grid">
      <?php
      $lvs = [
        ['lv1','L1','shield-alt',   $employee_strength['L1']['Total']],
        ['lv2','L2','user-tie',     $employee_strength['L2']['Total']],
        ['lv3','L3','user',         $employee_strength['L3']['Total']],
        ['lv4','L4','user-friends', $employee_strength['L4']['Total']],
        ['lv5','L5','users',        $employee_strength['L5']['Total']],
        ['lvt','Total','building',  $employee_strength['Total']['Total']],
      ];
      foreach ($lvs as [$cls, $lbl, $icon, $num]):
      ?>
      <div class="stat-card <?php echo $cls; ?>">
        <div class="stat-icon"><i class="fas fa-<?php echo $icon; ?>"></i></div>
        <div class="stat-num"><?php echo $num ?? 0; ?></div>
        <div class="stat-lbl"><?php echo $lbl === 'Total' ? 'Total Employees' : $lbl . ' Employees'; ?></div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- Tabs -->
    <div class="tabs-wrap">
      <button class="tab-btn active" data-panel="panel-orgchart" onclick="switchTab(this)">
        <i class="fas fa-sitemap"></i> Org Chart
      </button>
      <button class="tab-btn" data-panel="panel-strength" onclick="switchTab(this)">
        <i class="fas fa-chart-bar"></i> Strength by Location
      </button>
      <button class="tab-btn" data-panel="panel-birthdays" onclick="switchTab(this)">
        <i class="fas fa-birthday-cake"></i> Birthday Folks
        <?php if (!empty($birthday_folks)): ?>
        <span style="background:#ef4444;color:#fff;border-radius:20px;padding:0 6px;font-size:10px;margin-left:2px"><?php echo count($birthday_folks); ?></span>
        <?php endif; ?>
      </button>
      <button class="tab-btn" data-panel="panel-newhires" onclick="switchTab(this)">
        <i class="fas fa-user-plus"></i> New Hires
        <?php if (!empty($new_hires)): ?>
        <span style="background:#059669;color:#fff;border-radius:20px;padding:0 6px;font-size:10px;margin-left:2px"><?php echo count($new_hires); ?></span>
        <?php endif; ?>
      </button>
    </div>

    <!-- ════ PANEL: ORG CHART ════ -->
    <div class="panel active" id="panel-orgchart">
      <div class="panel-header">
        <div class="panel-title">Organisation Hierarchy</div>
      </div>

      <!-- MD Spotlight Card -->
      <div class="md-spotlight">
        <div class="md-card-hero">
          <div class="md-hero-avatar">
            <img src="<?php echo h($md_photo_path); ?>" alt="<?php echo h($md['full_name']); ?>"
                 onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($md['full_name']); ?>&background=ffffff&color=0f172a&size=88&bold=true';">
            <span class="md-hero-badge"><?php echo h($md_level_val); ?></span>
          </div>
          <div class="md-hero-info">
            <div class="md-hero-label">Managing Director</div>
            <div class="md-hero-name"><?php echo h($md['full_name']); ?></div>
            <div class="md-hero-desig"><?php echo h($md['designation']); ?></div>
            <div class="md-hero-loc">
              <span class="md-hero-loc-dot"></span>
              <?php echo h($md_location); ?>
            </div>
          </div>
        </div>
      </div>

      <!-- Org Tree -->
      <div class="org-canvas-wrap">
        <?php echo orgCards($map, $md['full_name'], $base_url, $location_labels); ?>
      </div>
    </div>

    <!-- ════ PANEL: STRENGTH BY LOCATION ════ -->
    <div class="panel" id="panel-strength">
      <div class="panel-header">
        <div class="panel-title">Employee Strength by Location</div>
      </div>
      <div class="card">
        <div class="tbl-wrap">
          <table>
            <thead>
              <tr>
                <th>Level</th>
                <th><i class="fas fa-star" style="color:#f59e0b;margin-right:4px"></i>Karur (HO)</th>
                <th>Trichy</th>
                <th>Madurai</th>
                <th>Coimbatore</th>
                <th>Tirunelveli</th>
                <th>Salem</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($employee_strength as $level => $counts): ?>
                <?php if ($level !== 'Total'): ?>
                <tr>
                  <td><span class="lvbadge <?php echo strtolower($level); ?>"><?php echo h($level); ?></span></td>
                  <td style="font-family:'JetBrains Mono',monospace;font-weight:600"><?php echo $counts['Karur']       ?? 0; ?></td>
                  <td style="font-family:'JetBrains Mono',monospace;font-weight:600"><?php echo $counts['Trichy']      ?? 0; ?></td>
                  <td style="font-family:'JetBrains Mono',monospace;font-weight:600"><?php echo $counts['Madurai']     ?? 0; ?></td>
                  <td style="font-family:'JetBrains Mono',monospace;font-weight:600"><?php echo $counts['Coimbatore']  ?? 0; ?></td>
                  <td style="font-family:'JetBrains Mono',monospace;font-weight:600"><?php echo $counts['Tirunelveli'] ?? 0; ?></td>
                  <td style="font-family:'JetBrains Mono',monospace;font-weight:600"><?php echo $counts['Salem']       ?? 0; ?></td>
                  <td style="font-family:'JetBrains Mono',monospace;font-weight:600;color:var(--ink)"><?php echo $counts['Total'] ?? 0; ?></td>
                </tr>
                <?php endif; ?>
              <?php endforeach; ?>
            </tbody>
            <tfoot>
              <tr>
                <td>Grand Total</td>
                <td><?php echo $employee_strength['Total']['Karur']       ?? 0; ?></td>
                <td><?php echo $employee_strength['Total']['Trichy']      ?? 0; ?></td>
                <td><?php echo $employee_strength['Total']['Madurai']     ?? 0; ?></td>
                <td><?php echo $employee_strength['Total']['Coimbatore']  ?? 0; ?></td>
                <td><?php echo $employee_strength['Total']['Tirunelveli'] ?? 0; ?></td>
                <td><?php echo $employee_strength['Total']['Salem']       ?? 0; ?></td>
                <td><?php echo $employee_strength['Total']['Total']       ?? 0; ?></td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>

    <!-- ════ PANEL: BIRTHDAY FOLKS ════ -->
    <div class="panel" id="panel-birthdays">
      <div class="panel-header">
        <div class="panel-title">🎂 Birthday Folks — <?php echo $today->format('F Y'); ?></div>
        <div style="font-size:12px;color:var(--muted)"><?php echo count($all_bdays); ?> birthday<?php echo count($all_bdays) != 1 ? 's' : ''; ?> this month</div>
      </div>

      <?php if (empty($all_bdays)): ?>
      <div class="card">
        <div class="empty-state">
          <i class="fas fa-birthday-cake"></i>
          <p>No birthdays recorded for <?php echo $today->format('F'); ?>.</p>
          <p style="font-size:12px;margin-top:6px">Make sure employee DOB fields are filled in.</p>
        </div>
      </div>
      <?php else: ?>

        <?php if (!empty($birthday_folks)): ?>
        <div class="section-sub-head"><i class="fas fa-fire" style="color:#ef4444"></i> Today's Birthdays — <?php echo $today->format('d M'); ?></div>
        <div class="people-grid">
          <?php foreach ($birthday_folks as $emp):
            $fn  = $emp['full_name'] ?? trim(($emp['first_name']??'').' '.($emp['last_name']??''));
            $pn  = $emp['photo'] ?? '';
            $pp  = !empty($pn) ? $base_url.'/'.$pn : $base_url.'/default.jpg';
            $des = $emp['designation'] ?? '';
          ?>
          <div class="people-card bday-today">
            <img src="<?php echo h($pp); ?>" alt="<?php echo h($fn); ?>" class="people-avatar"
                 onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($fn); ?>&background=fef3c7&color=b45309&size=52';">
            <div class="people-info">
              <div class="people-name"><?php echo h($fn); ?></div>
              <div class="people-role"><?php echo h($des); ?></div>
              <span class="people-badge badge-today"><i class="fas fa-birthday-cake"></i> Today!</span>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <?php if (!empty($upcoming_bdays)): ?>
        <div class="section-sub-head"><i class="fas fa-calendar-alt" style="color:#7c3aed"></i> Upcoming This Month</div>
        <div class="people-grid">
          <?php foreach ($upcoming_bdays as $emp):
            $fn  = $emp['full_name'] ?? trim(($emp['first_name']??'').' '.($emp['last_name']??''));
            $pn  = $emp['photo'] ?? '';
            $pp  = !empty($pn) ? $base_url.'/'.$pn : $base_url.'/default.jpg';
            $des = $emp['designation'] ?? '';
            $bdf = $emp['_dob_fmt'] ?? '';
          ?>
          <div class="people-card bday-upcoming">
            <img src="<?php echo h($pp); ?>" alt="<?php echo h($fn); ?>" class="people-avatar"
                 onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($fn); ?>&background=ede9fe&color=7c3aed&size=52';">
            <div class="people-info">
              <div class="people-name"><?php echo h($fn); ?></div>
              <div class="people-role"><?php echo h($des); ?></div>
              <span class="people-badge badge-upcoming"><i class="fas fa-calendar"></i> <?php echo h($bdf); ?></span>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>

      <?php endif; ?>
    </div>

    <!-- ════ PANEL: NEW HIRES ════ -->
    <div class="panel" id="panel-newhires">
      <div class="panel-header">
        <div class="panel-title">🌟 New Hires — Last 90 Days</div>
        <div style="font-size:12px;color:var(--muted)"><?php echo count($new_hires); ?> employee<?php echo count($new_hires) != 1 ? 's' : ''; ?> joined recently</div>
      </div>

      <?php if (empty($new_hires)): ?>
      <div class="card">
        <div class="empty-state">
          <i class="fas fa-user-plus"></i>
          <p>No new hires in the last 90 days.</p>
          <p style="font-size:12px;margin-top:6px">Make sure employee date_of_joining fields are filled in.</p>
        </div>
      </div>
      <?php else: ?>
      <div class="people-grid">
        <?php foreach ($new_hires as $emp):
          $fn      = $emp['full_name'] ?? trim(($emp['first_name']??'').' '.($emp['last_name']??''));
          $pn      = $emp['photo'] ?? '';
          $pp      = !empty($pn) ? $base_url.'/'.$pn : $base_url.'/default.jpg';
          $des     = $emp['designation'] ?? '';
          $div     = $emp['division'] ?? '';
          $lv      = strtoupper($emp['level'] ?? '');
          $lk      = strtolower(trim($emp['location'] ?? ''));
          $dloc    = $location_labels[$lk] ?? ucfirst($lk);
          $doj_fmt = $emp['_doj_fmt'] ?? '';
          $comp    = trim($emp['company'] ?? '');
        ?>
        <div class="people-card new-hire">
          <img src="<?php echo h($pp); ?>" alt="<?php echo h($fn); ?>" class="people-avatar"
               onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($fn); ?>&background=d1fae5&color=059669&size=52';">
          <div class="people-info">
            <div class="people-name"><?php echo h($fn); ?></div>
            <div class="people-role"><?php echo h($des); ?><?php if ($div): ?> · <?php echo h($div); ?><?php endif; ?></div>
            <?php if ($comp): ?>
            <div style="font-size:10px;color:var(--muted);margin-bottom:3px"><?php echo h($comp); ?></div>
            <?php endif; ?>
            <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
              <span class="people-badge badge-newhire"><i class="fas fa-calendar-check"></i> <?php echo h($doj_fmt); ?></span>
              <?php if ($lv): ?><span class="lvbadge <?php echo strtolower($lv); ?>" style="font-size:10px;padding:1px 6px"><?php echo h($lv); ?></span><?php endif; ?>
              <?php if ($dloc): ?>
              <span style="font-size:10px;color:var(--muted);display:flex;align-items:center;gap:3px"><span class="loc-dot"></span><?php echo h($dloc); ?></span>
              <?php endif; ?>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

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

<script>
/* ═══ SIDEBAR ══════════════════════════════════════════════════════════════ */
function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('hidden');
  document.getElementById('content').classList.toggle('expanded');
}

/* ═══ TABS ═════════════════════════════════════════════════════════════════ */
function switchTab(btn) {
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
  btn.classList.add('active');
  document.getElementById(btn.dataset.panel)?.classList.add('active');
}

/* ═══ ORG TEAM TOGGLE ══════════════════════════════════════════════════════ */
function toggleTeam(id) {
  const el  = document.getElementById(id);
  const arr = document.getElementById('arr_' + id);
  if (!el) return;
  el.classList.toggle('hidden');
  if (arr) arr.style.transform = el.classList.contains('hidden') ? '' : 'rotate(180deg)';
}
</script>
</body>
</html>