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

function h($s){return htmlspecialchars($s??'',ENT_QUOTES,'UTF-8');}
function nk($n){return mb_strtolower(trim(preg_replace('/\s+/',' ',(string)$n)),'UTF-8');}
function purl($p,$n,$base,$bg='e2e8f0',$c='475569'){
    return !empty(trim($p??''))?$base.'/'.ltrim($p,'/'):
        'https://ui-avatars.com/api/?name='.urlencode($n).'&background='.$bg.'&color='.$c.'&size=80&bold=true';
}
function fmtdate($s){
    if(!$s||$s==='0000-00-00')return'—';
    try{$d=new DateTime($s);return $d->format('d M Y');}catch(Exception $e){return $s;}
}

/*
|--------------------------------------------------------------------------
| SUPERADMIN ACCESS ONLY
|--------------------------------------------------------------------------
| Only logged-in users with role = superadmin can access this page.
|--------------------------------------------------------------------------
*/
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

if (
    !isset($_SESSION['role']) ||
    strtolower(trim((string)$_SESSION['role'])) !== 'superadmin'
) {
    header("Location: index.php");
    exit();
}

$employee_id = $_SESSION['user_id'];
$username = $_SESSION['username'] ?? '';
$today_date = date('Y-m-d');

// ── AJAX: today's daily report only
if(isset($_GET['action'])&&$_GET['action']==='reports'&&!empty($_GET['uid'])){
    header('Content-Type: application/json');
    $uid=(int)$_GET['uid'];
    $td = mysqli_real_escape_string($conn, $today_date);
    $sql="SELECT report_date,`Location`,`Name of the Client` AS client,Hits,Missed,`carry forward` AS carry,
          full_report,daily_summary,end_of_day_report,report_status,manager_remarks,
          approval_status,login_time,logout_time,location_type,client_name,location_address
          FROM daily_reports WHERE user_id=$uid AND report_date='$td' LIMIT 1";
    $res=mysqli_query($conn,$sql);
    $rows=[];
    if($res)while($r=mysqli_fetch_assoc($res))$rows[]=$r;
    echo json_encode($rows);exit;
}

// ── AJAX: Save/Update today's daily report
if(isset($_POST['action'])&&$_POST['action']==='save_report'){
    header('Content-Type: application/json');
    $uid = (int)($_POST['uid']??0);
    if(!$uid){echo json_encode(['success'=>false,'msg'=>'Invalid employee']);exit;}
    $td = mysqli_real_escape_string($conn, $today_date);
    $location     = mysqli_real_escape_string($conn, trim($_POST['location']??''));
    $loc_type     = mysqli_real_escape_string($conn, trim($_POST['location_type']??''));
    $client       = mysqli_real_escape_string($conn, trim($_POST['client_name']??''));
    $hits         = mysqli_real_escape_string($conn, trim($_POST['hits']??''));
    $missed       = mysqli_real_escape_string($conn, trim($_POST['missed']??''));
    $carry        = mysqli_real_escape_string($conn, trim($_POST['carry']??''));
    $summary      = mysqli_real_escape_string($conn, trim($_POST['daily_summary']??''));
    $eod          = mysqli_real_escape_string($conn, trim($_POST['end_of_day_report']??''));
    $full         = mysqli_real_escape_string($conn, trim($_POST['full_report']??''));
    $status       = mysqli_real_escape_string($conn, trim($_POST['report_status']??'submitted'));
    $mgr_remarks  = mysqli_real_escape_string($conn, trim($_POST['manager_remarks']??''));
    $login_time   = mysqli_real_escape_string($conn, trim($_POST['login_time']??''));
    $logout_time  = mysqli_real_escape_string($conn, trim($_POST['logout_time']??''));
    $approval     = mysqli_real_escape_string($conn, trim($_POST['approval_status']??'pending'));

    // Check if report exists for today
    $chk = mysqli_query($conn,"SELECT id FROM daily_reports WHERE user_id=$uid AND report_date='$td' LIMIT 1");
    if($chk && mysqli_num_rows($chk)>0){
        $row = mysqli_fetch_assoc($chk);
        $rid = (int)$row['id'];
        $upd="UPDATE daily_reports SET
            `Location`='$location', location_type='$loc_type', client_name='$client',
            `Name of the Client`='$client',
            Hits='$hits', Missed='$missed', `carry forward`='$carry',
            daily_summary='$summary', end_of_day_report='$eod', full_report='$full',
            report_status='$status', manager_remarks='$mgr_remarks',
            login_time=".($login_time?"'$login_time'":'login_time').",
            logout_time=".($logout_time?"'$logout_time'":'logout_time').",
            approval_status='$approval'
            WHERE id=$rid";
        if(mysqli_query($conn,$upd)){echo json_encode(['success'=>true,'msg'=>'Report updated successfully','action'=>'updated']);}
        else{echo json_encode(['success'=>false,'msg'=>mysqli_error($conn)]);}
    } else {
        $ins="INSERT INTO daily_reports
            (user_id,report_date,`Location`,location_type,client_name,`Name of the Client`,
             Hits,Missed,`carry forward`,daily_summary,end_of_day_report,full_report,
             report_status,manager_remarks,login_time,logout_time,approval_status)
            VALUES($uid,'$td','$location','$loc_type','$client','$client',
            '$hits','$missed','$carry','$summary','$eod','$full',
            '$status','$mgr_remarks',".($login_time?"'$login_time'":'NULL').",".($logout_time?"'$logout_time'":'NULL').",'$approval')";
        if(mysqli_query($conn,$ins)){echo json_encode(['success'=>true,'msg'=>'Report added successfully','action'=>'added']);}
        else{echo json_encode(['success'=>false,'msg'=>mysqli_error($conn)]);}
    }
    exit;
}

$valid_locs=['karur','trichy','madurai','coimbatore','tirunelveli','salem'];
$loc_labels=['karur'=>'Karur (HO)','trichy'=>'Trichy','madurai'=>'Madurai','coimbatore'=>'Coimbatore','tirunelveli'=>'Tirunelveli','salem'=>'Salem'];
$base_url='https://spica.mybelief.in/uploads';

// id->name map
$id_name=[];
$r=mysqli_query($conn,"SELECT id,first_name,last_name FROM users WHERE status='active'");
if($r)while($row=mysqli_fetch_assoc($r))$id_name[$row['id']]=trim($row['first_name'].' '.$row['last_name']);

$res=mysqli_query($conn,
    "SELECT id,first_name,last_name,designation,division,level,location,
            reporting_manager,reporting_manager_id,photo,role,
            COALESCE(company,'') AS company,COALESCE(dob,'') AS dob,
            COALESCE(date_of_joining,'') AS date_of_joining
     FROM users WHERE status='active' AND role!='superadmin'");
if(!$res)die("Query failed: ".mysqli_error($conn));

function rloc($r){global $valid_locs;$k=strtolower(trim($r??''));return in_array($k,$valid_locs)?$k:'karur';}
function rlvl($r){$l=strtoupper(trim($r??''));return in_array($l,['L1','L2','L3','L4','L5'])?$l:'';}

$lc_caps=['Karur','Trichy','Madurai','Coimbatore','Tirunelveli','Salem'];
$lc_map=array_combine($valid_locs,$lc_caps);
$str_tpl=array_fill_keys(array_merge($lc_caps,['Total']),0);
$strength=[];foreach(array_merge(['L1','L2','L3','L4','L5'],['Total'])as$lv)$strength[$lv]=$str_tpl;

$all_rows=[];$md_row=null;
while($row=mysqli_fetch_assoc($res)){
    $row['level']=rlvl($row['level']);
    $row['location']=rloc($row['location']);
    $fn=trim($row['first_name'].' '.$row['last_name']);
    $rm=trim($row['reporting_manager']??'');
    if($rm===''&&!empty($row['reporting_manager_id'])&&isset($id_name[$row['reporting_manager_id']]))
        $rm=$id_name[$row['reporting_manager_id']];
    $row['rm']=$rm;$row['fn']=$fn;
    $lv=$row['level'];$lck=$lc_map[$row['location']]??'Karur';
    if($lv!==''){$strength[$lv][$lck]++;$strength[$lv]['Total']++;$strength['Total'][$lck]++;$strength['Total']['Total']++;}
    if(strtolower($row['role'])==='md'){$md_row=$row;continue;}
    $all_rows[]=$row;
}

if(!$md_row)$md_row=['id'=>'','first_name'=>'Managing','last_name'=>'Director','fn'=>'Managing Director',
    'designation'=>'Managing Director','division'=>'Leadership','level'=>'L1','location'=>'karur',
    'photo'=>'','rm'=>'','role'=>'md','company'=>'','dob'=>'','date_of_joining'=>''];
if(!isset($md_row['fn']))$md_row['fn']=trim($md_row['first_name'].' '.$md_row['last_name']);

$md_key=nk($md_row['fn']);$md_name=$md_row['fn'];

$hier=[];
foreach($all_rows as $emp){
    $rm=trim($emp['rm']??'');
    if($rm===''||strcasecmp($rm,'md')===0)$rm=$md_name;
    $mk=nk($rm);if($mk==='')$mk='unmapped';
    $hier[$mk][]=$emp;
}

$EMP=[];
$md_photo=purl($md_row['photo'],$md_name,$base_url,'1e293b','ffffff');
$EMP[$md_key]=['id'=>$md_row['id'],'name'=>$md_name,'designation'=>$md_row['designation'],
    'division'=>$md_row['division'],'level'=>$md_row['level'],
    'location'=>$loc_labels[$md_row['location']]??ucfirst($md_row['location']),
    'company'=>$md_row['company'],'dob'=>$md_row['dob'],'doj'=>$md_row['date_of_joining'],
    'manager'=>'','photo'=>$md_photo,'role'=>'md','reportees'=>[]];
foreach($all_rows as $emp){
    $k=nk($emp['fn']);
    $rm=trim($emp['rm']??'');if(strcasecmp($rm,'md')===0)$rm=$md_name;
    $EMP[$k]=['id'=>$emp['id'],'name'=>$emp['fn'],'designation'=>$emp['designation'],
        'division'=>$emp['division'],'level'=>$emp['level'],
        'location'=>$loc_labels[$emp['location']]??ucfirst($emp['location']),
        'company'=>$emp['company'],'dob'=>$emp['dob'],'doj'=>$emp['date_of_joining'],
        'manager'=>$rm,'photo'=>purl($emp['photo'],$emp['fn'],$base_url),
        'role'=>$emp['role'],'reportees'=>[]];
}
foreach($EMP as $k=>&$e){$mk=nk($e['manager']);if($mk!==''&&isset($EMP[$mk]))$EMP[$mk]['reportees'][]=$e['name'];}
unset($e);

$divisions=[];
foreach($all_rows as $emp){$d=trim($emp['division']??'')?:'General';$divisions[$d][]=$emp;}
$md_div=trim($md_row['division']??'')?:'Leadership';
if(!isset($divisions[$md_div]))$divisions[$md_div]=[];
array_unshift($divisions[$md_div],array_merge($md_row,['_is_md'=>true]));
ksort($divisions);

$sorted=$all_rows;
usort($sorted,function($a,$b){$o=['L1'=>1,'L2'=>2,'L3'=>3,'L4'=>4,'L5'=>5];return($o[$a['level']]??99)<=>($o[$b['level']]??99)?:strcmp($a['fn'],$b['fn']);});

$all_divs=[];
foreach($all_rows as $e){$d=trim($e['division']??'');if($d!==''&&!in_array($d,$all_divs))$all_divs[]=$d;}
sort($all_divs);

$today=new DateTime();$tm=(int)$today->format('m');$td2=(int)$today->format('d');
$bdays_today=[];$bdays_up=[];
foreach(array_merge([$md_row],$all_rows)as $emp){
    $dob=trim($emp['dob']??'');if($dob===''||$dob==='0000-00-00')continue;
    try{$d=new DateTime($dob);if((int)$d->format('m')===$tm){$emp['_bd']=(int)$d->format('d');$emp['_bdf']=$d->format('d M');
        if($emp['_bd']===$td2)$bdays_today[]=$emp;else $bdays_up[]=$emp;}}catch(Exception $e){}
}
usort($bdays_up,fn($a,$b)=>$a['_bd']<=>$b['_bd']);
$all_bdays=array_merge($bdays_today,$bdays_up);

$new_hires=[];$ninety=(new DateTime())->modify('-90 days');
foreach(array_merge([$md_row],$all_rows)as $emp){
    $doj=trim($emp['date_of_joining']??'');if($doj===''||$doj==='0000-00-00')continue;
    try{$d=new DateTime($doj);if($d>=$ninety){$emp['_djf']=$d->format('d M Y');$new_hires[]=$emp;}}catch(Exception $e){}
}
usort($new_hires,fn($a,$b)=>strtotime($b['date_of_joining'])<=>strtotime($a['date_of_joining']));

$div_colors=['#2563eb','#059669','#d97706','#dc2626','#7c3aed','#0891b2','#be185d','#15803d','#b45309','#1d4ed8'];
$emp_json=json_encode($EMP,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP);
$hier_json=json_encode($hier,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>MPC · Admin Dashboard</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700;800&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">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --f:'DM Sans',-apple-system,sans-serif;--fm:'DM Mono',monospace;
  --sw:240px;--ink:#0a0f1e;--ink2:#1e2740;--muted:#6b7a99;--muted2:#9ba8c0;
  --bd:#e2e8f5;--bd2:#c8d4ea;--surf:#ffffff;--bg:#f4f7fc;--bg2:#eaeff8;
  --l1a:#2d4080;--l1l:#e0e7f5;--l2a:#2563eb;--l2l:#dbeafe;
  --l3a:#059669;--l3l:#d1fae5;--l4a:#d97706;--l4l:#fef3c7;
  --l5a:#dc2626;--l5l:#fee2e2;--acc:#2563eb;--acc2:#1d4ed8;
  --r:12px;--rsm:8px;
  --sh:0 1px 3px rgba(10,15,30,.06),0 4px 16px rgba(10,15,30,.07);
  --shmd:0 8px 32px rgba(10,15,30,.12);--shlg:0 24px 72px rgba(10,15,30,.18);
  --ow:160px;--og:16px;
}
html,body{height:100%;font-family:var(--f);font-size:13px;line-height:1.6;background:var(--bg);color:var(--ink);-webkit-font-smoothing:antialiased}
.layout{display:flex;min-height:100vh}
img{display:block}button{font-family:var(--f);cursor:pointer}a{text-decoration:none}
::-webkit-scrollbar{width:5px;height:5px}::-webkit-scrollbar-thumb{background:var(--bd2);border-radius:4px}

/* SIDEBAR */
.sidebar{width:var(--sw);background:linear-gradient(180deg,#0d1424,#0f1929);position:fixed;inset:0 auto 0 0;z-index:200;display:flex;flex-direction:column;overflow-y:auto;transition:transform .28s;scrollbar-width:none;border-right:1px solid rgba(255,255,255,.04)}
.sidebar.closed{transform:translateX(-100%)}.sidebar::-webkit-scrollbar{display:none}
.sb-brand{padding:20px 16px 16px;display:flex;align-items:center;gap:10px;border-bottom:1px solid rgba(255,255,255,.06);margin-bottom:6px}
.sb-logo{width:34px;height:34px;background:linear-gradient(135deg,#3b82f6,#2563eb);border-radius:9px;display:flex;align-items:center;justify-content:center;font-weight:800;color:#fff;font-size:14px;flex-shrink:0}
.sb-name{font-size:13px;font-weight:700;color:#fff}.sb-sub{font-size:8.5px;color:rgba(255,255,255,.22);letter-spacing:1.6px;text-transform:uppercase;margin-top:1px}
.ns{padding:0 8px 8px}.nl{font-size:8px;font-weight:700;letter-spacing:1.8px;text-transform:uppercase;color:rgba(255,255,255,.16);padding:10px 10px 4px}
.na,.nd{display:flex;align-items:center;gap:7px;padding:7px 10px;border-radius:8px;color:rgba(255,255,255,.44);font-size:11.5px;font-weight:500;cursor:pointer;border:none;background:none;width:100%;text-align:left;transition:all .15s}
.na:hover,.nd:hover{background:rgba(255,255,255,.07);color:rgba(255,255,255,.85)}
.na.on{background:linear-gradient(90deg,rgba(37,99,235,.35),rgba(37,99,235,.12));color:#93c5fd;border-left:2px solid #3b82f6;padding-left:8px}
.na i,.nd i{width:14px;text-align:center;font-size:10.5px;opacity:.7}.na.on i{opacity:1}
.nd .arr{margin-left:auto;font-size:7px;transition:transform .2s;opacity:.5}.nd.open .arr{transform:rotate(180deg)}
.nsub{list-style:none;overflow:hidden;max-height:0;transition:max-height .3s;padding-left:20px}.nsub.open{max-height:500px}
.nsub .na{font-size:11px;padding:5px 10px;color:rgba(255,255,255,.28)}.nsub .na:hover{color:rgba(255,255,255,.75)}.nsub .na.on{color:#93c5fd}
.sb-foot{margin-top:auto;padding:10px;border-top:1px solid rgba(255,255,255,.06)}

/* CONTENT */
.content{flex:1;margin-left:var(--sw);min-width:0;display:flex;flex-direction:column;transition:margin .28s}
.content.exp{margin-left:0}

/* TOPBAR */
.tb{height:54px;background:var(--surf);border-bottom:1px solid var(--bd);display:flex;align-items:center;gap:10px;padding:0 16px;position:sticky;top:0;z-index:100;box-shadow:0 1px 0 var(--bd)}
.hbtn{width:32px;height:32px;border-radius:8px;border:1.5px solid var(--bd);background:transparent;display:flex;align-items:center;justify-content:center;cursor:pointer;color:var(--ink2);font-size:12px;flex-shrink:0;transition:all .15s}
.hbtn:hover{background:var(--bg)}
.tb-bc{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--muted)}
.tb-cur{color:var(--ink);font-weight:700;font-size:11.5px}
.tb-sp{flex:1}

/* GLOBAL SEARCH */
.gsw{position:relative;width:280px;flex-shrink:0}
.gs-inp{width:100%;height:34px;border:1.5px solid var(--bd);border-radius:20px;padding:0 12px 0 32px;font-size:12px;font-family:var(--f);color:var(--ink);background:var(--bg);outline:none;transition:all .18s}
.gs-inp:focus{border-color:var(--acc);background:var(--surf);box-shadow:0 0 0 3px rgba(37,99,235,.1);border-radius:10px 10px 0 0}
.gsw i{position:absolute;left:11px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:10.5px;pointer-events:none}
.gs-drop{display:none;position:absolute;top:calc(100% - 1px);left:0;right:0;background:var(--surf);border:1.5px solid var(--acc);border-top:none;border-radius:0 0 10px 10px;box-shadow:var(--shmd);z-index:300;max-height:340px;overflow-y:auto}
.gsd-item{display:flex;align-items:center;gap:9px;padding:8px 12px;cursor:pointer;transition:background .12s;border-bottom:1px solid var(--bd)}
.gsd-item:last-child{border-bottom:none}.gsd-item:hover{background:#eff6ff}
.gsd-av{width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid var(--bd);flex-shrink:0}
.gsd-nm{font-size:12px;font-weight:700;color:var(--ink)}.gsd-dg{font-size:9.5px;color:var(--muted);margin-top:1px}
.gsd-lv{font-size:8.5px;font-weight:700;padding:2px 6px;border-radius:20px;margin-left:auto;flex-shrink:0;font-family:var(--fm)}
.gs-none{padding:10px 12px;font-size:11px;color:var(--muted);text-align:center}

.tb-pill{display:flex;align-items:center;gap:5px;font-size:11px;background:var(--bg);border:1.5px solid var(--bd);padding:4px 12px;border-radius:20px;color:var(--ink2);font-weight:600}
.ldot{width:7px;height:7px;border-radius:50%;background:#22c55e;flex-shrink:0;animation:pulse 2s infinite}
@keyframes pulse{0%,100%{box-shadow:0 0 0 3px rgba(34,197,94,.18)}50%{box-shadow:0 0 0 5px rgba(34,197,94,.08)}}
.tb-av{width:29px;height:29px;border-radius:50%;background:linear-gradient(135deg,#2563eb,#60a5fa);display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:800;flex-shrink:0}

/* PAGE */
.page{padding:20px;flex:1}
.ph{display:flex;align-items:flex-end;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:16px}
.ph-t{font-size:20px;font-weight:800;color:var(--ink);letter-spacing:-.6px}
.ph-s{font-size:11px;color:var(--muted);margin-top:2px}

/* STAT CARDS */
.sg{display:grid;grid-template-columns:repeat(6,1fr);gap:10px;margin-bottom:16px}
.sc{background:var(--surf);border-radius:var(--r);padding:15px 13px;box-shadow:var(--sh);border:1.5px solid var(--bd);position:relative;overflow:hidden;transition:transform .2s}
.sc:hover{transform:translateY(-3px);box-shadow:var(--shmd)}
.sc-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:9px}
.sc-ic{width:32px;height:32px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:12.5px}
.s1 .sc-ic{background:var(--l1l);color:var(--l1a)}.s2 .sc-ic{background:var(--l2l);color:var(--l2a)}
.s3 .sc-ic{background:var(--l3l);color:var(--l3a)}.s4 .sc-ic{background:var(--l4l);color:var(--l4a)}
.s5 .sc-ic{background:var(--l5l);color:var(--l5a)}.st .sc-ic{background:#ede9fe;color:#6d28d9}
.sc-tag{font-size:8px;font-weight:700;padding:2px 7px;border-radius:20px;border:1.5px solid var(--bd);color:var(--muted);font-family:var(--fm)}
.sc-n{font-size:28px;font-weight:800;letter-spacing:-.8px;color:var(--ink);line-height:1;margin-bottom:2px;font-family:var(--fm)}
.sc-l{font-size:9.5px;color:var(--muted)}
.sc-bar{height:3px;background:var(--bd);border-radius:3px;margin-top:9px;overflow:hidden}
.sc-fill{height:100%;border-radius:3px;transition:width 1s cubic-bezier(.4,0,.2,1)}
.s1 .sc-fill{background:linear-gradient(90deg,var(--l1a),#6b7fa8)}.s2 .sc-fill{background:linear-gradient(90deg,var(--l2a),#60a5fa)}
.s3 .sc-fill{background:linear-gradient(90deg,var(--l3a),#34d399)}.s4 .sc-fill{background:linear-gradient(90deg,var(--l4a),#fbbf24)}
.s5 .sc-fill{background:linear-gradient(90deg,var(--l5a),#f87171)}.st .sc-fill{background:linear-gradient(90deg,#6d28d9,#a78bfa)}

/* TABS */
.tabs{display:flex;flex-wrap:wrap;gap:2px;background:var(--surf);border:1.5px solid var(--bd);border-radius:11px;padding:3px;width:fit-content;margin-bottom:16px;box-shadow:var(--sh)}
.tab{padding:6px 13px;border:none;background:none;border-radius:8px;font-size:11px;font-weight:600;color:var(--muted);cursor:pointer;display:flex;align-items:center;gap:5px;transition:all .15s;white-space:nowrap}
.tab:hover{color:var(--ink);background:var(--bg)}.tab.on{background:var(--ink);color:#fff;box-shadow:0 2px 8px rgba(10,15,30,.2)}
.tbg{background:#ef4444;color:#fff;border-radius:20px;padding:0 5px;font-size:8px;line-height:1.6;font-family:var(--fm)}.tbg.g{background:#059669}

/* PANELS */
.panel{display:none}.panel.on{display:block;animation:fadeUp .2s ease}
@keyframes fadeUp{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
.pnl-hd{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;flex-wrap:wrap;gap:8px}
.pnl-t{font-size:15px;font-weight:700;color:var(--ink)}.pnl-m{font-size:10.5px;color:var(--muted)}

/* CARD/TABLE */
.card{background:var(--surf);border:1.5px solid var(--bd);border-radius:var(--r);box-shadow:var(--sh);overflow:hidden}
.tw{overflow-x:auto}
table{width:100%;border-collapse:collapse;font-size:12px}
thead th{background:var(--ink);color:rgba(255,255,255,.6);font-weight:600;font-size:9px;text-transform:uppercase;letter-spacing:.8px;padding:10px 13px;text-align:left;white-space:nowrap}
tbody td{padding:8px 13px;border-bottom:1px solid var(--bd);color:var(--ink2);vertical-align:middle}
tbody tr:last-child td{border-bottom:none}tbody tr:hover td{background:var(--bg)}
tbody tr.cr td{background:linear-gradient(90deg,var(--bg),var(--surf));font-weight:700;color:var(--muted);font-size:9px;text-transform:uppercase;letter-spacing:.7px;padding:5px 13px;border-top:2px solid var(--bd2)}
tfoot td{padding:9px 13px;font-weight:700;font-size:11.5px;color:var(--ink);background:var(--bg);border-top:2px solid var(--bd2)}
.eth{width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid var(--bd)}
.lb{display:inline-flex;align-items:center;padding:2px 7px;border-radius:20px;font-size:9px;font-weight:700;font-family:var(--fm)}
.lb.l1{background:var(--l1l);color:var(--l1a)}.lb.l2{background:var(--l2l);color:var(--l2a)}
.lb.l3{background:var(--l3l);color:var(--l3a)}.lb.l4{background:var(--l4l);color:var(--l4a)}.lb.l5{background:var(--l5l);color:var(--l5a)}

/* FILTER BAR */
.fb{display:flex;flex-wrap:wrap;gap:10px;align-items:flex-end;padding:12px 14px;background:var(--surf);border:1.5px solid var(--bd);border-radius:var(--r);margin-bottom:10px;box-shadow:var(--sh)}
.fg{display:flex;flex-direction:column;gap:3px}.fg.grow{flex:1;min-width:160px}
.fl{font-size:8px;font-weight:700;text-transform:uppercase;letter-spacing:.9px;color:var(--muted2)}
.fsel,.finp{height:32px;border:1.5px solid var(--bd);border-radius:var(--rsm);padding:0 10px;font-size:11.5px;font-family:var(--f);color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s;min-width:110px}
.fsel:focus,.finp:focus{border-color:var(--acc);background:var(--surf)}
.fbtn{height:32px;padding:0 12px;border:1.5px solid var(--bd);border-radius:var(--rsm);background:var(--surf);color:var(--ink2);font-size:11px;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:4px;transition:all .15s;white-space:nowrap}
.fbtn:hover{background:var(--bg)}

/* ORG CHART */
.owrap{background:var(--surf);border:1.5px solid var(--bd);border-radius:var(--r);box-shadow:var(--sh);overflow:hidden}
.otb{display:flex;align-items:center;gap:8px;padding:10px 14px;border-bottom:1px solid var(--bd);background:var(--bg);flex-wrap:wrap}
.osw{position:relative;flex:1;min-width:150px}
.osw i{position:absolute;left:9px;top:50%;transform:translateY(-50%);color:var(--muted);font-size:10px;pointer-events:none}
.osi{width:100%;height:32px;border:1.5px solid var(--bd);border-radius:var(--rsm);padding:0 9px 0 28px;font-size:11.5px;font-family:var(--f);color:var(--ink);background:var(--surf);outline:none;transition:border-color .15s}
.osi:focus{border-color:var(--acc)}.osel{height:32px;border:1.5px solid var(--bd);border-radius:var(--rsm);padding:0 9px;font-size:11.5px;font-family:var(--f);color:var(--ink);background:var(--surf);outline:none;cursor:pointer}
.oleg{padding:7px 14px;border-bottom:1px solid var(--bd);background:var(--bg);display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.oli{display:flex;align-items:center;gap:5px;font-size:9.5px;color:var(--muted);font-weight:500}
.old{width:8px;height:8px;border-radius:3px;flex-shrink:0}
.oinfo{padding:7px 14px;background:linear-gradient(90deg,rgba(37,99,235,.05),transparent);border-bottom:1px solid var(--bd);font-size:10.5px;color:var(--muted);display:flex;align-items:center;gap:6px}
.ocanv{overflow:auto;background:var(--bg);background-image:radial-gradient(circle,#c8d4e8 1.2px,transparent 1.2px);background-size:24px 24px;scrollbar-width:thin;scrollbar-color:#c8d4ea transparent}
.oinner{padding:32px 40px 56px;min-width:100%;display:inline-block}

/* ORG CARDS */
.org-level-block{margin-bottom:20px}
.org-level-label{display:flex;align-items:center;gap:8px;margin-bottom:16px;width:100%}
.org-lv-pill{font-size:9px;font-weight:700;font-family:var(--fm);padding:3px 10px;border-radius:20px;border:1.5px solid;white-space:nowrap}
.org-lv-line{flex:1;height:1px;background:var(--bd)}
.org-lv-count{font-size:9.5px;font-weight:600;color:var(--muted2);white-space:nowrap;font-family:var(--fm)}
.org-row-group{display:flex;flex-wrap:wrap;justify-content:center;gap:var(--og);margin-bottom:0;width:100%}
.org-children-block.collapsed{display:none}
.org-vline{width:2px;height:28px;background:linear-gradient(180deg,var(--bd2),var(--bd));border-radius:2px;margin:0 auto}
.oc2{background:var(--surf);border:1.5px solid var(--bd);border-radius:12px;width:var(--ow);min-width:var(--ow);padding:14px 11px 11px;display:flex;flex-direction:column;align-items:center;text-align:center;position:relative;cursor:pointer;transition:transform .2s,box-shadow .2s,border-color .2s;overflow:hidden}
.oc2::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:11px 11px 0 0}
.oc2:hover{transform:translateY(-3px);box-shadow:var(--shmd);border-color:#93b4d8}
.oc2.sel{border-color:var(--acc);box-shadow:0 0 0 3px rgba(37,99,235,.14)}
.oc2.hl{border-color:var(--acc)!important;box-shadow:0 0 0 3px rgba(37,99,235,.16)!important}
.oc2.dim{opacity:.12;pointer-events:none}
.oc2.root{background:linear-gradient(155deg,#0d1424,#1a2846)!important;border:1.5px solid rgba(255,255,255,.1)!important;width:calc(var(--ow) + 24px)!important;padding:18px 14px 14px!important}
.lc1::before{background:linear-gradient(90deg,var(--l1a),#6b7fa8)}.lc2::before{background:linear-gradient(90deg,var(--l2a),#60a5fa)}
.lc3::before{background:linear-gradient(90deg,var(--l3a),#34d399)}.lc4::before{background:linear-gradient(90deg,var(--l4a),#fbbf24)}.lc5::before{background:linear-gradient(90deg,var(--l5a),#f87171)}
.oc2-avw{position:relative;margin-bottom:9px}
.oc2-av{width:46px;height:46px;border-radius:50%;object-fit:cover;border:2px solid var(--bd)}
.oc2.root .oc2-av{width:58px;height:58px;border:3px solid rgba(255,255,255,.16)}
.oc2-lv{position:absolute;bottom:-3px;right:-5px;font-size:7.5px;font-weight:700;border-radius:20px;padding:1.5px 5px;color:#fff;border:2px solid var(--surf);font-family:var(--fm)}
.lv1b{background:var(--l1a)}.lv2b{background:var(--l2a)}.lv3b{background:var(--l3a)}.lv4b{background:var(--l4a)}.lv5b{background:var(--l5a)}
.oc2-name{font-size:11px;font-weight:700;color:var(--ink);line-height:1.3;margin-bottom:1px}
.oc2-desg{font-size:8.5px;color:var(--muted);margin-bottom:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%}
.oc2-loc{font-size:8px;color:var(--muted);display:flex;align-items:center;gap:3px;justify-content:center}
.oc2-dot{width:5px;height:5px;border-radius:50%;background:var(--l3a);flex-shrink:0}
.oc2-cnt{display:inline-flex;align-items:center;gap:3px;font-size:8.5px;font-weight:700;color:var(--l2a);background:var(--l2l);border-radius:20px;padding:2px 7px;margin-top:6px}
.oc2.root .oc2-name{color:#fff;font-size:12px}.oc2.root .oc2-desg{color:rgba(255,255,255,.5)}
.oc2.root .oc2-loc{color:rgba(255,255,255,.3)}.oc2.root .oc2-cnt{background:rgba(255,255,255,.1);color:rgba(255,255,255,.55)}
.org-expand-btn{display:inline-flex;align-items:center;gap:5px;padding:4px 12px;border-radius:20px;font-size:9.5px;font-weight:600;background:var(--surf);border:1.5px solid var(--bd2);color:var(--muted);cursor:pointer;transition:all .15s;margin:4px auto 16px;font-family:var(--f)}
.org-expand-btn:hover{background:var(--bg);color:var(--ink)}

/* LEVEL VIEW */
.lv-view{padding:16px}
.lv-sec{margin-bottom:24px}
.lv-hd{display:flex;align-items:center;gap:9px;margin-bottom:12px;padding-bottom:9px;border-bottom:2px solid var(--bd)}
.lv-bl{width:42px;height:42px;border-radius:10px;font-size:15px;font-weight:800;display:flex;align-items:center;justify-content:center;flex-shrink:0;font-family:var(--fm)}
.ll1 .lv-bl{background:var(--l1l);color:var(--l1a)}.ll2 .lv-bl{background:var(--l2l);color:var(--l2a)}
.ll3 .lv-bl{background:var(--l3l);color:var(--l3a)}.ll4 .lv-bl{background:var(--l4l);color:var(--l4a)}.ll5 .lv-bl{background:var(--l5l);color:var(--l5a)}
.lv-st{font-size:13.5px;font-weight:700;color:var(--ink)}.lv-sm{font-size:10.5px;color:var(--muted)}
.lv-num{margin-left:auto;font-size:22px;font-weight:800;color:var(--ink);font-family:var(--fm)}
.lv-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:9px}
.lv-card{background:var(--surf);border:1.5px solid var(--bd);border-radius:var(--r);padding:14px;display:flex;flex-direction:column;align-items:center;text-align:center;cursor:pointer;transition:all .2s;position:relative;overflow:hidden}
.lv-card::before{content:'';position:absolute;top:0;left:0;right:0;height:3px}
.ll1 .lv-card::before{background:linear-gradient(90deg,var(--l1a),#6b7fa8)}.ll2 .lv-card::before{background:linear-gradient(90deg,var(--l2a),#60a5fa)}
.ll3 .lv-card::before{background:linear-gradient(90deg,var(--l3a),#34d399)}.ll4 .lv-card::before{background:linear-gradient(90deg,var(--l4a),#fbbf24)}.ll5 .lv-card::before{background:linear-gradient(90deg,var(--l5a),#f87171)}
.lv-card:hover{transform:translateY(-2px);box-shadow:var(--shmd)}
.lv-av{width:52px;height:52px;border-radius:50%;object-fit:cover;border:2.5px solid var(--bd);margin-bottom:9px}
.lv-nm{font-size:12px;font-weight:700;color:var(--ink);margin-bottom:2px}
.lv-dg{font-size:9.5px;color:var(--muted);margin-bottom:6px}
.lv-tg{font-size:8.5px;padding:2px 7px;border-radius:20px;font-weight:600;margin:1px}
.tgloc{background:#f1f5f9;color:var(--muted)}.tgdiv{background:#ede9fe;color:#6d28d9}
.lv-rep{display:flex;align-items:center;gap:3px;margin-top:7px;font-size:9px;font-weight:700;color:var(--l2a);background:var(--l2l);padding:2px 8px;border-radius:20px}

/* DEPT */
.dl{display:grid;grid-template-columns:220px 1fr;gap:12px;align-items:start}
.dsb{background:var(--surf);border:1.5px solid var(--bd);border-radius:var(--r);box-shadow:var(--sh);overflow:hidden;position:sticky;top:64px}
.dsbhd{padding:10px 13px;background:var(--ink);color:rgba(255,255,255,.6);font-size:8.5px;font-weight:700;text-transform:uppercase;letter-spacing:.9px}
.ditem{display:flex;align-items:center;gap:7px;padding:9px 13px;cursor:pointer;border-bottom:1px solid var(--bd);font-size:11.5px;color:var(--ink2);transition:background .15s}
.ditem:last-child{border-bottom:none}.ditem:hover{background:var(--bg)}.ditem.on{background:#eff6ff;color:#1d4ed8;font-weight:700}
.ddot{width:8px;height:8px;border-radius:3px;flex-shrink:0}
.dcnt{margin-left:auto;background:var(--bg);color:var(--muted);font-size:8.5px;font-weight:700;padding:2px 7px;border-radius:20px;border:1.5px solid var(--bd);font-family:var(--fm)}
.ditem.on .dcnt{background:#dbeafe;color:#1d4ed8;border-color:#bfdbfe}
.dpanel{display:none}.dpanel.on{display:block;animation:fadeUp .2s ease}
.dhdr{padding:12px 15px;border-radius:var(--r);margin-bottom:12px;color:#fff;display:flex;align-items:center;gap:10px}
.dhico{width:40px;height:40px;border-radius:9px;background:rgba(255,255,255,.15);display:flex;align-items:center;justify-content:center;font-size:16px}
.dhname{font-size:14.5px;font-weight:700}.dhmeta{font-size:10px;opacity:.65;display:flex;gap:9px;flex-wrap:wrap;margin-top:2px}
.dtree{background:var(--surf);border:1.5px solid var(--bd);border-radius:var(--r);box-shadow:var(--sh);overflow:auto;padding:24px 16px 32px;background-image:radial-gradient(circle,#edf1f8 1px,transparent 1px);background-size:22px 22px;max-height:66vh;scrollbar-width:thin}
.dept-org-row{display:flex;flex-wrap:wrap;justify-content:center;gap:12px;margin-bottom:8px}

/* DETAIL PANEL */
.dovl{position:fixed;inset:0;background:rgba(10,15,30,.4);z-index:500;opacity:0;pointer-events:none;transition:opacity .24s;backdrop-filter:blur(4px)}
.dovl.on{opacity:1;pointer-events:all}
.dpan{position:fixed;top:0;right:-480px;bottom:0;width:470px;background:var(--surf);z-index:501;overflow-y:auto;box-shadow:var(--shlg);border-left:1.5px solid var(--bd);transition:right .3s cubic-bezier(.4,0,.2,1);display:flex;flex-direction:column}
.dpan.open{right:0}
.dphd{height:90px;position:relative;flex-shrink:0}
.dphd-pat{position:absolute;inset:0;opacity:.06;background-image:repeating-linear-gradient(45deg,#fff 0,#fff 1px,transparent 0,transparent 50%);background-size:12px 12px}
.dp-close{position:absolute;top:10px;right:10px;width:28px;height:28px;border-radius:50%;background:rgba(255,255,255,.16);border:none;cursor:pointer;color:rgba(255,255,255,.85);font-size:11px;display:flex;align-items:center;justify-content:center;transition:background .15s;z-index:2}
.dp-close:hover{background:rgba(255,255,255,.3)}
.dp-avw{position:absolute;bottom:-26px;left:18px;z-index:2}
.dp-av{width:60px;height:60px;border-radius:50%;object-fit:cover;border:3.5px solid var(--surf);box-shadow:0 4px 14px rgba(10,15,30,.18)}
.dp-lv{position:absolute;bottom:2px;right:-4px;font-size:7.5px;font-weight:700;padding:2px 5px;border-radius:20px;color:#fff;border:2px solid var(--surf);font-family:var(--fm)}
.dpinfo{padding:36px 18px 14px;border-bottom:1px solid var(--bd)}
.dp-nm{font-size:17px;font-weight:800;color:var(--ink);margin-bottom:2px}.dp-dg{font-size:11.5px;color:var(--muted);margin-bottom:8px}
.dp-tags{display:flex;flex-wrap:wrap;gap:4px}
.dp-tag{display:inline-flex;align-items:center;gap:3px;font-size:9.5px;font-weight:600;padding:3px 8px;border-radius:20px;background:var(--bg);color:var(--ink2);border:1.5px solid var(--bd)}
.dp-tag i{opacity:.6;font-size:8.5px}

/* DETAIL TABS */
.dp-tabs{display:flex;gap:0;border-bottom:2px solid var(--bd);flex-shrink:0;padding:0 16px}
.dp-tab{padding:9px 14px;font-size:11.5px;font-weight:600;color:var(--muted);cursor:pointer;border:none;background:none;border-bottom:2px solid transparent;margin-bottom:-2px;transition:all .15s;font-family:var(--f);display:flex;align-items:center;gap:5px}
.dp-tab:hover{color:var(--ink)}.dp-tab.on{color:var(--acc);border-bottom-color:var(--acc)}
.dp-panel{display:none;padding:16px}.dp-panel.on{display:block}
.dbody{flex:1;display:flex;flex-direction:column}

/* DETAIL INFO SECTIONS */
.ds-sec{margin-bottom:16px}
.ds-t{font-size:8.5px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:var(--muted);margin-bottom:9px;display:flex;align-items:center;gap:6px}
.ds-t::after{content:'';flex:1;height:1px;background:var(--bd)}
.dig{display:grid;grid-template-columns:1fr 1fr;gap:7px}
.di{background:var(--bg);border-radius:9px;padding:9px 11px;border:1.5px solid var(--bd)}
.di-l{font-size:8px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:var(--muted);margin-bottom:3px}
.di-l i{font-size:9px;opacity:.7;margin-right:2px}
.di-v{font-size:11.5px;font-weight:600;color:var(--ink)}
.ci,.ri{display:flex;align-items:center;gap:9px;padding:8px 10px;background:var(--bg);border-radius:9px;cursor:pointer;transition:all .15s;border:1.5px solid transparent;margin-bottom:5px}
.ci:hover,.ri:hover{background:#eff6ff;border-color:#bfdbfe}
.ci-av,.ri-av{width:34px;height:34px;border-radius:50%;object-fit:cover;border:2px solid var(--bd);flex-shrink:0}
.ci-nm,.ri-nm{font-size:11.5px;font-weight:700;color:var(--ink)}.ci-rl,.ri-rl{font-size:9px;color:var(--muted)}
.ci-bd{font-size:7.5px;font-weight:700;padding:2px 6px;border-radius:20px;flex-shrink:0;margin-left:auto;font-family:var(--fm)}
.carrow{display:flex;align-items:center;justify-content:center;padding:2px 0;color:var(--bd2);font-size:9px}
.nodata{font-size:11px;color:var(--muted);padding:7px 10px;font-style:italic;background:var(--bg);border-radius:8px;border:1.5px solid var(--bd)}
.rqg{display:grid;grid-template-columns:1fr 1fr;gap:5px;margin-bottom:5px}
.rqc{background:var(--bg);border:1.5px solid var(--bd);border-radius:9px;padding:7px 9px;display:flex;align-items:center;gap:7px;cursor:pointer;transition:all .15s}
.rqc:hover{background:#eff6ff;border-color:#bfdbfe}
.rqav{width:28px;height:28px;border-radius:50%;object-fit:cover;border:2px solid var(--bd);flex-shrink:0}
.rqnm{font-size:10px;font-weight:700;color:var(--ink);line-height:1.2}.rqdg{font-size:8.5px;color:var(--muted)}
.sab{width:100%;padding:7px;border:1.5px dashed #bfdbfe;background:none;border-radius:9px;color:var(--l2a);font-size:10.5px;font-weight:600;cursor:pointer;font-family:var(--f);transition:all .15s;display:flex;align-items:center;justify-content:center;gap:5px;margin-top:2px}
.sab:hover{background:#eff6ff}

/* TODAY'S REPORT SECTION */
.today-report-wrap{margin-bottom:0}
.today-date-banner{display:flex;align-items:center;gap:8px;padding:9px 12px;background:linear-gradient(90deg,rgba(37,99,235,.08),rgba(37,99,235,.02));border:1.5px solid rgba(37,99,235,.2);border-radius:10px;margin-bottom:12px}
.today-date-banner i{color:var(--acc);font-size:11px}
.today-date-text{font-size:11px;font-weight:700;color:var(--acc)}
.today-date-sub{font-size:9.5px;color:var(--muted);margin-left:auto}
.rep-exists-badge{display:inline-flex;align-items:center;gap:4px;font-size:9px;font-weight:700;padding:2px 8px;border-radius:20px;background:#d1fae5;color:#065f46;border:1px solid #a7f3d0;margin-left:8px}
.rep-missing-badge{display:inline-flex;align-items:center;gap:4px;font-size:9px;font-weight:700;padding:2px 8px;border-radius:20px;background:#fee2e2;color:#991b1b;border:1px solid #fca5a5;margin-left:8px}

/* TODAY'S REPORT CARD */
.rep-card{background:var(--bg);border:1.5px solid var(--bd);border-radius:10px;padding:12px 14px;margin-bottom:10px;transition:border-color .15s}
.rep-card:hover{border-color:var(--bd2)}
.rep-top{display:flex;align-items:center;gap:7px;margin-bottom:8px;flex-wrap:wrap}
.rep-date{font-size:11px;font-weight:700;color:var(--ink);font-family:var(--fm)}
.rep-loc{font-size:9.5px;background:#f1f5f9;color:var(--muted);padding:2px 7px;border-radius:20px;display:flex;align-items:center;gap:3px}
.rep-stat{font-size:8.5px;font-weight:700;padding:2px 7px;border-radius:20px;margin-left:auto;font-family:var(--fm)}
.stat-submitted{background:#dbeafe;color:#1d4ed8}.stat-approved{background:#d1fae5;color:#065f46}
.stat-reviewed{background:#fef3c7;color:#92400e}.stat-pending{background:#fee2e2;color:#991b1b}
.stat-default{background:#f1f5f9;color:var(--muted)}
.rep-body{font-size:10.5px;color:var(--ink2);line-height:1.5}
.rep-row{display:flex;gap:6px;margin-bottom:5px}
.rep-label{font-size:8.5px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;color:var(--muted);width:70px;flex-shrink:0;padding-top:1px}
.rep-val{flex:1;font-size:10.5px;color:var(--ink2)}
.login-badge{display:inline-flex;align-items:center;gap:4px;font-size:9px;padding:2px 7px;border-radius:20px;font-family:var(--fm)}
.login-in{background:#d1fae5;color:#065f46}.login-out{background:#fee2e2;color:#991b1b}
.rep-approval{font-size:9px;padding:2px 6px;border-radius:20px;font-weight:700;font-family:var(--fm)}
.appr-approved{background:#d1fae5;color:#065f46}.appr-pending{background:#fef3c7;color:#92400e}.appr-rejected{background:#fee2e2;color:#991b1b}

/* ADD/EDIT FORM */
.rep-form-wrap{border:1.5px solid var(--bd);border-radius:12px;overflow:hidden;margin-top:2px}
.rep-form-header{display:flex;align-items:center;justify-content:space-between;padding:10px 14px;background:var(--ink);cursor:pointer;user-select:none}
.rep-form-title{font-size:12px;font-weight:700;color:#fff;display:flex;align-items:center;gap:7px}
.rep-form-toggle-icon{color:rgba(255,255,255,.5);font-size:10px;transition:transform .2s}
.rep-form-header.open .rep-form-toggle-icon{transform:rotate(180deg)}
.rep-form-body{display:none;padding:14px;background:var(--surf)}
.rep-form-body.open{display:block;animation:fadeUp .18s ease}
.rff{display:flex;flex-direction:column;gap:3px;margin-bottom:10px}
.rfl{font-size:8px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);margin-bottom:2px}
.rfi,.rfsel,.rft{width:100%;border:1.5px solid var(--bd);border-radius:8px;padding:7px 10px;font-size:12px;font-family:var(--f);color:var(--ink);background:var(--bg);outline:none;transition:border-color .15s}
.rfi:focus,.rfsel:focus,.rft:focus{border-color:var(--acc);background:var(--surf);box-shadow:0 0 0 3px rgba(37,99,235,.08)}
.rft{resize:vertical;min-height:60px;line-height:1.5}
.rf-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.rf-grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px}
.rep-form-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:12px;padding-top:12px;border-top:1px solid var(--bd)}
.rep-btn-save{height:34px;padding:0 18px;background:linear-gradient(135deg,var(--acc),var(--acc2));color:#fff;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;font-family:var(--f);display:flex;align-items:center;gap:6px;transition:all .15s;box-shadow:0 2px 8px rgba(37,99,235,.25)}
.rep-btn-save:hover{transform:translateY(-1px);box-shadow:0 4px 14px rgba(37,99,235,.35)}
.rep-btn-save:disabled{opacity:.6;cursor:not-allowed;transform:none}
.rep-btn-cancel{height:34px;padding:0 14px;background:transparent;color:var(--muted);border:1.5px solid var(--bd);border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;font-family:var(--f);transition:all .15s}
.rep-btn-cancel:hover{background:var(--bg);color:var(--ink)}
.rep-toast{display:none;padding:9px 13px;border-radius:9px;font-size:11.5px;font-weight:600;margin-bottom:10px;display:flex;align-items:center;gap:7px}
.rep-toast.success{background:#d1fae5;color:#065f46;border:1.5px solid #a7f3d0}
.rep-toast.error{background:#fee2e2;color:#991b1b;border:1.5px solid #fca5a5}
.rep-toast.hidden{display:none!important}

/* PEOPLE CARDS */
.pg{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:9px}
.pcard{background:var(--surf);border:1.5px solid var(--bd);border-radius:var(--r);padding:13px;display:flex;align-items:center;gap:10px;box-shadow:var(--sh);transition:all .2s;position:relative;overflow:hidden;cursor:pointer}
.pcard:hover{box-shadow:var(--shmd);transform:translateY(-2px)}.pcard::before{content:'';position:absolute;top:0;left:0;right:0;height:3px}
.bt::before{background:linear-gradient(90deg,#f59e0b,#ef4444)}.bu::before{background:linear-gradient(90deg,#a78bfa,#6366f1)}.nh::before{background:linear-gradient(90deg,#10b981,#06b6d4)}
.pav{width:44px;height:44px;border-radius:50%;object-fit:cover;border:2px solid var(--bd);flex-shrink:0}
.pnm{font-size:12px;font-weight:700;color:var(--ink);margin-bottom:1px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.pro{font-size:9px;color:var(--muted);margin-bottom:5px}
.pbg{display:inline-flex;align-items:center;gap:3px;font-size:8.5px;font-weight:600;padding:2px 7px;border-radius:20px}
.btoday{background:#fef3c7;color:#b45309}.bup{background:#ede9fe;color:#7c3aed}.bnh{background:#d1fae5;color:#059669}
.empty{text-align:center;padding:48px 22px;color:var(--muted)}
.empty i{font-size:30px;margin-bottom:10px;opacity:.18;display:block}
.subs{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--muted);margin:14px 0 9px;display:flex;align-items:center;gap:6px}
.subs::after{content:'';flex:1;height:1px;background:var(--bd)}
.um{margin-top:32px;padding:18px;background:#fff9f9;border:2px dashed #fca5a5;border-radius:var(--r)}
.um-t{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:var(--l5a);margin-bottom:10px;display:flex;align-items:center;gap:5px}
.um-g{display:flex;flex-wrap:wrap;gap:9px;justify-content:center}

/* RESPONSIVE */
@media(max-width:1280px){.sg{grid-template-columns:repeat(3,1fr)}}
@media(max-width:1024px){.dl{grid-template-columns:1fr}.dsb{position:static}}
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}.sidebar:not(.closed){transform:none}
  .content{margin-left:0}.sg{grid-template-columns:repeat(2,1fr)}.page{padding:12px}
  .dpan{width:100%;right:-100%}.gsw{width:180px}
  :root{--ow:140px;--og:10px}
}
@media(max-width:480px){.sg{grid-template-columns:1fr 1fr}.gsw{width:140px}}
</style>
</head>
<body>
<div class="layout">

<!-- SIDEBAR -->
<nav class="sidebar" id="sidebar">
  <div class="sb-brand">
    <div class="sb-logo">M</div>
    <div><div class="sb-name">MPC Admin</div><div class="sb-sub">People Portal</div></div>
  </div>
  <div class="ns">
    <div class="nl">Overview</div>
    <ul style="list-style:none"><li><a href="dashboard_admin.php" class="na on"><i class="fas fa-sitemap"></i> Organisation Chart</a></li></ul>
    <div class="nl">Modules</div>
    <ul style="list-style:none">
      <li>
        <button class="nd" onclick="toggleMenu(this)"><i class="fas fa-folder-open"></i> DAP<i class="fas fa-chevron-down arr"></i></button>
        <ul class="nsub">
          <li><a href="manage_users.php" class="na"><i class="fas fa-users"></i> Employee Details</a></li>
          <li><a href="manage_documents.php" class="na"><i class="fas fa-file-alt"></i> Policies</a></li>
          <li><a href="digital.php" class="na"><i class="fas fa-check-circle"></i> Acceptance Confirmed</a></li>
          <li><a href="employee_manager_assignment.php" class="na"><i class="fas fa-user-check"></i> Assigned Employee</a></li>
          <li><a href="change_password.php" class="na"><i class="fas fa-key"></i> Change Password</a></li>
        </ul>
      </li>
      <li>
        <button class="nd" onclick="toggleMenu(this)"><i class="fas fa-calendar-alt"></i> CAB<i class="fas fa-chevron-down arr"></i></button>
        <ul class="nsub">
          <li><a href="attendance.php" class="na"><i class="fas fa-clock"></i> Attendance</a></li>
          <li><a href="payroll.php" class="na"><i class="fas fa-money-bill"></i> Payroll</a></li>
          <li><a href="mobile_attendance.php" class="na"><i class="fas fa-mobile-alt"></i> Daily Report</a></li>
          <li><a href="task_dashboard.php" class="na"><i class="fas fa-tasks"></i> Tasks</a></li>
          <li><a href="daily_reports_dashboard.php" class="na"><i class="fas fa-chart-line"></i> Daily Reports</a></li>
          <li><a href="company_holidays.php" class="na"><i class="fas fa-star"></i> Holidays</a></li>
          <li><a href="hr_approval_salary.php" class="na"><i class="fas fa-hand-holding-usd"></i> Advance</a></li>
          <li><a href="expense_admin_dashboard.php" class="na"><i class="fas fa-receipt"></i> Expenses</a></li>
          <li><a href="leave_dashboard.php" class="na"><i class="fas fa-umbrella-beach"></i> Leave</a></li>
          <li><a href="grievance_dashboard.php" class="na"><i class="fas fa-comment-alt"></i> Grievance</a></li>
        </ul>
      </li>
      <li>
        <button class="nd" onclick="toggleMenu(this)"><i class="fas fa-calendar-alt"></i> DOT<i class="fas fa-chevron-down arr"></i></button>
        <ul class="nsub">
         <li><a href="task_dashboard.php" class="na"><i class="fas fa-tasks"></i> Tasks</a></li>
          <li><a href="daily_reports_dashboard.php" class="na"><i class="fas fa-chart-line"></i> Daily Reports</a></li>
          
        </ul>
      </li>
      <li>
        <button class="nd" onclick="toggleMenu(this)"><i class="fas fa-user-tie"></i> PEP<i class="fas fa-chevron-down arr"></i></button>
        <ul class="nsub">
          <li><a href="individual_rr.php" class="na"><i class="fas fa-trophy"></i> R &amp; R</a></li>
          <li><a href="hr_kra_review.php" class="na"><i class="fas fa-bullseye"></i> KRA Review</a></li>
          <li><a href="kra_assignment.php" class="na"><i class="fas fa-trophy"></i> KRA Assign</a></li>
          <li><a href="kpi_assignment.php" class="na"><i class="fas fa-bullseye"></i> KPI Assgn</a></li>
          <li><a href="https://pep.mypeopleconnect.app/" class="na" target="_blank"><i class="fas fa-external-link-alt"></i> PEP Login</a></li>
        </ul>
      </li>
      <li>
        <button class="nd" onclick="toggleMenu(this)"><i class="fas fa-book-open"></i> L&amp;D<i class="fas fa-chevron-down arr"></i></button>
        <ul class="nsub">
          <li><a href="incident_employee.php" class="na"><i class="fas fa-exclamation-triangle"></i> Incidents</a></li>
          <li><a href="training_dashboard.php" class="na"><i class="fas fa-chalkboard-teacher"></i> Training</a></li>
          <li><a href="rr.php" class="na"><i class="fas fa-award"></i> Rewards</a></li>
        </ul>
      </li>
      <li>
        <button class="nd" onclick="toggleMenu(this)"><i class="fas fa-star"></i> AAA<i class="fas fa-chevron-down arr"></i></button>
        <ul class="nsub">
          <li><a href="employee_tiy.php" class="na"><i class="fas fa-user-check"></i> Employee TIY</a></li>
          <li><a href="superadmin_notifications.php" class="na"><i class="fas fa-bell"></i> Notifications</a></li>
        </ul>
      </li>
    </ul>
  </div>
  <div class="sb-foot">
    <a href="logout.php" class="na" style="color:#f87171"><i class="fas fa-sign-out-alt"></i> Logout</a>
  </div>
</nav>

<!-- DETAIL PANEL OVERLAY -->
<div class="dovl" id="dovl" onclick="closeDetail()"></div>
<div class="dpan" id="dpan">
  <div class="dphd" id="dphd">
    <div class="dphd-pat"></div>
    <button class="dp-close" onclick="closeDetail()"><i class="fas fa-times"></i></button>
    <div class="dp-avw"><img id="dpAv" src="" alt="" class="dp-av"><span id="dpLvB" class="dp-lv"></span></div>
  </div>
  <div class="dpinfo">
    <div id="dpNm" class="dp-nm"></div>
    <div id="dpDg" class="dp-dg"></div>
    <div class="dp-tags">
      <span class="dp-tag"><i class="fas fa-layer-group"></i><span id="dpDiv">—</span></span>
      <span class="dp-tag"><i class="fas fa-map-marker-alt"></i><span id="dpLoc">—</span></span>
      <span class="dp-tag"><i class="fas fa-signal"></i><span id="dpLvT">—</span></span>
    </div>
  </div>
  <div class="dp-tabs">
    <button class="dp-tab on" onclick="switchDpTab(this,'dpt-info')"><i class="fas fa-id-card"></i> Profile</button>
    <button class="dp-tab" onclick="switchDpTab(this,'dpt-reports')"><i class="fas fa-clipboard-list"></i> Today's Report</button>
  </div>
  <div class="dbody">
    <!-- Profile tab -->
    <div class="dp-panel on" id="dpt-info">
      <div class="ds-sec">
        <div class="ds-t">Employee Info</div>
        <div class="dig">
          <div class="di"><div class="di-l"><i class="fas fa-building"></i> Company</div><div class="di-v" id="dpCo">—</div></div>
          <div class="di"><div class="di-l"><i class="fas fa-id-badge"></i> Employee ID</div><div class="di-v" id="dpId">—</div></div>
          <div class="di"><div class="di-l"><i class="fas fa-calendar-check"></i> Joined</div><div class="di-v" id="dpDoj">—</div></div>
          <div class="di"><div class="di-l"><i class="fas fa-birthday-cake"></i> Birthday</div><div class="di-v" id="dpDob">—</div></div>
        </div>
      </div>
      <div class="ds-sec"><div class="ds-t">Reporting Manager</div><div id="dpChain"></div></div>
      <div class="ds-sec">
        <div class="ds-t">Direct Reportees <span id="dpRcnt" style="font-weight:800;color:var(--l2a);font-size:12px;margin-left:4px"></span></div>
        <div id="dpReps"></div>
      </div>
    </div>

    <!-- Today's Report tab -->
    <div class="dp-panel" id="dpt-reports">
      <!-- Date banner -->
      <div class="today-date-banner">
        <i class="fas fa-calendar-day"></i>
        <span class="today-date-text">Today — <?php echo date('d M Y'); ?></span>
        <span class="today-date-sub" id="repStatusBadge"></span>
      </div>

      <!-- Toast notification -->
      <div class="rep-toast hidden" id="repToast"></div>

      <!-- Existing today report display -->
      <div id="dpReports"></div>

      <!-- Add / Edit Form -->
      <div class="rep-form-wrap" id="repFormWrap">
        <div class="rep-form-header" id="repFormToggle" onclick="toggleRepForm()">
          <div class="rep-form-title"><i class="fas fa-plus-circle"></i><span id="repFormTitle">Add Today's Report</span></div>
          <i class="fas fa-chevron-down rep-form-toggle-icon" id="repFormIcon"></i>
        </div>
        <div class="rep-form-body" id="repFormBody">
          <input type="hidden" id="rfUid" value="">

          <div class="rf-grid">
            <div class="rff">
              <label class="rfl"><i class="fas fa-map-marker-alt"></i> Location</label>
              <input type="text" class="rfi" id="rfLocation" placeholder="e.g. Karur, Trichy…">
            </div>
            <div class="rff">
              <label class="rfl"><i class="fas fa-tag"></i> Location Type</label>
              <select class="rfsel" id="rfLocType">
                <option value="">Select…</option>
                <option value="office">Office</option>
                <option value="field">Field</option>
                <option value="remote">Remote</option>
                <option value="wfh">WFH</option>
                <option value="travel">Travel</option>
              </select>
            </div>
          </div>

          <div class="rff">
            <label class="rfl"><i class="fas fa-user-tie"></i> Client Name</label>
            <input type="text" class="rfi" id="rfClient" placeholder="Client / Company name">
          </div>

          <div class="rf-grid-3">
            <div class="rff">
              <label class="rfl"><i class="fas fa-check-circle"></i> Hits</label>
              <input type="number" class="rfi" id="rfHits" placeholder="0" min="0">
            </div>
            <div class="rff">
              <label class="rfl"><i class="fas fa-times-circle"></i> Missed</label>
              <input type="number" class="rfi" id="rfMissed" placeholder="0" min="0">
            </div>
            <div class="rff">
              <label class="rfl"><i class="fas fa-forward"></i> Carry Fwd</label>
              <input type="number" class="rfi" id="rfCarry" placeholder="0" min="0">
            </div>
          </div>

          <div class="rff">
            <label class="rfl"><i class="fas fa-align-left"></i> Daily Summary</label>
            <textarea class="rft" id="rfSummary" rows="3" placeholder="Brief summary of today's activities…"></textarea>
          </div>

          <div class="rff">
            <label class="rfl"><i class="fas fa-moon"></i> End of Day Report</label>
            <textarea class="rft" id="rfEod" rows="3" placeholder="End of day observations, outcomes…"></textarea>
          </div>

          <div class="rff">
            <label class="rfl"><i class="fas fa-file-alt"></i> Full Report</label>
            <textarea class="rft" id="rfFull" rows="4" placeholder="Detailed full report…"></textarea>
          </div>

          <div class="rf-grid">
            <div class="rff">
              <label class="rfl"><i class="fas fa-sign-in-alt"></i> Login Time</label>
              <input type="datetime-local" class="rfi" id="rfLogin">
            </div>
            <div class="rff">
              <label class="rfl"><i class="fas fa-sign-out-alt"></i> Logout Time</label>
              <input type="datetime-local" class="rfi" id="rfLogout">
            </div>
          </div>

          <div class="rf-grid">
            <div class="rff">
              <label class="rfl"><i class="fas fa-flag"></i> Report Status</label>
              <select class="rfsel" id="rfStatus">
                <option value="submitted">Submitted</option>
                <option value="pending">Pending</option>
                <option value="reviewed">Reviewed</option>
                <option value="approved">Approved</option>
              </select>
            </div>
            <div class="rff">
              <label class="rfl"><i class="fas fa-thumbs-up"></i> Approval Status</label>
              <select class="rfsel" id="rfApproval">
                <option value="pending">Pending</option>
                <option value="approved">Approved</option>
                <option value="rejected">Rejected</option>
              </select>
            </div>
          </div>

          <div class="rff">
            <label class="rfl"><i class="fas fa-comment"></i> Manager Remarks</label>
            <textarea class="rft" id="rfRemarks" rows="2" placeholder="Manager's comments or feedback…"></textarea>
          </div>

          <div class="rep-form-actions">
            <button class="rep-btn-cancel" onclick="toggleRepForm()">Cancel</button>
            <button class="rep-btn-save" id="repSaveBtn" onclick="saveReport()">
              <i class="fas fa-save"></i> <span id="repSaveTxt">Save Report</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- MAIN CONTENT -->
<div class="content" id="content">
  <div class="tb">
    <button class="hbtn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="tb-bc">
      <span>Organisation</span>
      <span style="color:var(--bd2);font-size:8.5px;margin:0 2px"><i class="fas fa-chevron-right"></i></span>
      <span class="tb-cur">Overview</span>
    </div>
    <div class="tb-sp"></div>

    <!-- GLOBAL EMPLOYEE SEARCH -->
    <div class="gsw" id="gswrap">
      <i class="fas fa-search"></i>
      <input type="text" id="globalSearch" class="gs-inp" placeholder="Search employee…" autocomplete="off" oninput="gsearch(this.value)">
      <div class="gs-drop" id="gsDrop"></div>
    </div>

    <div class="tb-pill"><span class="ldot"></span><strong style="font-family:var(--fm)"><?php echo $strength['Total']['Total']; ?></strong>&nbsp;Active</div>
    <div style="display:flex;align-items:center;gap:7px;font-size:11.5px;color:var(--ink2);font-weight:600">
      <div class="tb-av"><?php echo strtoupper(substr($username?:'A',0,1)); ?></div>
      <?php echo h($username?:'Admin'); ?>
    </div>
  </div>

  <div class="page">
    <div class="ph">
      <div>
        <div class="ph-t">Organisation Overview</div>
        <div class="ph-s">Workforce structure · Headcount analytics · Reporting hierarchy</div>
      </div>
    </div>

    <!-- STAT CARDS -->
    <?php
    $tot=max($strength['Total']['Total'],1);
    $lvs=[['s1','L1','shield-alt','Executive'],['s2','L2','user-tie','Senior Mgmt'],['s3','L3','user','Management'],['s4','L4','user-friends','Team Leads'],['s5','L5','users','Staff'],['st','Total','building','Grand Total']];
    ?>
    <div class="sg">
      <?php foreach($lvs as [$cls,$lbl,$ico,$sub]):
        $n=$strength[$lbl]['Total']??0;$pct=round($n/$tot*100); ?>
      <div class="sc <?php echo $cls; ?>">
        <div class="sc-top"><div class="sc-ic"><i class="fas fa-<?php echo $ico; ?>"></i></div><span class="sc-tag"><?php echo $lbl; ?></span></div>
        <div class="sc-n"><?php echo $n; ?></div>
        <div class="sc-l"><?php echo $sub; ?></div>
        <div class="sc-bar"><div class="sc-fill" data-w="<?php echo $pct; ?>%"></div></div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- TABS -->
    <div class="tabs">
      <button class="tab on" data-p="p-org" onclick="switchTab(this)"><i class="fas fa-sitemap"></i> Org Chart</button>
      <button class="tab" data-p="p-level" onclick="switchTab(this)"><i class="fas fa-layer-group"></i> Levels</button>
      <button class="tab" data-p="p-dept" onclick="switchTab(this)"><i class="fas fa-th-large"></i> Departments</button>
      <button class="tab" data-p="p-strength" onclick="switchTab(this)"><i class="fas fa-chart-bar"></i> Strength</button>
      <button class="tab" data-p="p-emps" onclick="switchTab(this)"><i class="fas fa-users"></i> Employees</button>
      <button class="tab" data-p="p-bdays" onclick="switchTab(this)"><i class="fas fa-birthday-cake"></i> Birthdays<?php if(!empty($bdays_today)):?><span class="tbg"><?php echo count($bdays_today);?></span><?php endif;?></button>
      <button class="tab" data-p="p-hires" onclick="switchTab(this)"><i class="fas fa-user-plus"></i> New Hires<?php if(!empty($new_hires)):?><span class="tbg g"><?php echo count($new_hires);?></span><?php endif;?></button>
    </div>

    <!-- ORG CHART -->
    <div class="panel on" id="p-org">
      <div class="pnl-hd"><div class="pnl-t">Organisation Hierarchy</div><div class="pnl-m">Max 6 per row · Click card for profile</div></div>
      <div class="owrap">
        <div class="otb">
          <div class="osw"><i class="fas fa-search"></i><input type="text" class="osi" id="orgQ" placeholder="Search name, designation, division…" oninput="orgFilter()"></div>
          <select class="osel" id="orgLv" onchange="orgFilter()"><option value="">All Levels</option><option>L1</option><option>L2</option><option>L3</option><option>L4</option><option>L5</option></select>
          <select class="osel" id="orgDv" onchange="orgFilter()"><option value="">All Divisions</option><?php foreach($all_divs as $d):?><option><?php echo h($d);?></option><?php endforeach;?></select>
          <select class="osel" id="orgLoc" onchange="orgFilter()"><option value="">All Locations</option><?php foreach($loc_labels as $ll):?><option><?php echo h($ll);?></option><?php endforeach;?></select>
          <button class="fbtn" onclick="orgCollapseAll()"><i class="fas fa-compress-alt"></i> Collapse</button>
          <button class="fbtn" onclick="orgExpandAll()"><i class="fas fa-expand-alt"></i> Expand</button>
          <button class="fbtn" onclick="orgReset()"><i class="fas fa-times"></i> Clear</button>
        </div>
        <div class="oleg">
          <?php foreach(['L1'=>['var(--l1a)','Executive'],'L2'=>['var(--l2a)','Senior Mgmt'],'L3'=>['var(--l3a)','Management'],'L4'=>['var(--l4a)','Team Leads'],'L5'=>['var(--l5a)','Staff']] as $l=>[$c,$label]):?>
          <span class="oli"><span class="old" style="background:<?php echo $c;?>"></span><?php echo $l;?> <span style="opacity:.6;margin-left:1px"><?php echo $label;?></span></span>
          <?php endforeach;?>
          <span style="margin-left:auto;font-size:9.5px;color:var(--muted)"><i class="fas fa-hand-point-right" style="margin-right:3px"></i>Click card for full profile &amp; reports</span>
        </div>
        <div class="ocanv" style="min-height:500px;max-height:78vh"><div class="oinner" id="orgMount"></div></div>
      </div>
    </div>

    <!-- LEVEL VIEW -->
    <div class="panel" id="p-level">
      <div class="pnl-hd"><div class="pnl-t">Level-wise View</div><div class="pnl-m">Employees grouped by seniority</div></div>
      <div class="owrap">
        <div class="otb" style="padding:9px 14px">
          <div class="osw"><i class="fas fa-search"></i><input type="text" class="osi" id="lvQ" placeholder="Search name or designation…" oninput="filterLv()"></div>
          <select class="osel" id="lvLoc" onchange="filterLv()"><option value="">All Locations</option><?php foreach($loc_labels as $ll):?><option><?php echo h($ll);?></option><?php endforeach;?></select>
          <select class="osel" id="lvDv" onchange="filterLv()"><option value="">All Divisions</option><?php foreach($all_divs as $d):?><option><?php echo h($d);?></option><?php endforeach;?></select>
        </div>
        <div class="lv-view" id="lvCont">
          <?php
          $lv_lbl=['L1'=>'Executive','L2'=>'Senior Management','L3'=>'Management','L4'=>'Team Leads','L5'=>'Staff'];
          $lvg=['L1'=>[],'L2'=>[],'L3'=>[],'L4'=>[],'L5'=>[]];
          $lvg['L1'][]=array_merge($md_row,['_key'=>$md_key]);
          foreach($all_rows as $emp){$lv=$emp['level'];if(isset($lvg[$lv]))$lvg[$lv][]=array_merge($emp,['_key'=>nk($emp['fn'])]);}
          foreach(['L1','L2','L3','L4','L5'] as $lv):$les=$lvg[$lv]??[];if(empty($les))continue;?>
          <div class="lv-sec ll<?php echo strtolower($lv)[1];?>" id="lvsec-<?php echo $lv;?>">
            <div class="lv-hd">
              <div class="lv-bl"><?php echo $lv;?></div>
              <div><div class="lv-st"><?php echo $lv_lbl[$lv];?></div><div class="lv-sm"><?php echo count($les);?> employee<?php echo count($les)!=1?'s':'';?></div></div>
              <div class="lv-num"><?php echo count($les);?></div>
            </div>
            <div class="lv-grid">
              <?php foreach($les as $le):
                $fn=$le['fn']??trim(($le['first_name']??'').' '.($le['last_name']??''));
                $lkey=nk($fn);$rc=count($EMP[$lkey]['reportees']??[]);
                $pp=purl($le['photo']??'',$fn,$base_url,$lv==='L1'?'1e293b':'e2e8f0',$lv==='L1'?'ffffff':'475569');
                $dl=$loc_labels[$le['location']]??ucfirst($le['location']??'');
                $dn2=trim($le['division']??'');?>
              <div class="lv-card" data-n="<?php echo h(strtolower($fn));?>" data-l="<?php echo h(strtolower($dl));?>" data-d="<?php echo h(strtolower($dn2));?>" onclick="showDetail('<?php echo addslashes($lkey);?>')">
                <img src="<?php echo h($pp);?>" alt="" class="lv-av" loading="lazy" onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($fn);?>&background=<?php echo $lv==='L1'?'1e293b':'e2e8f0';?>&color=<?php echo $lv==='L1'?'ffffff':'475569';?>&size=80&bold=true'">
                <div class="lv-nm"><?php echo h($fn);?></div>
                <div class="lv-dg"><?php echo h($le['designation']??'');?></div>
                <div style="display:flex;flex-wrap:wrap;justify-content:center;gap:2px">
                  <?php if($dl):?><span class="lv-tg tgloc"><i class="fas fa-map-marker-alt" style="font-size:7.5px"></i> <?php echo h($dl);?></span><?php endif;?>
                  <?php if($dn2):?><span class="lv-tg tgdiv"><?php echo h($dn2);?></span><?php endif;?>
                </div>
                <?php if($rc>0):?><div class="lv-rep"><i class="fas fa-users" style="font-size:8px"></i> <?php echo $rc;?> reportee<?php echo $rc>1?'s':'';?></div><?php endif;?>
              </div>
              <?php endforeach;?>
            </div>
          </div>
          <?php endforeach;?>
        </div>
      </div>
    </div>

    <!-- DEPARTMENTS -->
    <div class="panel" id="p-dept">
      <div class="pnl-hd"><div class="pnl-t">Department / Division View</div><div class="pnl-m"><?php echo count($divisions);?> departments</div></div>
      <div class="dl">
        <div class="dsb">
          <div class="dsbhd"><i class="fas fa-layer-group" style="margin-right:5px"></i>Departments</div>
          <?php $di=0;foreach($divisions as $dn=>$de):$clr=$div_colors[$di%count($div_colors)];?>
          <div class="ditem<?php echo $di===0?' on':'';?>" onclick="showDept('dp-<?php echo $di;?>',this)">
            <span class="ddot" style="background:<?php echo $clr;?>"></span>
            <?php echo h($dn);?><span class="dcnt"><?php echo count($de);?></span>
          </div>
          <?php $di++;endforeach;?>
        </div>
        <div>
          <?php $di=0;foreach($divisions as $dn=>$de):
            $clr=$div_colors[$di%count($div_colors)];
            $lvc=[];foreach($de as $e){$lv=strtoupper(trim($e['level']??''));if($lv)$lvc[$lv]=($lvc[$lv]??0)+1;}ksort($lvc);?>
          <div class="dpanel<?php echo $di===0?' on':'';?>" id="dp-<?php echo $di;?>">
            <div class="dhdr" style="background:linear-gradient(135deg,<?php echo $clr;?>,<?php echo $clr;?>cc)">
              <div class="dhico"><i class="fas fa-layer-group"></i></div>
              <div style="flex:1;min-width:0">
                <div class="dhname"><?php echo h($dn);?></div>
                <div class="dhmeta"><span><i class="fas fa-users" style="margin-right:2px"></i><?php echo count($de);?> member<?php echo count($de)!=1?'s':'';?></span>
                  <?php foreach($lvc as $lv=>$c):?><span><?php echo h($lv);?>: <?php echo $c;?></span><?php endforeach;?>
                </div>
              </div>
            </div>
            <div class="dtree" id="dept-tree-<?php echo $di;?>"></div>
          </div>
          <?php $di++;endforeach;?>
        </div>
      </div>
    </div>

    <!-- STRENGTH TABLE -->
    <div class="panel" id="p-strength">
      <div class="pnl-hd"><div class="pnl-t">Employee Strength by Location</div><div class="pnl-m">Active headcount across all offices</div></div>
      <div class="card"><div class="tw">
        <table>
          <thead><tr><th>Level</th><th><i class="fas fa-star" style="color:#f59e0b;margin-right:3px"></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(['L1','L2','L3','L4','L5'] as $lv):$c=$strength[$lv];?>
            <tr>
              <td><span class="lb <?php echo strtolower($lv);?>"><?php echo $lv;?></span></td>
              <?php foreach(['Karur','Trichy','Madurai','Coimbatore','Tirunelveli','Salem','Total'] as $loc):?>
              <td style="font-weight:600;color:<?php echo($c[$loc]??0)>0?'var(--ink)':'var(--muted2)';?>;font-family:<?php echo($c[$loc]??0)>0?'var(--fm)':'inherit';?>"><?php echo $c[$loc]??0;?></td>
              <?php endforeach;?>
            </tr>
            <?php endforeach;?>
          </tbody>
          <tfoot><tr><td>Grand Total</td><?php foreach(['Karur','Trichy','Madurai','Coimbatore','Tirunelveli','Salem','Total'] as $loc):?><td style="font-family:var(--fm)"><?php echo $strength['Total'][$loc]??0;?></td><?php endforeach;?></tr></tfoot>
        </table>
      </div></div>
    </div>

    <!-- ALL EMPLOYEES -->
    <div class="panel" id="p-emps">
      <div class="pnl-hd"><div class="pnl-t">All Employees</div><div class="pnl-m" id="empCnt"><?php echo count($all_rows)+1;?> employees</div></div>
      <div class="fb">
        <div class="fg"><span class="fl">Level</span><select id="fLv" class="fsel" onchange="filterEmps()"><option value="">All</option><option>L1</option><option>L2</option><option>L3</option><option>L4</option><option>L5</option></select></div>
        <div class="fg"><span class="fl">Division</span><select id="fDiv" class="fsel" onchange="filterEmps()"><option value="">All</option><?php foreach($all_divs as $d):?><option><?php echo h($d);?></option><?php endforeach;?></select></div>
        <div class="fg"><span class="fl">Location</span><select id="fLoc" class="fsel" onchange="filterEmps()"><option value="">All</option><?php foreach($loc_labels as $ll):?><option><?php echo h($ll);?></option><?php endforeach;?></select></div>
        <div class="fg grow"><span class="fl">Search</span><input type="text" id="fQ" class="finp" placeholder="Name, designation, manager…" oninput="filterEmps()"></div>
        <div class="fg"><span class="fl">&nbsp;</span><button class="fbtn" onclick="clearF()"><i class="fas fa-times"></i> Clear</button></div>
      </div>
      <div class="card"><div class="tw">
        <table id="empTbl">
          <thead><tr><th>#</th><th></th><th>Name</th><th>Designation</th><th>Division</th><th>Level</th><th>Location</th><th>Company</th><th>Manager</th></tr></thead>
          <tbody>
            <?php $sno=1;echo "<tr class='cr'><td colspan='9'>L1 — Executive</td></tr>";?>
            <tr style="cursor:pointer" onclick="showDetail('<?php echo addslashes($md_key);?>')">
              <td style="font-size:10.5px;color:var(--muted);font-family:var(--fm)"><?php echo $sno++;?></td>
              <td><img src="<?php echo h($md_photo);?>" alt="" class="eth"></td>
              <td style="font-weight:700"><?php echo h($md_name);?></td>
              <td><?php echo h($md_row['designation']);?></td>
              <td><?php echo h($md_row['division']);?></td>
              <td><span class="lb l1">L1</span></td>
              <td><?php echo h($loc_labels[$md_row['location']]??ucfirst($md_row['location']));?></td>
              <td><?php echo h($md_row['company']?:'—');?></td>
              <td style="color:var(--muted)">—</td>
            </tr>
            <?php
            $clv='l1';$lv_lbl3=['l1'=>'Executive','l2'=>'Senior Management','l3'=>'Management','l4'=>'Team Leads','l5'=>'Staff'];
            foreach($sorted as $emp):
              $fn=$emp['fn'];$lvr=strtolower($emp['level']??'');$lvu=strtoupper($lvr);
              $pp=purl($emp['photo']??'',$fn,$base_url);
              $dl=$loc_labels[$emp['location']]??ucfirst($emp['location']);
              $rm=trim($emp['rm']??'');$rmd=$rm!==''?(strcasecmp($rm,'md')===0?$md_name:$rm):'—';
              $nkey=nk($fn);
              if($lvr&&$lvr!==$clv){$clv=$lvr;echo "<tr class='cr'><td colspan='9'>".strtoupper($clv)." — ".($lv_lbl3[$clv]??'')."</td></tr>";}
            ?>
            <tr style="cursor:pointer" onclick="showDetail('<?php echo addslashes($nkey);?>')">
              <td style="font-size:10.5px;color:var(--muted);font-family:var(--fm)"><?php echo $sno++;?></td>
              <td><img src="<?php echo h($pp);?>" alt="" class="eth" loading="lazy" onerror="this.src='https://ui-avatars.com/api/?name=<?php echo urlencode($fn);?>&background=e2e8f0&color=475569&size=36'"></td>
              <td style="font-weight:700"><?php echo h($fn);?></td>
              <td><?php echo h($emp['designation']);?></td>
              <td><?php echo h($emp['division']);?></td>
              <td><?php echo $lvr?'<span class="lb '.$lvr.'">'.h($lvu).'</span>':'—';?></td>
              <td><?php echo h($dl);?></td>
              <td><?php echo h(trim($emp['company']??'')?:'—');?></td>
              <td><?php if($rmd!=='—'):?><span style="font-weight:600;cursor:pointer;color:var(--l2a)" onclick="event.stopPropagation();showDetail('<?php echo addslashes(nk($rmd));?>')"><?php echo h($rmd);?></span><?php else:?><span style="color:var(--muted)">—</span><?php endif;?></td>
            </tr>
            <?php endforeach;?>
          </tbody>
        </table>
      </div></div>
    </div>

    <!-- BIRTHDAYS -->
    <div class="panel" id="p-bdays">
      <div class="pnl-hd"><div class="pnl-t">🎂 Birthdays — <?php echo $today->format('F Y');?></div><div class="pnl-m"><?php echo count($all_bdays);?> this month</div></div>
      <?php if(empty($all_bdays)):?>
      <div class="card"><div class="empty"><i class="fas fa-birthday-cake"></i><p>No birthdays in <?php echo $today->format('F');?>.</p></div></div>
      <?php else:?>
        <?php if(!empty($bdays_today)):?>
        <div class="subs"><i class="fas fa-fire" style="color:#ef4444"></i> Today — <?php echo $today->format('d M');?></div>
        <div class="pg">
          <?php foreach($bdays_today as $emp):$fn=$emp['fn']??trim(($emp['first_name']??'').' '.($emp['last_name']??''));$pp=purl($emp['photo']??'',$fn,$base_url);?>
          <div class="pcard bt" onclick="showDetail('<?php echo addslashes(nk($fn));?>')">
            <img src="<?php echo h($pp);?>" alt="" class="pav" loading="lazy">
            <div style="flex:1;min-width:0"><div class="pnm"><?php echo h($fn);?></div><div class="pro"><?php echo h($emp['designation']??'');?></div><span class="pbg btoday"><i class="fas fa-birthday-cake"></i> Today!</span></div>
          </div>
          <?php endforeach;?>
        </div>
        <?php endif;?>
        <?php if(!empty($bdays_up)):?>
        <div class="subs" style="margin-top:16px"><i class="fas fa-calendar-alt" style="color:#7c3aed"></i> Upcoming This Month</div>
        <div class="pg">
          <?php foreach($bdays_up as $emp):$fn=$emp['fn']??trim(($emp['first_name']??'').' '.($emp['last_name']??''));$pp=purl($emp['photo']??'',$fn,$base_url);?>
          <div class="pcard bu" onclick="showDetail('<?php echo addslashes(nk($fn));?>')">
            <img src="<?php echo h($pp);?>" alt="" class="pav" loading="lazy">
            <div style="flex:1;min-width:0"><div class="pnm"><?php echo h($fn);?></div><div class="pro"><?php echo h($emp['designation']??'');?></div><span class="pbg bup"><i class="fas fa-calendar"></i> <?php echo h($emp['_bdf']??'');?></span></div>
          </div>
          <?php endforeach;?>
        </div>
        <?php endif;?>
      <?php endif;?>
    </div>

    <!-- NEW HIRES -->
    <div class="panel" id="p-hires">
      <div class="pnl-hd"><div class="pnl-t">🌟 New Hires — Last 90 Days</div><div class="pnl-m"><?php echo count($new_hires);?> joined recently</div></div>
      <?php if(empty($new_hires)):?>
      <div class="card"><div class="empty"><i class="fas fa-user-plus"></i><p>No new hires in the last 90 days.</p></div></div>
      <?php else:?>
      <div class="pg">
        <?php foreach($new_hires as $emp):
          $fn=$emp['fn']??trim(($emp['first_name']??'').' '.($emp['last_name']??''));
          $pp=purl($emp['photo']??'',$fn,$base_url);$lv=strtoupper($emp['level']??'');
          $dl=$loc_labels[$emp['location']]??ucfirst($emp['location']??'');?>
        <div class="pcard nh" onclick="showDetail('<?php echo addslashes(nk($fn));?>')">
          <img src="<?php echo h($pp);?>" alt="" class="pav" loading="lazy">
          <div style="flex:1;min-width:0">
            <div class="pnm"><?php echo h($fn);?></div>
            <div class="pro"><?php echo h($emp['designation']??'');?><?php if(trim($emp['division']??'')):?> · <?php echo h($emp['division']);endif;?></div>
            <div style="display:flex;align-items:center;gap:5px;flex-wrap:wrap">
              <span class="pbg bnh"><i class="fas fa-calendar-check"></i> <?php echo h($emp['_djf']??'');?></span>
              <?php if($lv):?><span class="lb <?php echo strtolower($lv);?>" style="font-size:8px;padding:1px 5px"><?php echo h($lv);?></span><?php endif;?>
            </div>
          </div>
        </div>
        <?php endforeach;?>
      </div>
      <?php endif;?>
    </div>

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

<script>
// ═══════════════════════════════════════════
// DATA
// ═══════════════════════════════════════════
const EMP  = <?php echo $emp_json; ?>;
const HIER = <?php echo $hier_json; ?>;
const MD_KEY = '<?php echo addslashes($md_key); ?>';
const MAX_ROW = 6;
const TODAY_DATE = '<?php echo $today_date; ?>';

const LVC={L1:'#0f1929',L2:'#1a3fbf',L3:'#065f46',L4:'#92400e',L5:'#991b1b'};
const LVL={L1:'#e0e7f5',L2:'#dbeafe',L3:'#d1fae5',L4:'#fef3c7',L5:'#fee2e2'};
const LVA={L1:'#2d4080',L2:'#2563eb',L3:'#059669',L4:'#d97706',L5:'#dc2626'};
const LVN={L1:'Executive',L2:'Senior Mgmt',L3:'Management',L4:'Team Leads',L5:'Staff'};

function nk(s){return(s||'').trim().toLowerCase().replace(/\s+/g,' ')}
function fbUrl(n,bg,c){return`https://ui-avatars.com/api/?name=${encodeURIComponent(n||'?')}&background=${bg||'e2e8f0'}&color=${c||'475569'}&size=80&bold=true`}
function fmtD(s){if(!s||s==='0000-00-00')return'—';try{return new Date(s).toLocaleDateString('en-IN',{day:'2-digit',month:'short',year:'numeric'})}catch{return s}}
function fmtDT(s){if(!s)return'—';try{return new Date(s).toLocaleString('en-IN',{day:'2-digit',month:'short',hour:'2-digit',minute:'2-digit'})}catch{return s}}

// ═══════════════════════════════════════════
// GLOBAL SEARCH
// ═══════════════════════════════════════════
const gsInp=document.getElementById('globalSearch');
const gsDrop=document.getElementById('gsDrop');

function gsearch(val){
  const q=val.trim().toLowerCase();
  if(q.length<2){gsDrop.style.display='none';return;}
  const res=Object.entries(EMP).filter(([k,e])=>
    (e.name||'').toLowerCase().includes(q)||
    (e.designation||'').toLowerCase().includes(q)||
    (e.division||'').toLowerCase().includes(q)||
    String(e.id||'').includes(q)
  ).slice(0,8);
  if(!res.length){
    gsDrop.innerHTML='<div class="gs-none"><i class="fas fa-search" style="opacity:.3;margin-right:4px"></i>No employees found</div>';
    gsDrop.style.display='block';return;
  }
  gsDrop.innerHTML=res.map(([k,e])=>{
    const lv=(e.level||'').toUpperCase();
    const ph=e.photo||fbUrl(e.name,lv==='L1'?'1e293b':'e2e8f0',lv==='L1'?'ffffff':'475569');
    return `<div class="gsd-item" onclick="gsSelect('${k}')">
      <img src="${ph}" class="gsd-av" onerror="this.src='${fbUrl(e.name)}'">
      <div style="flex:1;min-width:0">
        <div class="gsd-nm">${e.name}</div>
        <div class="gsd-dg">${[e.designation,e.division].filter(Boolean).join(' · ')}</div>
      </div>
      ${lv?`<span class="gsd-lv" style="background:${LVL[lv]||'#f1f5f9'};color:${LVA[lv]||'#64748b'}">${lv}</span>`:''}
    </div>`;
  }).join('');
  gsDrop.style.display='block';
}
function gsSelect(key){
  gsDrop.style.display='none';
  gsInp.value=EMP[key]?.name||'';
  showDetail(key);
}
document.addEventListener('click',e=>{if(!e.target.closest('#gswrap')){gsDrop.style.display='none';}});
gsInp.addEventListener('keydown',e=>{if(e.key==='Escape'){gsDrop.style.display='none';gsInp.value='';}});

// ═══════════════════════════════════════════
// SIDEBAR / TABS
// ═══════════════════════════════════════════
function toggleSidebar(){
  document.getElementById('sidebar').classList.toggle('closed');
  document.getElementById('content').classList.toggle('exp');
}
function toggleMenu(b){b.nextElementSibling.classList.toggle('open');b.classList.toggle('open');}
function switchTab(b){
  document.querySelectorAll('.tab').forEach(t=>t.classList.remove('on'));
  document.querySelectorAll('.panel').forEach(p=>p.classList.remove('on'));
  b.classList.add('on');document.getElementById(b.dataset.p)?.classList.add('on');
}
function showDept(id,el){
  document.querySelectorAll('.dpanel').forEach(p=>p.classList.remove('on'));
  document.querySelectorAll('.ditem').forEach(i=>i.classList.remove('on'));
  document.getElementById(id)?.classList.add('on');el.classList.add('on');
}
function switchDpTab(b,pid){
  document.querySelectorAll('.dp-tab').forEach(t=>t.classList.remove('on'));
  document.querySelectorAll('.dp-panel').forEach(p=>p.classList.remove('on'));
  b.classList.add('on');document.getElementById(pid)?.classList.add('on');
}

// ═══════════════════════════════════════════
// ORG CHART
// ═══════════════════════════════════════════
function buildBFS(){
  const levels={};const visited=new Set();
  const queue=[{key:MD_KEY,depth:0}];
  while(queue.length){
    const{key,depth}=queue.shift();
    if(visited.has(key)||!EMP[key])continue;
    visited.add(key);
    if(!levels[depth])levels[depth]=[];
    const children=(HIER[key]||[]).map(c=>nk(c.fn||((c.first_name||'')+' '+(c.last_name||'')))).filter(ck=>EMP[ck]&&!visited.has(ck));
    levels[depth].push({key,children});
    children.forEach(ck=>queue.push({key:ck,depth:depth+1}));
  }
  return{levels,visited};
}

function makeCard(key,isRoot){
  const e=EMP[key];if(!e)return null;
  const lv=(e.level||'L1').toUpperCase(),lvi=lv[1]||'1';
  const ph=e.photo||fbUrl(e.name,isRoot?'1e293b':'e2e8f0',isRoot?'ffffff':'475569');
  const hkids=!!(HIER[key]&&HIER[key].length);
  const c=document.createElement('div');
  c.className=`oc2${isRoot?' root':' lc'+lvi}`;c.dataset.key=key;
  c.innerHTML=`
    <div class="oc2-avw"><img src="${ph}" class="oc2-av" loading="lazy" onerror="this.src='${fbUrl(e.name,isRoot?'1e293b':'e2e8f0',isRoot?'ffffff':'475569')}'"><span class="oc2-lv lv${lvi}b">${lv}</span></div>
    <div class="oc2-name">${e.name}</div>
    <div class="oc2-desg" title="${e.designation||''}">${e.designation||''}</div>
    ${e.division?`<div class="oc2-loc" style="margin-bottom:2px;font-size:7.5px;opacity:.6"><i class="fas fa-layer-group" style="font-size:7px;margin-right:2px"></i>${e.division}</div>`:''}
    <div class="oc2-loc"><span class="oc2-dot"></span>${e.location||''}</div>
    ${hkids?`<div class="oc2-cnt"><i class="fas fa-users" style="font-size:7.5px"></i>${HIER[key].length}</div>`:''}`;
  c.addEventListener('click',()=>showDetail(key));
  return c;
}

function renderOrg(){
  const mount=document.getElementById('orgMount');mount.innerHTML='';
  const{levels,visited}=buildBFS();
  const depths=Object.keys(levels).map(Number).sort((a,b)=>a-b);
  depths.forEach((depth)=>{
    const nodes=levels[depth];
    const block=document.createElement('div');
    block.className='org-level-block';block.dataset.depth=depth;
    if(depth>0){
      const allLvs=[...new Set(nodes.map(n=>(EMP[n.key]?.level||'?').toUpperCase()))];
      const pl=allLvs[0];const lc=LVA[pl]||'#64748b';const lb=LVL[pl]||'#f1f5f9';
      const lbl=document.createElement('div');lbl.className='org-level-label';
      lbl.innerHTML=`<div class="org-lv-line" style="max-width:48px"></div><span class="org-lv-pill" style="color:${lc};background:${lb};border-color:${lc}44">${allLvs.join(' / ')} · ${LVN[pl]||'Staff'}</span><div class="org-lv-line"></div><span class="org-lv-count">${nodes.length} employees</span>`;
      block.appendChild(lbl);
      const vw=document.createElement('div');vw.style.cssText='display:flex;justify-content:center';
      const vl=document.createElement('div');vl.className='org-vline';vw.appendChild(vl);block.appendChild(vw);
    }
    const cb=document.createElement('div');cb.className='org-children-block';cb.id=`lvl-block-${depth}`;
    for(let i=0;i<nodes.length;i+=MAX_ROW){
      const row=document.createElement('div');row.className='org-row-group';
      nodes.slice(i,i+MAX_ROW).forEach(node=>{const c=makeCard(node.key,depth===0);if(c)row.appendChild(c);});
      cb.appendChild(row);
      if(i+MAX_ROW<nodes.length){const sp=document.createElement('div');sp.style.height='12px';cb.appendChild(sp);}
    }
    block.appendChild(cb);
    if(depth>0&&depth<depths.length-1){
      const bw=document.createElement('div');bw.style.cssText='display:flex;justify-content:center;margin-top:8px';
      const btn=document.createElement('button');btn.className='org-expand-btn';
      btn.dataset.td=depth+1;btn.innerHTML=`<i class="fas fa-chevron-up"></i> Hide next level`;
      btn.addEventListener('click',()=>toggleLvlBlock(btn,depth+1));bw.appendChild(btn);block.appendChild(bw);
    }
    mount.appendChild(block);
  });
  const um=Object.keys(EMP).filter(k=>k!==MD_KEY&&!visited.has(k)&&EMP[k]);
  if(um.length){
    const w=document.createElement('div');w.className='um';
    w.innerHTML=`<div class="um-t"><i class="fas fa-exclamation-triangle"></i> Not Mapped (${um.length})</div>`;
    const g=document.createElement('div');g.className='um-g';
    um.forEach(k=>{const c=makeCard(k,false);if(c){c.style.width='var(--ow)';g.appendChild(c);}});
    w.appendChild(g);mount.appendChild(w);
  }
}
function toggleLvlBlock(btn,d){
  const bl=document.getElementById(`lvl-block-${d}`);if(!bl)return;
  const hidden=bl.classList.toggle('collapsed');
  btn.innerHTML=hidden?`<i class="fas fa-chevron-down"></i> Show next level`:`<i class="fas fa-chevron-up"></i> Hide next level`;
}
function orgCollapseAll(){document.querySelectorAll('.org-children-block').forEach((b,i)=>{if(i>0)b.classList.add('collapsed')});document.querySelectorAll('.org-expand-btn').forEach(b=>b.innerHTML=`<i class="fas fa-chevron-down"></i> Show next level`);}
function orgExpandAll(){document.querySelectorAll('.org-children-block').forEach(b=>b.classList.remove('collapsed'));document.querySelectorAll('.org-expand-btn').forEach(b=>b.innerHTML=`<i class="fas fa-chevron-up"></i> Hide next level`);}
function orgReset(){['orgQ','orgLv','orgDv','orgLoc'].forEach(id=>{const el=document.getElementById(id);if(el)el.value='';});document.querySelectorAll('.oc2').forEach(c=>c.classList.remove('hl','dim'));orgExpandAll();}
function orgFilter(){
  const t=(document.getElementById('orgQ').value||'').trim().toLowerCase();
  const lv=(document.getElementById('orgLv').value||'').toLowerCase();
  const dv=(document.getElementById('orgDv').value||'').toLowerCase();
  const lc=(document.getElementById('orgLoc').value||'').toLowerCase();
  if(!t&&!lv&&!dv&&!lc){document.querySelectorAll('.oc2').forEach(c=>c.classList.remove('hl','dim'));return;}
  document.querySelectorAll('.oc2').forEach(c=>{
    const e=EMP[c.dataset.key]||{};
    let ok=(!t||(e.name||'').toLowerCase().includes(t)||(e.designation||'').toLowerCase().includes(t)||(e.division||'').toLowerCase().includes(t));
    if(ok&&lv&&(e.level||'').toLowerCase()!==lv)ok=false;
    if(ok&&dv&&(e.division||'').toLowerCase()!==dv)ok=false;
    if(ok&&lc&&!(e.location||'').toLowerCase().includes(lc))ok=false;
    c.classList.toggle('hl',ok);c.classList.toggle('dim',!ok);
  });
  orgExpandAll();
}

// ═══════════════════════════════════════════
// DEPT TREES
// ═══════════════════════════════════════════
function buildDeptTrees(){
  <?php $di3=0;foreach($divisions as $dn=>$de):
    $dvkeys=[];foreach($de as $e){$fn2=isset($e['_is_md'])?($e['fn']??trim(($e['first_name']??'').' '.($e['last_name']??''))):($e['fn']??trim(($e['first_name']??'').' '.($e['last_name']??'')));$dvkeys[nk($fn2)]=true;}
    $roots=[];foreach($de as $e){
      if(!empty($e['_is_md'])){$fn2=$e['fn']??trim(($e['first_name']??'').' '.($e['last_name']??''));$roots[]=nk($fn2);continue;}
      $rm2=trim($e['rm']??'');$rk=nk($rm2===''||strcasecmp($rm2,'md')===0?$md_name:$rm2);
      if($rm2===''||strcasecmp($rm2,'md')===0||!isset($dvkeys[$rk]))$roots[]=nk($e['fn']??trim(($e['first_name']??'').' '.($e['last_name']??'')));
    }$roots=array_unique($roots);?>
  (()=>{
    const ct=document.getElementById('dept-tree-<?php echo $di3;?>');if(!ct)return;
    const dn=<?php echo json_encode(strtolower($dn));?>;
    function bdr(keys,d){
      if(!keys.length||d>8)return null;
      const w=document.createElement('div');w.style.cssText='display:flex;flex-direction:column;align-items:center;width:100%';
      for(let i=0;i<keys.length;i+=MAX_ROW){
        const row=document.createElement('div');row.className='dept-org-row';
        keys.slice(i,i+MAX_ROW).forEach(k=>{
          if(!EMP[k])return;const e=EMP[k];const lv=(e.level||'L2').toUpperCase(),lvi=lv[1]||'2';
          const c=document.createElement('div');c.className=`oc2 lc${lvi}`;c.dataset.key=k;c.style.cssText='width:144px;min-width:144px';
          c.innerHTML=`<div class="oc2-avw"><img src="${e.photo||fbUrl(e.name)}" class="oc2-av" loading="lazy" onerror="this.src='${fbUrl(e.name)}'"><span class="oc2-lv lv${lvi}b">${lv}</span></div><div class="oc2-name">${e.name}</div><div class="oc2-desg">${e.designation||''}</div><div class="oc2-loc"><span class="oc2-dot"></span>${e.location||''}</div>`;
          c.addEventListener('click',()=>showDetail(k));row.appendChild(c);
        });
        w.appendChild(row);
        const ck=[];keys.slice(i,i+MAX_ROW).forEach(k=>{(HIER[k]||[]).forEach(c=>{const cf=nk((c.fn||'')||((c.first_name||'')+' '+(c.last_name||'')));if(EMP[cf]&&(EMP[cf].division||'').toLowerCase()===dn)ck.push(cf);});});
        if(ck.length){const vl=document.createElement('div');vl.className='org-vline';w.appendChild(vl);const cr=bdr(ck,d+1);if(cr)w.appendChild(cr);}
      }
      return w;
    }
    const r=bdr(<?php echo json_encode(array_values($roots),JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP);?>,0);
    if(r)ct.appendChild(r);
  })();
  <?php $di3++;endforeach;?>
}

// ═══════════════════════════════════════════
// FILTERS
// ═══════════════════════════════════════════
function filterEmps(){
  const lv=document.getElementById('fLv').value.toLowerCase();
  const dv=document.getElementById('fDiv').value.toLowerCase();
  const lc=document.getElementById('fLoc').value.toLowerCase();
  const q=document.getElementById('fQ').value.toLowerCase();
  const rows=[...document.querySelectorAll('#empTbl tbody tr')];
  let vis=0;
  rows.forEach(r=>{
    if(r.classList.contains('cr')){r.style.display='';return;}
    const c=r.querySelectorAll('td');if(c.length<9)return;
    let ok=true;
    if(lv&&c[5].innerText.trim().toLowerCase()!==lv)ok=false;
    if(dv&&c[4].innerText.trim().toLowerCase()!==dv)ok=false;
    if(lc&&!c[6].innerText.toLowerCase().includes(lc))ok=false;
    if(q&&![2,3,4,6,8].some(i=>c[i].innerText.toLowerCase().includes(q)))ok=false;
    r.style.display=ok?'':'none';if(ok)vis++;
  });
  document.getElementById('empCnt').textContent=vis+' employees';
  rows.forEach((r,i)=>{if(!r.classList.contains('cr'))return;let v=false;for(let j=i+1;j<rows.length;j++){if(rows[j].classList.contains('cr'))break;if(rows[j].style.display!=='none'){v=true;break;}}r.style.display=v?'':'none';});
}
function clearF(){['fLv','fDiv','fLoc'].forEach(id=>document.getElementById(id).value='');document.getElementById('fQ').value='';filterEmps();}
function filterLv(){
  const t=(document.getElementById('lvQ').value||'').trim().toLowerCase();
  const lf=(document.getElementById('lvLoc').value||'').toLowerCase();
  const df=(document.getElementById('lvDv').value||'').toLowerCase();
  document.querySelectorAll('.lv-card').forEach(c=>{
    let ok=(!t||(c.dataset.n||'').includes(t))&&(!lf||(c.dataset.l||'').includes(lf))&&(!df||(c.dataset.d||'')===df);
    c.style.display=ok?'':'none';
  });
  document.querySelectorAll('.lv-sec').forEach(s=>s.style.display=[...s.querySelectorAll('.lv-card')].some(c=>c.style.display!=='none')?'':'none');
}

// ═══════════════════════════════════════════
// DETAIL PANEL
// ═══════════════════════════════════════════
let currentEmpId=null;
function showDetail(key){
  key=nk(key);const emp=EMP[key];if(!emp)return;
  const lv=(emp.level||'L1').toUpperCase();
  const clr=LVC[lv]||'#1e2740',aclr=LVA[lv]||'#475569',lclr=LVL[lv]||'#f1f5f9';
  document.getElementById('dphd').style.background=`linear-gradient(135deg,${clr},${aclr})`;
  const av=document.getElementById('dpAv');
  av.src=emp.photo||fbUrl(emp.name,clr.replace('#',''),'ffffff');
  av.onerror=()=>{av.src=fbUrl(emp.name);};
  const lvb=document.getElementById('dpLvB');lvb.textContent=lv;lvb.style.background=aclr;
  document.getElementById('dpNm').textContent=emp.name||'—';
  document.getElementById('dpDg').textContent=emp.designation||'—';
  document.getElementById('dpDiv').textContent=emp.division||'—';
  document.getElementById('dpLoc').textContent=emp.location||'—';
  document.getElementById('dpLvT').textContent=lv;
  document.getElementById('dpCo').textContent=emp.company||'—';
  document.getElementById('dpId').textContent=emp.id||'—';
  document.getElementById('dpDoj').textContent=fmtD(emp.doj);
  document.getElementById('dpDob').textContent=fmtD(emp.dob);

  // Manager chain
  const chainEl=document.getElementById('dpChain');chainEl.innerHTML='';
  if(!emp.manager){chainEl.innerHTML='<div class="nodata">No reporting manager</div>';}
  else{
    const chain=[];let cur=key,safe=0;
    while(safe++<10){const c=EMP[cur];if(!c||!c.manager)break;const mk=nk(c.manager);const m=EMP[mk];if(!m){chain.push({name:c.manager,designation:'',level:'',key:'',photo:''});break;}chain.push({...m,key:mk});cur=mk;}
    if(!chain.length){chainEl.innerHTML='<div class="nodata">No reporting manager</div>';}
    else chain.forEach((m,i)=>{
      if(i>0){const a=document.createElement('div');a.className='carrow';a.innerHTML='<i class="fas fa-level-up-alt"></i>';chainEl.appendChild(a);}
      const ml=(m.level||'').toUpperCase(),mac=LVA[ml]||'#64748b',mlc=LVL[ml]||'#f1f5f9';
      const it=document.createElement('div');it.className='ci';
      it.innerHTML=`<img src="${m.photo||fbUrl(m.name)}" class="ci-av" onerror="this.src='${fbUrl(m.name)}'"><div style="flex:1;min-width:0"><div class="ci-nm">${m.name||'—'}</div><div class="ci-rl">${m.designation||''}</div></div>${ml?`<span class="ci-bd" style="background:${mlc};color:${mac}">${ml}</span>`:''}`;
      if(m.key)it.onclick=e=>{e.stopPropagation();showDetail(m.key);};
      chainEl.appendChild(it);
    });
  }

  // Reportees
  const repEl=document.getElementById('dpReps');repEl.innerHTML='';
  const reps=emp.reportees||[];
  document.getElementById('dpRcnt').textContent=reps.length?`(${reps.length})`:'';
  if(!reps.length){repEl.innerHTML='<div class="nodata">No direct reportees</div>';}
  else{
    const LIM=6,vis=reps.slice(0,LIM),hid=reps.slice(LIM);
    const g=document.createElement('div');g.className='rqg';
    vis.forEach(rn=>{
      const rk=nk(rn);const r=EMP[rk];const rl=(r?.level||'').toUpperCase();const rac=LVA[rl]||'#64748b';const rlc=LVL[rl]||'#f1f5f9';
      const c=document.createElement('div');c.className='rqc';
      c.innerHTML=`<img src="${r?.photo||fbUrl(rn)}" class="rqav" onerror="this.src='${fbUrl(rn)}'"><div style="min-width:0"><div class="rqnm">${rn}</div><div class="rqdg">${r?.designation||''}</div>${rl?`<span style="font-size:7.5px;font-weight:700;color:${rac};background:${rlc};padding:1px 5px;border-radius:10px;font-family:var(--fm)">${rl}</span>`:''}</div>`;
      if(r)c.onclick=e=>{e.stopPropagation();showDetail(rk);};
      g.appendChild(c);
    });
    repEl.appendChild(g);
    if(hid.length){
      const hd=document.createElement('div');hd.style.display='none';const hg=document.createElement('div');hg.className='rqg';
      hid.forEach(rn=>{const rk=nk(rn);const r=EMP[rk];const rl=(r?.level||'').toUpperCase();const rac=LVA[rl]||'#64748b';const rlc=LVL[rl]||'#f1f5f9';
        const c=document.createElement('div');c.className='rqc';
        c.innerHTML=`<img src="${r?.photo||fbUrl(rn)}" class="rqav" onerror="this.src='${fbUrl(rn)}'"><div style="min-width:0"><div class="rqnm">${rn}</div><div class="rqdg">${r?.designation||''}</div>${rl?`<span style="font-size:7.5px;font-weight:700;color:${rac};background:${rlc};padding:1px 5px;border-radius:10px;font-family:var(--fm)">${rl}</span>`:''}</div>`;
        if(r)c.onclick=e=>{e.stopPropagation();showDetail(rk);};hg.appendChild(c);});
      hd.appendChild(hg);repEl.appendChild(hd);
      const sb=document.createElement('button');sb.className='sab';
      sb.innerHTML=`<i class="fas fa-chevron-down"></i> Show ${hid.length} more`;
      sb.onclick=()=>{const exp=hd.style.display==='none';hd.style.display=exp?'':'none';sb.innerHTML=exp?`<i class="fas fa-chevron-up"></i> Show less`:`<i class="fas fa-chevron-down"></i> Show ${hid.length} more`;};
      repEl.appendChild(sb);
    }
  }

  // Reset tabs to Profile
  document.querySelectorAll('.dp-tab').forEach(t=>t.classList.remove('on'));
  document.querySelectorAll('.dp-panel').forEach(p=>p.classList.remove('on'));
  document.querySelector('.dp-tab').classList.add('on');
  document.getElementById('dpt-info').classList.add('on');

  // Set employee ID for report form
  currentEmpId = emp.id;
  document.getElementById('rfUid').value = emp.id || '';

  // Reset form
  resetRepForm();

  // Load today's report
  loadTodayReport(emp.id);

  document.querySelectorAll('.oc2.sel').forEach(c=>c.classList.remove('sel'));
  document.querySelectorAll(`[data-key="${key}"].oc2`).forEach(c=>c.classList.add('sel'));
  document.getElementById('dovl').classList.add('on');
  document.getElementById('dpan').classList.add('open');
}

// ═══════════════════════════════════════════
// TODAY'S REPORT — LOAD
// ═══════════════════════════════════════════
function loadTodayReport(uid){
  const el=document.getElementById('dpReports');
  const badge=document.getElementById('repStatusBadge');
  el.innerHTML='<div style="text-align:center;padding:14px;color:var(--muted);font-size:11px"><i class="fas fa-spinner fa-spin"></i> Loading…</div>';
  badge.innerHTML='';
  hideToast();

  if(!uid){
    el.innerHTML='<div class="nodata">No employee ID</div>';
    return;
  }

  fetch(`?action=reports&uid=${encodeURIComponent(uid)}`)
    .then(r=>r.json())
    .then(reports=>{
      if(reports&&reports.length>0){
        renderTodayReport(reports[0], el);
        badge.innerHTML='<span class="rep-exists-badge"><i class="fas fa-check"></i> Report submitted</span>';
        prefillForm(reports[0]);
        document.getElementById('repFormTitle').textContent = 'Edit Today\'s Report';
      } else {
        el.innerHTML='<div class="nodata" style="text-align:center;padding:18px"><i class="fas fa-clipboard" style="font-size:22px;opacity:.15;display:block;margin-bottom:8px"></i>No report submitted for today yet</div>';
        badge.innerHTML='<span class="rep-missing-badge"><i class="fas fa-exclamation-circle"></i> Not submitted</span>';
        document.getElementById('repFormTitle').textContent = 'Add Today\'s Report';
        // Auto-open form if no report
        openRepForm();
      }
    })
    .catch(()=>{
      el.innerHTML='<div class="nodata">Failed to load report</div>';
    });
}

function renderTodayReport(r, el){
  const statClass=s=>{s=(s||'').toLowerCase();return s==='submitted'?'stat-submitted':s==='approved'?'stat-approved':s==='reviewed'?'stat-reviewed':s==='pending'?'stat-pending':'stat-default';};
  const apprClass=s=>{s=(s||'').toLowerCase();return s==='approved'?'appr-approved':s==='rejected'?'appr-rejected':'appr-pending';};
  const loc=r.Location||r.location_type||'';
  const cli=r.client||r.client_name||'';
  const loginT=r.login_time?`<span class="login-badge login-in"><i class="fas fa-sign-in-alt"></i> ${fmtDT(r.login_time)}</span>`:'';
  const logoutT=r.logout_time?`<span class="login-badge login-out"><i class="fas fa-sign-out-alt"></i> ${fmtDT(r.logout_time)}</span>`:'';
  const appr=r.approval_status?`<span class="rep-approval ${apprClass(r.approval_status)}">${r.approval_status}</span>`:'';

  const rows=[
    loc?`<div class="rep-row"><span class="rep-label">Location</span><span class="rep-val">${loc}${cli?' · '+cli:''}</span></div>`:'',
    r.Hits?`<div class="rep-row"><span class="rep-label">Hits</span><span class="rep-val">${r.Hits}</span></div>`:'',
    r.Missed?`<div class="rep-row"><span class="rep-label">Missed</span><span class="rep-val">${r.Missed}</span></div>`:'',
    r.carry?`<div class="rep-row"><span class="rep-label">Carry fwd</span><span class="rep-val">${r.carry}</span></div>`:'',
    r.daily_summary?`<div class="rep-row"><span class="rep-label">Summary</span><span class="rep-val">${r.daily_summary}</span></div>`:'',
    r.end_of_day_report?`<div class="rep-row"><span class="rep-label">EOD</span><span class="rep-val">${r.end_of_day_report}</span></div>`:'',
    r.full_report?`<div class="rep-row"><span class="rep-label">Full Report</span><span class="rep-val">${r.full_report}</span></div>`:'',
    r.manager_remarks?`<div class="rep-row"><span class="rep-label">Manager</span><span class="rep-val">${r.manager_remarks}</span></div>`:'',
  ].filter(Boolean).join('');

  el.innerHTML=`<div class="rep-card" style="border-color:#a7f3d0;background:#f0fdf4">
    <div class="rep-top">
      <span class="rep-date"><i class="fas fa-calendar-check" style="color:#059669;margin-right:4px"></i>${r.report_date||TODAY_DATE}</span>
      <span class="rep-stat ${statClass(r.report_status)}">${r.report_status||'submitted'}</span>
      ${appr?`<span class="rep-approval ${apprClass(r.approval_status)}">${r.approval_status}</span>`:''}
    </div>
    ${loginT||logoutT?`<div style="display:flex;flex-wrap:wrap;gap:5px;margin-bottom:8px">${loginT}${logoutT}</div>`:''}
    ${rows?`<div class="rep-body">${rows}</div>`:'<div class="rep-body" style="color:var(--muted);font-style:italic">No details recorded</div>'}
  </div>`;
}

function prefillForm(r){
  document.getElementById('rfLocation').value  = r.Location||r.location_address||'';
  document.getElementById('rfLocType').value   = r.location_type||'';
  document.getElementById('rfClient').value    = r.client||r.client_name||'';
  document.getElementById('rfHits').value      = r.Hits||'';
  document.getElementById('rfMissed').value    = r.Missed||'';
  document.getElementById('rfCarry').value     = r.carry||'';
  document.getElementById('rfSummary').value   = r.daily_summary||'';
  document.getElementById('rfEod').value       = r.end_of_day_report||'';
  document.getElementById('rfFull').value      = r.full_report||'';
  document.getElementById('rfStatus').value    = r.report_status||'submitted';
  document.getElementById('rfApproval').value  = r.approval_status||'pending';
  document.getElementById('rfRemarks').value   = r.manager_remarks||'';
  // datetime-local needs format: YYYY-MM-DDTHH:MM
  if(r.login_time){try{const d=new Date(r.login_time);document.getElementById('rfLogin').value=d.toISOString().slice(0,16);}catch{}}
  if(r.logout_time){try{const d=new Date(r.logout_time);document.getElementById('rfLogout').value=d.toISOString().slice(0,16);}catch{}}
}

function resetRepForm(){
  ['rfLocation','rfClient','rfHits','rfMissed','rfCarry','rfSummary','rfEod','rfFull','rfRemarks','rfLogin','rfLogout'].forEach(id=>{
    const el=document.getElementById(id);if(el)el.value='';
  });
  document.getElementById('rfLocType').value='';
  document.getElementById('rfStatus').value='submitted';
  document.getElementById('rfApproval').value='pending';
  hideToast();
  closeRepForm();
}

// ═══════════════════════════════════════════
// FORM TOGGLE
// ═══════════════════════════════════════════
function toggleRepForm(){
  const body=document.getElementById('repFormBody');
  const hdr=document.getElementById('repFormToggle');
  const icon=document.getElementById('repFormIcon');
  const open=body.classList.toggle('open');
  hdr.classList.toggle('open',open);
  icon.style.transform=open?'rotate(180deg)':'';
}
function openRepForm(){
  const body=document.getElementById('repFormBody');
  const hdr=document.getElementById('repFormToggle');
  const icon=document.getElementById('repFormIcon');
  body.classList.add('open');hdr.classList.add('open');
  icon.style.transform='rotate(180deg)';
}
function closeRepForm(){
  const body=document.getElementById('repFormBody');
  const hdr=document.getElementById('repFormToggle');
  const icon=document.getElementById('repFormIcon');
  body.classList.remove('open');hdr.classList.remove('open');
  icon.style.transform='';
}

// ═══════════════════════════════════════════
// SAVE REPORT
// ═══════════════════════════════════════════
function saveReport(){
  const uid=document.getElementById('rfUid').value;
  if(!uid){showToast('error','No employee selected');return;}
  const btn=document.getElementById('repSaveBtn');
  const txt=document.getElementById('repSaveTxt');
  btn.disabled=true;txt.textContent='Saving…';

  const data=new FormData();
  data.append('action','save_report');
  data.append('uid',uid);
  data.append('location',document.getElementById('rfLocation').value);
  data.append('location_type',document.getElementById('rfLocType').value);
  data.append('client_name',document.getElementById('rfClient').value);
  data.append('hits',document.getElementById('rfHits').value);
  data.append('missed',document.getElementById('rfMissed').value);
  data.append('carry',document.getElementById('rfCarry').value);
  data.append('daily_summary',document.getElementById('rfSummary').value);
  data.append('end_of_day_report',document.getElementById('rfEod').value);
  data.append('full_report',document.getElementById('rfFull').value);
  data.append('report_status',document.getElementById('rfStatus').value);
  data.append('manager_remarks',document.getElementById('rfRemarks').value);
  data.append('login_time',document.getElementById('rfLogin').value);
  data.append('logout_time',document.getElementById('rfLogout').value);
  data.append('approval_status',document.getElementById('rfApproval').value);

  fetch('dashboard_admin.php',{method:'POST',body:data})
    .then(r=>r.json())
    .then(res=>{
      btn.disabled=false;txt.textContent='Save Report';
      if(res.success){
        showToast('success',res.msg||'Report saved');
        closeRepForm();
        // Reload today's report view
        loadTodayReport(uid);
      } else {
        showToast('error',res.msg||'Save failed');
      }
    })
    .catch(()=>{
      btn.disabled=false;txt.textContent='Save Report';
      showToast('error','Network error. Please try again.');
    });
}

function showToast(type,msg){
  const t=document.getElementById('repToast');
  t.className=`rep-toast ${type}`;
  t.innerHTML=`<i class="fas fa-${type==='success'?'check-circle':'exclamation-circle'}"></i>${msg}`;
  t.style.display='flex';
  if(type==='success')setTimeout(()=>hideToast(),4000);
}
function hideToast(){
  const t=document.getElementById('repToast');
  if(t){t.style.display='none';t.className='rep-toast hidden';}
}

function closeDetail(){
  document.getElementById('dovl').classList.remove('on');
  document.getElementById('dpan').classList.remove('open');
  document.querySelectorAll('.oc2.sel').forEach(c=>c.classList.remove('sel'));
}
document.addEventListener('keydown',e=>{if(e.key==='Escape')closeDetail();});

// ═══════════════════════════════════════════
// INIT
// ═══════════════════════════════════════════
document.addEventListener('DOMContentLoaded',()=>{
  renderOrg();
  buildDeptTrees();
  setTimeout(()=>document.querySelectorAll('.sc-fill').forEach(el=>el.style.width=el.dataset.w||'0%'),250);
});
</script>
</body>
</html>