// SPM Dashboard - Main JS
document.addEventListener('DOMContentLoaded',function(){
  // Loading screen
  setTimeout(()=>{
    const ls=document.getElementById('loadingScreen');
    if(ls){ls.style.opacity='0';ls.style.transition='opacity .5s';setTimeout(()=>ls.remove(),500);}
  },1500);

  // Animate stats
  document.querySelectorAll('.stat-number[data-count]').forEach(el=>{
    const target=+el.dataset.count;
    let cur=0;const inc=target/50;
    const timer=setInterval(()=>{cur=Math.min(cur+inc,target);el.textContent=Math.floor(cur);if(cur>=target)clearInterval(timer);},30);
  });

  // Global search
  const gs=document.getElementById('globalSearch');
  if(gs){
    let t;
    gs.addEventListener('input',function(){
      clearTimeout(t);
      const q=this.value.trim();
      if(q.length<2)return;
      t=setTimeout(()=>{
        fetch(BASE_URL+'modules/pegawai/search.php?q='+encodeURIComponent(q))
        .then(r=>r.json()).then(data=>{showSearchResults(data,gs);}).catch(()=>{});
      },400);
    });
    gs.addEventListener('blur',()=>setTimeout(()=>{const sr=document.getElementById('searchResults');if(sr)sr.remove();},200));
  }
});

function showSearchResults(data,input){
  let sr=document.getElementById('searchResults');
  if(!sr){sr=document.createElement('div');sr.id='searchResults';sr.style.cssText='position:absolute;top:100%;right:0;width:350px;background:#0f0f1a;border:1px solid rgba(204,0,1,0.3);border-radius:16px;z-index:9999;max-height:400px;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,0.5);margin-top:.5rem';input.parentElement.style.position='relative';input.parentElement.appendChild(sr);}
  if(!data.length){sr.innerHTML='<div style="padding:1.5rem;text-align:center;color:#555">Tiada keputusan</div>';return;}
  sr.innerHTML=data.map(p=>`<a href="${BASE_URL}modules/pegawai/view.php?id=${p.id}" style="display:flex;align-items:center;gap:.75rem;padding:.75rem 1rem;text-decoration:none;color:#e0e0e0;border-bottom:1px solid rgba(255,255,255,0.04);transition:background .2s" onmouseover="this.style.background='rgba(204,0,1,0.08)'" onmouseout="this.style.background=''">
    <img src="${p.gambar_url}" style="width:40px;height:40px;border-radius:50%;object-fit:cover;border:2px solid rgba(204,0,1,0.3)">
    <div><div style="font-weight:600;font-size:.9rem">${p.nama}</div><div style="font-size:.75rem;color:#666">${p.jawatan} &bull; ${p.unit}</div></div>
  </a>`).join('');
}

function toggleSidebar(){
  const s=document.getElementById('sidebar');
  const o=document.getElementById('darkOverlay');
  s.classList.toggle('show');
  if(s.classList.contains('show')){o.style.display='block';}else{o.style.display='none';}
}

function closeSidebar(){
  document.getElementById('sidebar').classList.remove('show');
  document.getElementById('darkOverlay').style.display='none';
}

function confirmDelete(id,url,name){
  Swal.fire({
    title:'Padam Rekod?',
    html:`Adakah anda pasti untuk memadam <b>${name}</b>?`,
    icon:'warning',background:'#0f0f1a',color:'#e0e0e0',
    confirmButtonColor:'#cc0001',cancelButtonColor:'#333',
    confirmButtonText:'Ya, Padam!',cancelButtonText:'Batal',
    showCancelButton:true
  }).then(r=>{
    if(r.isConfirmed){
      fetch(url+'?id='+id+'&csrf='+CSRF_TOKEN)
      .then(res=>res.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 showToast(msg,type='success'){
  Swal.fire({toast:true,position:'top-end',icon:type,title:msg,showConfirmButton:false,timer:3000,timerProgressBar:true,background:'#0f0f1a',color:'#e0e0e0'});
}

function ajaxSubmit(form,callback){
  const data=new FormData(form);
  fetch(form.action,{method:'POST',body:data})
  .then(r=>r.json()).then(d=>{
    if(d.success){showToast(d.message||'Berjaya!','success');}
    else{showToast(d.message||'Ralat berlaku!','error');}
    if(callback)callback(d);
  }).catch(()=>showToast('Ralat rangkaian!','error'));
}

var BASE_URL = document.querySelector('meta[name="base-url"]')?.content || '/sepmu/';
var CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]')?.content || '';
