<?php
$pageTitle = 'Pengurusan Pegawai';
require_once __DIR__.'/../../config/functions.php';
requireLogin();

$unitId = intval($_GET['unit']??0);
$unitInfo = null;
if($unitId){
  $unitInfo = $pdo->prepare("SELECT * FROM unit WHERE id=?");
  $unitInfo->execute([$unitId]);
  $unitInfo = $unitInfo->fetch();
  $pageTitle = $unitInfo ? 'Pegawai - '.htmlspecialchars($unitInfo['nama_unit']) : 'Pegawai';
}

$where = "WHERE p.status IN (0,1)";
$params = [];
if($unitId){$where.=" AND p.unit_id=?";$params[]=$unitId;}
elseif(isset($_GET['unit'])&&$_GET['unit']===''){ $where.=" AND p.unit_id IS NULL"; }
if(!empty($_GET['s'])){$where.=" AND (p.nama LIKE ? OR p.email LIKE ? OR j.nama_jawatan LIKE ?)";$q='%'.sanitize($_GET['s']).'%';$params=array_merge($params,[$q,$q,$q]);}
if(isset($_GET['aktif'])&&$_GET['aktif']!==''){$where.=" AND p.status=?";$params[]=intval($_GET['aktif']);}

$stmt=$pdo->prepare("SELECT p.*,j.nama_jawatan,j.urutan as j_urutan,u.nama_unit,u.warna,u.urutan as unit_urutan,su.nama_subunit FROM pegawai p JOIN jawatan j ON p.jawatan_id=j.id LEFT JOIN unit u ON p.unit_id=u.id LEFT JOIN subunit su ON p.subunit_id=su.id $where ORDER BY u.urutan, u.id, j.urutan, p.urutan, p.nama");
$stmt->execute($params);
$pegawaiList=$stmt->fetchAll();

// Pisahkan Timbalan (jawatan urutan=1 / tiada unit) dan lain
$timbalanList=array_filter($pegawaiList,fn($p)=>$p['j_urutan']==1);
// Kumpulan pegawai mengikut unit untuk paparan teratur
// Kumpulan pegawai mengikut unit dan subunit untuk paparan teratur
$pegawaiByUnit=[];
foreach($pegawaiList as $p){
  if($p['j_urutan']>1){
    $uid = $p['unit_id'] ?? 0;
    $sid = $p['subunit_id'] ?? 0;
    if(!isset($pegawaiByUnit[$uid][$sid])) {
      $pegawaiByUnit[$uid][$sid] = [
        'nama' => $p['nama_subunit'] ?? 'Utama / Umum',
        'pegawai' => []
      ];
    }
    $pegawaiByUnit[$uid][$sid]['pegawai'][] = $p;
  }
}

$units=$pdo->query("SELECT * FROM unit WHERE status=1 ORDER BY urutan ASC, id ASC")->fetchAll();
$jawatanList=$pdo->query("SELECT * FROM jawatan WHERE status=1 ORDER BY urutan")->fetchAll();
$unitColors=[1=>'#0d6efd',2=>'#dc3545',3=>'#198754'];

// Dashboard links for unit grouped by subunit
$linksBySubunit = [];
if($unitId){
  // Get all subunits for this unit
  $subunits = $pdo->prepare("SELECT * FROM subunit WHERE unit_id=? AND status=1 ORDER BY id");
  $subunits->execute([$unitId]);
  $subunitList = $subunits->fetchAll();
  
  // Get all links for this unit
  $lstmt = $pdo->prepare("SELECT l.*, s.nama_subunit FROM links l LEFT JOIN subunit s ON l.subunit_id = s.id WHERE l.unit_id=? AND l.status=1 ORDER BY s.id, l.urutan");
  $lstmt->execute([$unitId]);
  $allLinks = $lstmt->fetchAll();
  
  foreach($allLinks as $lnk) {
    $sid = $lnk['subunit_id'] ?? 0;
    $linksBySubunit[$sid]['nama'] = $lnk['nama_subunit'] ?? 'Utama / Umum';
    $linksBySubunit[$sid]['links'][] = $lnk;
  }
}

$breadcrumb=[['label'=>'Utama','url'=>BASE_URL],['label'=>$pageTitle,'url'=>'#']];
require_once __DIR__.'/../../templates/header.php';
?>
<meta name="base-url" content="<?=BASE_URL?>">
<meta name="csrf-token" content="<?=$csrf?>">
<style>
  .staff-flex-grid {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -0.5rem;
  }
  .subunit-wrapper {
    flex: 0 0 100%;
    padding: 0 0.5rem;
    margin-bottom: 2.5rem;
    min-width: 0;
  }

  /* Tablet & Above: Packing Logic */
  @media (min-width: 768px) {
    /* 2 Column Packing */
    .subunit-wrapper[data-count="1"] { flex: 0 0 50%; }
    .subunit-wrapper[data-count="2"] { flex: 0 0 100%; }
    
    .subunit-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    .subunit-wrapper[data-count="1"] .subunit-cards { grid-template-columns: minmax(0, 1fr); }
  }

  @media (min-width: 992px) {
    /* 3 Column Packing */
    .subunit-wrapper[data-count="1"] { flex: 0 0 33.333%; }
    .subunit-wrapper[data-count="2"] { flex: 0 0 66.666%; }
    .subunit-wrapper[data-count="3"] { flex: 0 0 100%; }
    
    .subunit-cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
    .subunit-wrapper[data-count="1"] .subunit-cards { grid-template-columns: minmax(0, 1fr); }
    .subunit-wrapper[data-count="2"] .subunit-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  }

  @media (min-width: 1200px) {
    /* 4/5 Column Packing */
    .subunit-wrapper[data-count="1"] { flex: 0 0 25%; }
    .subunit-wrapper[data-count="2"] { flex: 0 0 50%; }
    .subunit-wrapper[data-count="3"] { flex: 0 0 75%; }
    .subunit-wrapper[data-count="4"] { flex: 0 0 100%; }
    .subunit-wrapper[data-count="5"] { flex: 0 0 100%; }
    
    .subunit-cards { grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.75rem; }
    .subunit-wrapper[data-count="1"] .subunit-cards { grid-template-columns: minmax(0, 1fr); }
    .subunit-wrapper[data-count="2"] .subunit-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    .subunit-wrapper[data-count="3"] .subunit-cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
    .subunit-wrapper[data-count="5"] .subunit-cards { grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 0.5rem; }
    
    .staff-card-futuristic { padding: 0.75rem; }
  }

  @media (min-width: 1440px) {
    /* 5 Column Packing Full */
    .subunit-wrapper[data-count="1"] { flex: 0 0 20%; }
    .subunit-wrapper[data-count="2"] { flex: 0 0 40%; }
    .subunit-wrapper[data-count="3"] { flex: 0 0 60%; }
    .subunit-wrapper[data-count="4"] { flex: 0 0 80%; }
    .subunit-wrapper[data-count="5"] { flex: 0 0 100%; }
    
    .subunit-cards { grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 1rem; }
    .subunit-wrapper[data-count="1"] .subunit-cards { grid-template-columns: minmax(0, 1fr); }
    .subunit-wrapper[data-count="2"] .subunit-cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
    .subunit-wrapper[data-count="3"] .subunit-cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
    .subunit-wrapper[data-count="4"] .subunit-cards { grid-template-columns: repeat(4, minmax(0, 1fr)); }
    .subunit-wrapper[data-count="5"] .subunit-cards { grid-template-columns: repeat(5, minmax(0, 1fr)); }
    
    .staff-card-futuristic { padding: 1rem; }
  }

  .subunit-header {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-top: 1rem;
    margin-bottom: 1rem;
  }
  .subunit-header::after {
    content: '';
    flex: 1;
    height: 1px;
    background: linear-gradient(90deg, rgba(255,255,255,0.1), transparent);
  }

  .subunit-cards {
    display: grid;
    gap: 1rem;
  }
  .subunit-title {
    font-size: 0.7rem;
    font-weight: 700;
    color: #888;
    text-transform: uppercase;
    letter-spacing: 2px;
  }
  .subunit-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
  }

  .staff-card-futuristic {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 20px;
    padding: 1rem;
    text-align: center;
    transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    position: relative;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
    backdrop-filter: blur(10px);
  }
  .staff-card-futuristic:hover {
    transform: translateY(-10px);
    background: rgba(255, 255, 255, 0.05);
    border-color: var(--unit-color-op);
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.4), 0 0 20px var(--unit-color-glow);
  }
  .staff-avatar-wrapper {
    position: relative;
    display: inline-block;
    margin-bottom: 1rem;
    width: 80px;
    height: 80px;
    margin-left: auto;
    margin-right: auto;
  }
  .staff-avatar-futuristic {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid rgba(255, 255, 255, 0.1);
    transition: all 0.4s ease;
  }
  .staff-card-futuristic:hover .staff-avatar-futuristic {
    border-color: var(--unit-color);
    transform: scale(1.05);
  }
  .staff-name-futuristic {
    font-size: 0.85rem;
    font-weight: 800;
    color: #fff;
    margin-bottom: 0.25rem;
    line-height: 1.2;
    min-height: 2.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    text-transform: uppercase;
  }
  .staff-pos-futuristic {
    font-size: 0.7rem;
    color: #999;
    margin-bottom: 0.75rem;
    font-weight: 500;
    line-height: 1.2;
  }
  .staff-contact-futuristic {
    margin-top: auto;
    padding-top: 0.75rem;
    border-top: 1px solid rgba(255, 255, 255, 0.05);
    font-size: 0.7rem;
    color: #555;
    text-align: left;
  }
  .staff-contact-futuristic div {
    margin-bottom: 0.2rem;
    display: flex;
    align-items: center;
    gap: 0.4rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .staff-actions-futuristic {
    margin-top: 0.75rem;
    display: flex;
    gap: 0.4rem;
    justify-content: center;
  }
  .staff-actions-futuristic .btn-sm {
    padding: .25rem .5rem;
    font-size: .7rem;
    border-radius: 8px;
  }
</style>
<?php require_once __DIR__.'/../../templates/sidebar.php'; ?>
<div class="main-content">
<?php require_once __DIR__.'/../../templates/topbar.php'; ?>
<div style="padding:2rem">

<?php if($linksBySubunit): ?>
<div class="content-card mb-4">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <h3 style="font-size:1rem;font-weight:700;color:#fff;margin:0"><i class="fas fa-link me-2" style="color:<?=$unitInfo['warna']??'#cc0001'?>"></i>Dashboard & Pautan</h3>
    <?php if(isSuperAdmin() || currentUnitId() == $unitId): ?>
    <button class="btn btn-sm btn-outline-primary" onclick="showLinkModal()"><i class="fas fa-plus me-1"></i>Tambah Link</button>
    <?php endif; ?>
  </div>
  
  <?php foreach($linksBySubunit as $sid => $group): ?>
    <div class="mb-3">
      <div style="font-size:.7rem;color:#888;text-transform:uppercase;letter-spacing:1px;font-weight:600;margin-bottom:.75rem;display:flex;align-items:center;gap:.5rem">
        <div style="width:4px;height:12px;background:<?=$unitInfo['warna']??'#cc0001'?>;border-radius:2px"></div>
        <?=$group['nama']?>
      </div>
      <div class="row g-3">
      <?php foreach($group['links'] as $lnk): ?>
      <div class="col-12 col-md-6 col-xl-4">
        <a href="<?=htmlspecialchars($lnk['url'])?>" target="_blank" class="link-dashboard-btn" style="--link-color:<?=$lnk['warna']??'#0d6efd'?>; padding: 0.75rem 1rem;">
          <?php if($lnk['logo']): ?>
          <div class="link-icon" style="background:transparent;padding:0;overflow:hidden">
            <img src="<?=UPLOAD_URL?>links/<?=$lnk['logo']?>" style="width:100%;height:100%;object-fit:cover" alt="Logo">
          </div>
          <?php else: ?>
          <div class="link-icon" style="background:<?=$lnk['warna']??'#0d6efd'?>22;color:<?=$lnk['warna']??'#0d6efd'?>">
            <i class="<?=$lnk['ikon']??'fas fa-link'?>"></i>
          </div>
          <?php endif; ?>
          <div style="min-width:0;flex:1">
            <div style="font-size:0.9rem;font-weight:700;color:#fff;margin-bottom:2px" title="<?=htmlspecialchars($lnk['nama'])?>"><?=htmlspecialchars($lnk['nama'])?></div>
            <?php if($lnk['deskripsi']): ?><div style="font-size:0.7rem;color:#777;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?=htmlspecialchars($lnk['deskripsi'])?></div><?php endif; ?>
            
            <div style="display:flex;align-items:center;justify-content:space-between;margin-top:0.75rem">
              <span id="awam-badge-<?=$lnk['id']?>" style="font-size:.6rem;font-weight:700;padding:.15rem .5rem;border-radius:50px;display:inline-block;background:<?=$lnk['awam']?'rgba(25,135,84,0.1)':'rgba(108,117,125,0.1)'?>;color:<?=$lnk['awam']?'#75c99c':'#888'?>;border:1px solid <?=$lnk['awam']?'rgba(25,135,84,0.2)':'rgba(108,117,125,0.2)'?>">
                <i class="fas <?=$lnk['awam']?'fa-globe':'fa-lock'?> me-1"></i><?=$lnk['awam']?'Awam':'Peribadi'?>
              </span>
              
              <?php if(isSuperAdmin() || currentUnitId() == $unitId): ?>
              <div style="display:flex;gap:.2rem">
                <button onclick="event.preventDefault();toggleAwam(<?=$lnk['id']?>)" class="btn btn-sm" id="awam-btn-<?=$lnk['id']?>" title="<?=$lnk['awam']?'Jadikan Peribadi':'Jadikan Awam'?>" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.05);color:<?=$lnk['awam']?'#75c99c':'#888'?>;border-radius:6px;padding:.15rem .4rem;font-size:.65rem"><i class="fas <?=$lnk['awam']?'fa-globe':'fa-lock'?>"></i></button>
                <button onclick="event.preventDefault();editLink(<?=$lnk['id']?>)" class="btn btn-sm" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.05);color:#888;border-radius:6px;padding:.15rem .4rem;font-size:.65rem"><i class="fas fa-edit"></i></button>
                <button onclick="event.preventDefault();deleteLink(<?=$lnk['id']?>,`<?=htmlspecialchars($lnk['nama'])?>`)" class="btn btn-sm" style="background:rgba(204,0,1,0.05);border:1px solid rgba(204,0,1,0.1);color:#cc0001;border-radius:6px;padding:.15rem .4rem;font-size:.65rem"><i class="fas fa-trash"></i></button>
              </div>
              <?php endif; ?>
            </div>
          </div>
        </a>
      </div>
      <?php endforeach; ?>
      </div>
    </div>
  <?php endforeach; ?>
</div>
<?php elseif(isAdmin()&&$unitId && (isSuperAdmin() || currentUnitId() == $unitId)): ?>
<div class="content-card mb-4" style="text-align:center;padding:1.5rem">
  <button class="btn btn-outline-primary" onclick="showLinkModal()"><i class="fas fa-plus me-2"></i>Tambah Dashboard Link</button>
</div>
<?php endif; ?>

<div class="content-card">
<div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
  <div>
    <h2 style="font-size:1.3rem;font-weight:700;color:#fff;margin:0"><?=htmlspecialchars($pageTitle)?></h2>
    <div style="font-size:.8rem;color:#555"><?=count($pegawaiList)?> pegawai dijumpai</div>
  </div>
  <div style="display:flex;gap:.75rem;flex-wrap:wrap;align-items:center">
    <form method="GET" style="display:flex;gap:.5rem;align-items:center">
      <?php if($unitId): ?><input type="hidden" name="unit" value="<?=$unitId?>"><?php endif; ?>
      <input type="search" name="s" class="form-control" style="width:200px;border-radius:10px;font-size:.85rem" placeholder="Cari pegawai..." value="<?=htmlspecialchars($_GET['s']??'')?>">
      <select name="aktif" class="form-select" style="width:130px;font-size:.85rem">
        <option value="">Semua Status</option>
        <option value="1" <?=(($_GET['aktif']??'')==='1')?'selected':''?>>Aktif</option>
        <option value="0" <?=(($_GET['aktif']??'')==='0')?'selected':''?>>Tidak Aktif</option>
      </select>
      <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i></button>
    </form>
    <?php if(isAdmin()): ?>
    <button class="btn btn-primary" onclick="showAddModal()"><i class="fas fa-plus me-2"></i>Tambah Pegawai</button>
    <?php endif; ?>
  </div>
</div>

<?php
// Paparan Timbalan Pengarah - Ketua Sektor (di atas)
if($timbalanList&&!$unitId): ?>
<div class="mb-5" style="background:linear-gradient(135deg,rgba(204,0,1,0.08),rgba(26,26,46,0.6));border:1px solid rgba(204,0,1,0.2);border-radius:24px;padding:2rem">
  <div style="font-size:.7rem;color:#cc0001;text-transform:uppercase;letter-spacing:2px;font-weight:600;margin-bottom:1.5rem;display:flex;align-items:center;gap:.75rem">
    <i class="fas fa-crown"></i> Ketua Sektor
  </div>
  <div style="display:flex;justify-content:center;flex-wrap:wrap;gap:1.5rem">
  <?php foreach($timbalanList as $p): 
    $col = '#cc0001';
    $colGlow = $col . '22';
    $colOp = $col . '44';
  ?>
    <div class="pegawai-card" data-nama="<?=strtolower(htmlspecialchars($p['nama']))?>" data-unit="0" style="width:100%; max-width:280px; --unit-color:<?=$col?>; --unit-color-op:<?=$colOp?>; --unit-color-glow:<?=$colGlow?>">
      <div class="staff-card-futuristic">
        <div style="position:absolute;top:12px;right:12px;color:<?=$col?>;font-size:.7rem"><i class="fas fa-crown"></i></div>
        
        <div class="staff-avatar-wrapper">
          <img src="<?=getPegawaiImage($p['gambar'])?>" alt="<?=htmlspecialchars($p['nama'])?>" class="staff-avatar-futuristic">
          <div style="position:absolute;bottom:0;right:0;width:14px;height:14px;background:<?=$p['status']?'#198754':'#dc3545'?>;border-radius:50%;border:2px solid #0a0a0f"></div>
        </div>
        
        <div class="staff-name-futuristic"><?=htmlspecialchars($p['nama'])?></div>
        <div class="staff-pos-futuristic"><?=htmlspecialchars($p['nama_jawatan'])?></div>
        
        <div class="staff-contact-futuristic">
          <?php if($p['email']): ?><div><i class="fas fa-envelope" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['email'])?></div><?php endif; ?>
          <?php if($p['no_telefon_pejabat']): ?><div><i class="fas fa-phone" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['no_telefon_pejabat'])?></div><?php endif; ?>
        </div>

        <div class="staff-actions-futuristic">
          <a href="view.php?id=<?=$p['id']?>" class="btn btn-sm" style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);color:#ccc"><i class="fas fa-eye"></i></a>
          <?php if(isAdmin()): ?>
          <button onclick="editPegawai(<?=$p['id']?>)" class="btn btn-sm" style="background:rgba(13,110,253,0.1);border:1px solid rgba(13,110,253,0.3);color:#0d6efd"><i class="fas fa-edit"></i></button>
          <button onclick="confirmDelete(<?=$p['id']?>,'ajax_delete.php','<?=addslashes($p['nama'])?>')" class="btn btn-sm" style="background:rgba(204,0,1,0.1);border:1px solid rgba(204,0,1,0.3);color:#cc0001"><i class="fas fa-trash"></i></button>
          <?php endif; ?>
        </div>
      </div>
    </div>
  <?php endforeach; ?>
  </div>
</div>
<?php endif; ?>

<?php
// Tentukan unit yang akan dipaparkan
$displayUnits = [];
if($unitId) {
  $displayUnits[] = ['id' => $unitId, 'nama_unit' => $unitInfo['nama_unit']??'Pegawai', 'warna' => $unitInfo['warna']??'#888'];
} else {
  $displayUnits = $units;
  if(!empty($pegawaiByUnit[0])) {
    $displayUnits[] = ['id' => 0, 'nama_unit' => 'Lain-lain / Tiada Unit', 'warna' => '#888'];
  }
}

foreach($displayUnits as $u):
  $uGroups = $pegawaiByUnit[$u['id']]??[];
  if(!$uGroups) continue;
  $col = $u['warna']??'#888';
  $totalPegawai = 0;
  foreach($uGroups as $g) $totalPegawai += count($g['pegawai']);
?>
  <!-- Unit Heading (Papar jika bukan filter unit spesifik) -->
  <?php if(!$unitId): ?>
  <div style="display:flex;align-items:center;gap:1rem;margin:2.5rem 0 1.25rem;padding-bottom:.75rem;border-bottom:1px solid <?=$col?>22">
    <div style="width:8px;height:24px;background:<?=$col?>;border-radius:4px"></div>
    <h3 style="font-size:1.1rem;font-weight:800;color:#fff;margin:0"><?=htmlspecialchars($u['nama_unit'])?></h3>
    <span style="margin-left:auto;background:<?=$col?>11;color:<?=$col?>;border:1px solid <?=$col?>33;border-radius:50px;padding:.2rem .8rem;font-size:.65rem;font-weight:700;letter-spacing:1px"><?=$totalPegawai?> PEGAWAI</span>
  </div>
  <?php endif; ?>

  <?php
    // Separate Kpps for this unit
    $unitKpps = [];
    foreach($uGroups as $sid => $g) {
      foreach($g['pegawai'] as $p) {
        if($p['j_urutan'] == 2) $unitKpps[] = $p;
      }
    }
  ?>

  <!-- Ketua Unit (KPP) - Centered at Top -->
  <?php if($unitKpps): ?>
  <div style="display:flex;justify-content:center;flex-wrap:wrap;gap:1.5rem;margin-bottom:3rem">
    <?php foreach($unitKpps as $p): 
      $colGlow = $col . '22';
      $colOp = $col . '44';
    ?>
    <div class="pegawai-card" data-nama="<?=strtolower(htmlspecialchars($p['nama']))?>" data-unit="<?=$p['unit_id']?>" style="width:100%; max-width:280px; --unit-color:<?=$col?>; --unit-color-op:<?=$colOp?>; --unit-color-glow:<?=$colGlow?>">
      <div class="staff-card-futuristic" style="border-width:2px;background:rgba(255,255,255,0.03)">
        <div style="position:absolute;top:12px;right:12px;color:<?=$col?>;font-size:.7rem"><i class="fas fa-medal"></i></div>
        <div class="staff-avatar-wrapper">
          <img src="<?=getPegawaiImage($p['gambar'])?>" alt="<?=htmlspecialchars($p['nama'])?>" class="staff-avatar-futuristic" style="border-color:<?=$col?>">
          <div style="position:absolute;bottom:0;right:0;width:14px;height:14px;background:<?=$p['status']?'#198754':'#dc3545'?>;border-radius:50%;border:2px solid #0a0a0f"></div>
        </div>
        <div class="staff-name-futuristic"><?=htmlspecialchars($p['nama'])?></div>
        <div class="staff-pos-futuristic" style="color:<?=$col?>;font-weight:700"><?=htmlspecialchars($p['nama_jawatan'])?></div>
        <div class="staff-contact-futuristic">
          <?php if($p['email']): ?><div><i class="fas fa-envelope" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['email'])?></div><?php endif; ?>
          <?php if($p['no_telefon_pejabat']): ?><div><i class="fas fa-phone" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['no_telefon_pejabat'])?></div><?php endif; ?>
        </div>
        <div class="staff-actions-futuristic">
          <a href="view.php?id=<?=$p['id']?>" class="btn btn-sm" style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);color:#ccc"><i class="fas fa-eye"></i></a>
          <?php if(isAdmin()): ?>
          <button onclick="editPegawai(<?=$p['id']?>)" class="btn btn-sm" style="background:rgba(13,110,253,0.1);border:1px solid rgba(13,110,253,0.3);color:#0d6efd"><i class="fas fa-edit"></i></button>
          <button onclick="showAkaunModal(<?=$p['id']?>,'<?=addslashes($p['nama'])?>','<?=addslashes($p['email']??'')?>')" class="btn btn-sm" title="Maklumat Akaun Login" style="background:rgba(255,193,7,0.1);border:1px solid rgba(255,193,7,0.3);color:#ffc107"><i class="fas fa-key"></i></button>
          <button onclick="confirmDelete(<?=$p['id']?>,'ajax_delete.php','<?=addslashes($p['nama'])?>')" class="btn btn-sm" style="background:rgba(204,0,1,0.1);border:1px solid rgba(204,0,1,0.3);color:#cc0001"><i class="fas fa-trash"></i></button>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <div class="staff-flex-grid mb-5">
  <?php foreach($uGroups as $sid => $group): 
    $pList = array_filter($group['pegawai'], fn($p) => $p['j_urutan'] > 2);
    if(!$pList) continue;
    $count = count($pList);
    $colGlow = $col . '22';
    $colOp = $col . '44';
  ?>
    <div class="subunit-wrapper" data-count="<?=min(5, $count)?>">
      <div class="subunit-header">
        <div class="subunit-dot" style="background:<?=$col?>"></div>
        <div class="subunit-title"><?=htmlspecialchars($group['nama'])?></div>
      </div>
      <div class="subunit-cards">
        <?php foreach($pList as $p): ?>
        <div class="pegawai-card" data-nama="<?=strtolower(htmlspecialchars($p['nama']))?>" data-unit="<?=$p['unit_id']?>" style="--unit-color:<?=$col?>; --unit-color-op:<?=$colOp?>; --unit-color-glow:<?=$colGlow?>">
          <div class="staff-card-futuristic">
            <div class="staff-avatar-wrapper">
              <img src="<?=getPegawaiImage($p['gambar'])?>" alt="<?=htmlspecialchars($p['nama'])?>" class="staff-avatar-futuristic">
              <div style="position:absolute;bottom:0;right:0;width:14px;height:14px;background:<?=$p['status']?'#198754':'#dc3545'?>;border-radius:50%;border:2px solid #0a0a0f"></div>
            </div>
            
            <div class="staff-name-futuristic"><?=htmlspecialchars($p['nama'])?></div>
            <div class="staff-pos-futuristic"><?=htmlspecialchars($p['nama_jawatan'])?></div>
            
            <div class="staff-contact-futuristic">
              <?php if($p['email']): ?><div><i class="fas fa-envelope" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['email'])?></div><?php endif; ?>
              <?php if($p['no_telefon_pejabat']): ?><div><i class="fas fa-phone" style="width:14px;color:<?=$col?>"></i><?=htmlspecialchars($p['no_telefon_pejabat'])?></div><?php endif; ?>
            </div>

            <div class="staff-actions-futuristic">
              <a href="view.php?id=<?=$p['id']?>" class="btn btn-sm" style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);color:#ccc"><i class="fas fa-eye"></i></a>
              <?php if(isAdmin()): ?>
              <button onclick="editPegawai(<?=$p['id']?>)" class="btn btn-sm" style="background:rgba(13,110,253,0.1);border:1px solid rgba(13,110,253,0.3);color:#0d6efd"><i class="fas fa-edit"></i></button>
              <button onclick="showAkaunModal(<?=$p['id']?>,'<?=addslashes($p['nama'])?>','<?=addslashes($p['email']??'')?>')" class="btn btn-sm" title="Maklumat Akaun Login" style="background:rgba(255,193,7,0.1);border:1px solid rgba(255,193,7,0.3);color:#ffc107"><i class="fas fa-key"></i></button>
              <button onclick="confirmDelete(<?=$p['id']?>,'ajax_delete.php','<?=addslashes($p['nama'])?>')" class="btn btn-sm" style="background:rgba(204,0,1,0.1);border:1px solid rgba(204,0,1,0.3);color:#cc0001"><i class="fas fa-trash"></i></button>
              <?php endif; ?>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  <?php endforeach; ?>
  </div>
<?php endforeach; ?>

<?php if(!$pegawaiList): ?>
<div class="col-12 text-center py-5" style="color:#555"><i class="fas fa-users fa-3x mb-3"></i><p>Tiada pegawai dijumpai</p></div>
<?php endif; ?>
</div>
</div>

</div>
</div>

<!-- Add/Edit Pegawai Modal -->
<div class="modal fade" id="pegawaiModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
  <h5 class="modal-title" style="color:#fff;font-weight:700"><i class="fas fa-user-plus me-2" style="color:#cc0001"></i><span id="modalTitle">Tambah Pegawai</span></h5>
  <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form id="pegawaiForm" enctype="multipart/form-data">
<div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <input type="hidden" name="id" id="pegawaiId">
  <div class="row g-3">
    <div class="col-md-4 text-center">
      <img id="imgPreview" src="<?=BASE_URL?>assets/images/default-avatar.png" style="width:120px;height:120px;border-radius:50%;object-fit:cover;border:3px solid rgba(204,0,1,0.4);margin-bottom:1rem">
      <div><label class="btn btn-sm btn-outline-primary"><i class="fas fa-camera me-1"></i>Pilih Gambar<input type="file" name="gambar" accept="image/*" style="display:none" onchange="previewImg(this)"></label></div>
    </div>
    <div class="col-md-8">
      <div class="row g-2">
        <div class="col-12"><label class="form-label">Nama Penuh *</label><input type="text" name="nama" class="form-control" required></div>
        <div class="col-md-6"><label class="form-label">Unit</label><select name="unit_id" id="unit_id" class="form-select" onchange="loadSubunits(this.value)"><option value="">— Tiada Unit (Ketua Sektor) —</option><?php foreach($units as $u): ?><option value="<?=$u['id']?>" <?=$unitId==$u['id']?'selected':''?>><?=htmlspecialchars($u['nama_unit'])?></option><?php endforeach; ?></select></div>
        <div class="col-md-6"><label class="form-label">Subunit</label><select name="subunit_id" id="subunit_id" class="form-select"><option value="">— Tiada Subunit —</option></select></div>
        <div class="col-md-6"><label class="form-label">Jawatan *</label><select name="jawatan_id" class="form-select" required><?php foreach($jawatanList as $j): ?><option value="<?=$j['id']?>"><?=htmlspecialchars($j['nama_jawatan'])?></option><?php endforeach; ?></select></div>
        <div class="col-md-6"><label class="form-label">Emel</label><input type="email" name="email" class="form-control"></div>
        <div class="col-md-6"><label class="form-label">No. Telefon</label><input type="text" name="no_telefon" class="form-control" placeholder="01x-xxxxxxx"></div>
        <div class="col-md-6"><label class="form-label">No. Telefon Pejabat</label><input type="text" name="no_telefon_pejabat" class="form-control"></div>
        <div class="col-md-6"><label class="form-label">Status</label><select name="status" class="form-select"><option value="1">Aktif</option><option value="0">Tidak Aktif</option></select></div>
      </div>
    </div>
    <div class="col-12"><label class="form-label">Bio / Perihal</label><textarea name="bio" class="form-control" rows="3"></textarea></div>
    <div class="col-12"><label class="form-label">Tugas Utama</label><textarea name="tugas_utama" class="form-control" rows="3" placeholder="Senaraikan tugas-tugas utama..."></textarea></div>
    <div class="col-md-3"><label class="form-label"><i class="fab fa-facebook me-1" style="color:#1877f2"></i>Facebook</label><input type="url" name="facebook" class="form-control" placeholder="https://..."></div>
    <div class="col-md-3"><label class="form-label"><i class="fab fa-twitter me-1" style="color:#1da1f2"></i>Twitter</label><input type="url" name="twitter" class="form-control" placeholder="https://..."></div>
    <div class="col-md-3"><label class="form-label"><i class="fab fa-linkedin me-1" style="color:#0077b5"></i>LinkedIn</label><input type="url" name="linkedin" class="form-control" placeholder="https://..."></div>
    <div class="col-md-3"><label class="form-label"><i class="fab fa-instagram me-1" style="color:#e4405f"></i>Instagram</label><input type="url" name="instagram" class="form-control" placeholder="https://..."></div>
  </div>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
  <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>Simpan</button>
</div>
</form>
</div></div></div>

<!-- Link Modal -->
<?php if($unitId && (isSuperAdmin() || currentUnitId() == $unitId)): ?>
<div class="modal fade" id="linkModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header"><h5 class="modal-title" style="color:#fff;font-weight:700"><i class="fas fa-link me-2" style="color:#0d6efd"></i>Tambah / Edit Link</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
<form id="linkForm" enctype="multipart/form-data">
<div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <input type="hidden" name="link_id" id="linkId">
  <input type="hidden" name="unit_id" value="<?=$unitId?>">
  
  <div class="row g-3">
    <div class="col-md-4 text-center">
      <div id="logoPreviewContainer" style="width:120px;height:120px;margin:0 auto 1rem;border:2px dashed rgba(255,255,255,0.1);border-radius:15px;display:flex;align-items:center;justify-content:center;overflow:hidden;background:rgba(255,255,255,0.02)">
        <img id="logoPreview" src="" style="width:100%;height:100%;object-fit:cover;display:none">
        <i id="logoPlaceholder" class="fas fa-image fa-2x" style="color:#333"></i>
      </div>
      <label class="btn btn-sm btn-outline-primary"><i class="fas fa-upload me-1"></i>Pilih Logo (500x500)<input type="file" name="logo" accept="image/*" style="display:none" onchange="previewLogo(this)"></label>
      <div style="font-size:.65rem;color:#555;margin-top:.5rem">Format: JPG, PNG. Rekomendasi: 500x500px</div>
    </div>
    <div class="col-md-8">
      <div class="mb-3"><label class="form-label">Nama Link *</label><input type="text" name="link_nama" class="form-control" required placeholder="Contoh: Dashboard MyPWA"></div>
      <div class="mb-3"><label class="form-label">URL *</label><input type="url" name="link_url" class="form-control" required placeholder="https://..."></div>
      <div class="mb-3"><label class="form-label">Subunit</label><select name="subunit_id" id="link_subunit_id" class="form-select"><option value="">— Utama / Umum —</option><?php foreach($subunitList as $su): ?><option value="<?=$su['id']?>"><?=htmlspecialchars($su['nama_subunit'])?></option><?php endforeach; ?></select></div>
    </div>
  </div>

  <div class="row g-2 mt-2">
    <div class="col-md-6"><label class="form-label">Ikon (Jika tiada logo)</label><input type="text" name="link_ikon" class="form-control" placeholder="fas fa-link" value="fas fa-link"></div>
    <div class="col-md-6"><label class="form-label">Warna Tema</label><input type="color" name="link_warna" class="form-control form-control-color" value="#0d6efd" style="height:45px"></div>
  </div>
  <div class="mt-2"><label class="form-label">Deskripsi Ringkas</label><input type="text" name="link_desc" class="form-control" placeholder="Penerangan ringkas..."></div>
  
  <div class="mt-3" style="background:rgba(25,135,84,0.06);border:1px solid rgba(25,135,84,0.2);border-radius:12px;padding:.75rem 1rem">
    <label style="display:flex;align-items:center;gap:.75rem;cursor:pointer;margin:0">
      <input type="checkbox" name="link_awam" id="linkAwam" value="1" style="accent-color:#198754;width:16px;height:16px">
      <div>
        <div style="font-size:.9rem;font-weight:600;color:#fff"><i class="fas fa-globe me-2" style="color:#198754"></i>Paparkan di Halaman Awam</div>
        <div style="font-size:.75rem;color:#555">Link akan kelihatan kepada orang awam tanpa log masuk</div>
      </div>
    </label>
  </div>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
  <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>Simpan</button>
</div>
</form>
</div></div></div>
<?php endif; ?>

<!-- Modal Akaun Login -->
<?php if(isAdmin()): ?>
<div class="modal fade" id="akaunModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
  <h5 class="modal-title" style="color:#fff;font-weight:700"><i class="fas fa-key me-2" style="color:#ffc107"></i>Maklumat Akaun Login</h5>
  <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body" id="akaunBody">
  <div class="text-center py-4"><div class="spinner-border text-primary"></div></div>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
</div>
</div></div></div>

<!-- Modal Reset Password -->
<div class="modal fade" id="resetModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
  <h5 class="modal-title" style="color:#fff;font-weight:700"><i class="fas fa-unlock-alt me-2" style="color:#cc0001"></i>Reset Password</h5>
  <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form id="resetForm">
<div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <input type="hidden" name="pegawai_id" id="resetPegawaiId">
  <div class="mb-3">
    <label class="form-label">Password Baharu</label>
    <div style="position:relative">
      <input type="text" name="new_pass" id="newPassInput" class="form-control" placeholder="Min 6 aksara" value="password123">
    </div>
    <div style="font-size:.75rem;color:#555;margin-top:.35rem"><i class="fas fa-info-circle me-1"></i>Biarkan 'password123' untuk reset ke default</div>
  </div>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
  <button type="submit" class="btn btn-danger"><i class="fas fa-sync me-2"></i>Reset Password</button>
</div>
</form>
</div></div></div>
<?php endif; ?>

<script>
const unitId=<?=$unitId?0:0?>;
function showAddModal(){document.getElementById('modalTitle').textContent='Tambah Pegawai';document.getElementById('pegawaiForm').reset();document.getElementById('pegawaiId').value='';document.getElementById('imgPreview').src='<?=BASE_URL?>assets/images/default-avatar.png';loadSubunits(document.getElementById('unit_id').value);new bootstrap.Modal(document.getElementById('pegawaiModal')).show();}
function editPegawai(id){
  fetch('ajax_get.php?id='+id).then(r=>r.json()).then(d=>{
    if(!d.success)return;
    const p=d.data;document.getElementById('modalTitle').textContent='Edit Pegawai';
    document.getElementById('pegawaiId').value=p.id;
    const f=document.getElementById('pegawaiForm');
    ['nama','email','no_telefon','no_telefon_pejabat','bio','tugas_utama','facebook','twitter','linkedin','instagram'].forEach(k=>{if(f[k])f[k].value=p[k]??'';});
    f.unit_id.value=p.unit_id??'';
    loadSubunits(p.unit_id, p.subunit_id);
    f.jawatan_id.value=p.jawatan_id;f.status.value=p.status;
    document.getElementById('imgPreview').src=p.gambar_url||'<?=BASE_URL?>assets/images/default-avatar.png';
    new bootstrap.Modal(document.getElementById('pegawaiModal')).show();
  });
}
function loadSubunits(unit_id, selected_id = null) {
  const select = document.getElementById('subunit_id');
  select.innerHTML = '<option value="">— Tiada Subunit —</option>';
  if (!unit_id) return;
  fetch('ajax_get_subunits.php?unit_id='+unit_id).then(r=>r.json()).then(d=>{
    if(d.success && d.data.length) {
      d.data.forEach(su => {
        const opt = document.createElement('option');
        opt.value = su.id;
        opt.textContent = su.nama_subunit;
        if(selected_id && su.id == selected_id) opt.selected = true;
        select.appendChild(opt);
      });
    }
  });
}
function previewImg(input){if(input.files&&input.files[0]){const r=new FileReader();r.onload=e=>document.getElementById('imgPreview').src=e.target.result;r.readAsDataURL(input.files[0]);}}
document.getElementById('pegawaiForm').addEventListener('submit',function(e){
  e.preventDefault();
  const fd=new FormData(this);
  const id=document.getElementById('pegawaiId').value;
  fetch(id?'ajax_update.php':'ajax_add.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    bootstrap.Modal.getInstance(document.getElementById('pegawaiModal'))?.hide();
    if(d.success&&!id&&d.data){
      // Tunjuk kredential akaun yang baru dijana
      Swal.fire({title:'<i class="fas fa-check-circle" style="color:#198754"></i> Pegawai Ditambah!',
        html:`<div style="text-align:left;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);border-radius:12px;padding:1rem;margin-top:.5rem">
          <div style="font-size:.8rem;color:#888;margin-bottom:.75rem">Maklumat Akaun Login yang Dijana:</div>
          <div style="display:flex;align-items:center;gap:.75rem;margin-bottom:.5rem">
            <i class="fas fa-envelope" style="color:#0d6efd;width:20px"></i>
            <div><div style="font-size:.7rem;color:#555">Username / Email</div><div style="font-weight:700;color:#fff">${d.data.email}</div></div>
          </div>
          <div style="display:flex;align-items:center;gap:.75rem">
            <i class="fas fa-lock" style="color:#ffc107;width:20px"></i>
            <div><div style="font-size:.7rem;color:#555">Password Default</div><div style="font-weight:700;color:#fff;letter-spacing:2px">${d.data.password}</div></div>
          </div>
        </div>
        <div style="font-size:.75rem;color:#555;margin-top:.75rem"><i class="fas fa-info-circle me-1"></i>Sila maklumkan kepada pegawai berkenaan untuk menukar password selepas log masuk pertama.</div>`,
        background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#198754',confirmButtonText:'<i class="fas fa-check me-1"></i>Faham'});
      setTimeout(()=>location.reload(),500);
    } else {
      Swal.fire({toast:true,position:'top-end',icon:d.success?'success':'error',title:d.message,showConfirmButton:false,timer:3000,background:'#0f0f1a',color:'#e0e0e0'});
      if(d.success)setTimeout(()=>location.reload(),1500);
    }
  });
});
function showLinkModal(){document.getElementById('linkId').value='';document.getElementById('linkForm').reset();document.querySelector('[name=link_ikon]').value='fas fa-link';document.querySelector('[name=unit_id]').value=unitId;document.getElementById('linkAwam').checked=false;document.getElementById('logoPreview').style.display='none';document.getElementById('logoPlaceholder').style.display='block';new bootstrap.Modal(document.getElementById('linkModal')).show();}
function editLink(id){fetch('ajax_link.php?action=get&id='+id).then(r=>r.json()).then(d=>{if(!d.success)return;const l=d.data;document.getElementById('linkId').value=l.id;document.querySelector('[name=link_nama]').value=l.nama;document.querySelector('[name=link_url]').value=l.url;document.querySelector('[name=link_ikon]').value=l.ikon||'fas fa-link';document.querySelector('[name=link_warna]').value=l.warna||'#0d6efd';document.querySelector('[name=link_desc]').value=l.deskripsi??'';document.getElementById('linkAwam').checked=l.awam==1;document.getElementById('link_subunit_id').value=l.subunit_id??'';if(l.logo_url){document.getElementById('logoPreview').src=l.logo_url;document.getElementById('logoPreview').style.display='block';document.getElementById('logoPlaceholder').style.display='none';}else{document.getElementById('logoPreview').style.display='none';document.getElementById('logoPlaceholder').style.display='block';}new bootstrap.Modal(document.getElementById('linkModal')).show();});}
function previewLogo(input){if(input.files&&input.files[0]){const r=new FileReader();r.onload=e=>{document.getElementById('logoPreview').src=e.target.result;document.getElementById('logoPreview').style.display='block';document.getElementById('logoPlaceholder').style.display='none';};r.readAsDataURL(input.files[0]);}}
function deleteLink(id,name){Swal.fire({title:'Padam Link?',html:`Padam <b>${name}</b>?`,icon:'warning',background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#cc0001',cancelButtonColor:'#333',showCancelButton:true,confirmButtonText:'Padam'}).then(r=>{if(r.isConfirmed)fetch('ajax_link.php?action=delete&id='+id+'&csrf=<?=$csrf?>').then(r=>r.json()).then(d=>{Swal.fire({toast:true,position:'top-end',icon:d.success?'success':'error',title:d.message,showConfirmButton:false,timer:2500,background:'#0f0f1a',color:'#e0e0e0'});if(d.success)setTimeout(()=>location.reload(),1500);});});}
function toggleAwam(id){fetch('ajax_link.php?action=toggle_awam&id='+id+'&csrf=<?=$csrf?>').then(r=>r.json()).then(d=>{if(!d.success)return;const isAwam=d.data.awam==1;const badge=document.getElementById('awam-badge-'+id);const btn=document.getElementById('awam-btn-'+id);if(badge){badge.innerHTML='<i class="fas '+(isAwam?'fa-globe':'fa-lock')+' me-1"></i>'+(isAwam?'Awam':'Peribadi');badge.style.background=isAwam?'rgba(25,135,84,0.15)':'rgba(108,117,125,0.15)';badge.style.color=isAwam?'#75c99c':'#888';badge.style.borderColor=isAwam?'rgba(25,135,84,0.3)':'rgba(108,117,125,0.3)';}if(btn){btn.innerHTML='<i class="fas '+(isAwam?'fa-globe':'fa-lock')+'">';btn.style.background=isAwam?'rgba(25,135,84,0.15)':'rgba(108,117,125,0.1)';btn.style.color=isAwam?'#75c99c':'#888';btn.title=isAwam?'Jadikan Peribadi':'Jadikan Awam';}Swal.fire({toast:true,position:'top-end',icon:'success',title:d.message,showConfirmButton:false,timer:2000,background:'#0f0f1a',color:'#e0e0e0'});});}
document.getElementById('linkForm')?.addEventListener('submit',function(e){e.preventDefault();const fd=new FormData(this);fetch('ajax_link.php?action=save',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{bootstrap.Modal.getInstance(document.getElementById('linkModal'))?.hide();Swal.fire({toast:true,position:'top-end',icon:d.success?'success':'error',title:d.message,showConfirmButton:false,timer:2500,background:'#0f0f1a',color:'#e0e0e0'});if(d.success)setTimeout(()=>location.reload(),1500);});});

function showAkaunModal(pegawai_id,nama,email){
  document.getElementById('akaunBody').innerHTML='<div class="text-center py-4"><div class="spinner-border text-warning"></div></div>';
  new bootstrap.Modal(document.getElementById('akaunModal')).show();
  fetch('ajax_password.php?action=info&pegawai_id='+pegawai_id).then(r=>r.json()).then(d=>{
    if(!d.success){
      document.getElementById('akaunBody').innerHTML=`<div style="text-align:center;padding:1.5rem;color:#555"><i class="fas fa-user-times fa-2x mb-2"></i><p>Tiada akaun login untuk pegawai ini.</p><p style="font-size:.8rem">Email: <b style="color:#fff">${email||'-'}</b></p><p style="font-size:.75rem;color:#444">Mungkin pegawai ini ditambah sebelum sistem auto-jana akaun. Sila edit dan simpan semula untuk jana akaun.</p></div>`;return;
    }
    const u=d.data;
    const lastLogin=u.last_login?new Date(u.last_login).toLocaleString('ms-MY'):'Belum pernah log masuk';
    document.getElementById('akaunBody').innerHTML=`
    <div style="margin-bottom:1rem;padding:1rem;background:rgba(255,193,7,0.06);border:1px solid rgba(255,193,7,0.15);border-radius:12px">
      <div style="font-size:.7rem;color:#888;margin-bottom:.75rem;text-transform:uppercase;letter-spacing:1px">Maklumat Akaun</div>
      <div style="display:grid;gap:.5rem">
        <div style="display:flex;gap:.75rem;align-items:center"><i class="fas fa-envelope" style="color:#0d6efd;width:18px"></i><div><div style="font-size:.68rem;color:#555">Username / Email</div><div style="font-weight:600;color:#fff;font-size:.9rem">${u.email}</div></div></div>
        <div style="display:flex;gap:.75rem;align-items:center"><i class="fas fa-id-badge" style="color:#888;width:18px"></i><div><div style="font-size:.68rem;color:#555">Role</div><div style="font-weight:600;color:#fff;font-size:.9rem;text-transform:capitalize">${u.role}</div></div></div>
        <div style="display:flex;gap:.75rem;align-items:center"><i class="fas fa-clock" style="color:#888;width:18px"></i><div><div style="font-size:.68rem;color:#555">Log Masuk Terakhir</div><div style="font-weight:600;color:#fff;font-size:.85rem">${lastLogin}</div></div></div>
        <div style="display:flex;gap:.75rem;align-items:center"><i class="fas fa-circle" style="color:${u.status?'#198754':'#dc3545'};width:18px"></i><div><div style="font-size:.68rem;color:#555">Status</div><div style="font-weight:600;color:${u.status?'#75c99c':'#ff6b6b'};font-size:.9rem">${u.status?'Aktif':'Tidak Aktif'}</div></div></div>
      </div>
    </div>
    <div style="display:flex;gap:.5rem;flex-wrap:wrap">
      <button onclick="openResetModal(${pegawai_id})" class="btn btn-sm btn-danger flex-fill"><i class="fas fa-key me-1"></i>Reset Password</button>
      <button onclick="resetDefault(${pegawai_id})" class="btn btn-sm btn-warning flex-fill" style="color:#000"><i class="fas fa-undo me-1"></i>Reset ke Default</button>
      <button onclick="toggleAkaun(${pegawai_id},${u.status})" class="btn btn-sm flex-fill" style="background:${u.status?'rgba(108,117,125,0.2)':'rgba(25,135,84,0.2)'};border:1px solid ${u.status?'rgba(108,117,125,0.3)':'rgba(25,135,84,0.3)'};color:${u.status?'#888':'#75c99c'}">
        <i class="fas fa-${u.status?'ban':'check-circle'} me-1"></i>${u.status?'Lumpuhkan':'Aktifkan'} Akaun
      </button>
    </div>`;
  });
}
function openResetModal(pid){
  bootstrap.Modal.getInstance(document.getElementById('akaunModal'))?.hide();
  document.getElementById('resetPegawaiId').value=pid;
  document.getElementById('newPassInput').value='password123';
  new bootstrap.Modal(document.getElementById('resetModal')).show();
}
function resetDefault(pid){
  Swal.fire({title:'Reset ke password123?',text:'Password akan ditukar ke password123',icon:'warning',background:'#0f0f1a',color:'#e0e0e0',showCancelButton:true,confirmButtonColor:'#cc0001',cancelButtonColor:'#333',confirmButtonText:'Ya, Reset'}).then(r=>{
    if(!r.isConfirmed)return;
    fetch('ajax_password.php?action=reset_default&pegawai_id='+pid+'&csrf=<?=$csrf?>').then(r=>r.json()).then(d=>{
      bootstrap.Modal.getInstance(document.getElementById('akaunModal'))?.hide();
      Swal.fire({title:d.success?'Berjaya!':'Gagal',html:d.success?`<div style="text-align:center"><i class="fas fa-lock" style="color:#ffc107;font-size:2rem;margin-bottom:.75rem"></i><br><div style="font-size:.85rem;color:#888;margin-bottom:.5rem">Password baru:</div><div style="font-size:1.5rem;font-weight:800;color:#fff;letter-spacing:3px">${d.data?.password}</div></div>`:d.message,icon:d.success?'success':'error',background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#198754'});
    });
  });
}
function toggleAkaun(pid,currentStatus){
  fetch('ajax_password.php?action=toggle_status&pegawai_id='+pid+'&csrf=<?=$csrf?>').then(r=>r.json()).then(d=>{
    Swal.fire({toast:true,position:'top-end',icon:d.success?'success':'error',title:d.message,showConfirmButton:false,timer:2000,background:'#0f0f1a',color:'#e0e0e0'});
    if(d.success)bootstrap.Modal.getInstance(document.getElementById('akaunModal'))?.hide();
  });
}
document.getElementById('resetForm')?.addEventListener('submit',function(e){
  e.preventDefault();const fd=new FormData(this);
  fetch('ajax_password.php?action=reset',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    bootstrap.Modal.getInstance(document.getElementById('resetModal'))?.hide();
    Swal.fire({title:d.success?'Password Direset!':'Gagal',html:d.success?`<div style="text-align:center"><i class="fas fa-unlock-alt" style="color:#ffc107;font-size:2rem;margin-bottom:.75rem"></i><br><div style="font-size:.85rem;color:#888;margin-bottom:.5rem">Password baru:</div><div style="font-size:1.5rem;font-weight:800;color:#fff;letter-spacing:3px">${d.data?.password}</div></div>`:d.message,icon:d.success?'success':'error',background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#198754'});
  });
});
</script>

<?php require_once __DIR__.'/../../templates/footer.php'; ?>
