<?php
$pageTitle='Tetapan Sistem';
require_once __DIR__.'/../../config/functions.php';
requireLogin();if(!isSuperAdmin())redirect(BASE_URL);
$users=$pdo->query("SELECT u.*,p.nama as nama_pegawai FROM users u LEFT JOIN pegawai p ON u.pegawai_id=p.id ORDER BY u.id")->fetchAll();
$units=$pdo->query("SELECT * FROM unit WHERE status=1 ORDER BY urutan ASC, id ASC")->fetchAll();
$subunits=$pdo->query("SELECT s.*, u.nama_unit FROM subunit s JOIN unit u ON s.unit_id=u.id ORDER BY u.urutan ASC, u.id ASC, s.nama_subunit ASC")->fetchAll();
$logs=$pdo->query("SELECT a.*,u.username FROM activity_log a LEFT JOIN users u ON a.user_id=u.id ORDER BY a.created_at DESC LIMIT 20")->fetchAll();
$breadcrumb=[['label'=>'Utama','url'=>BASE_URL],['label'=>'Admin','url'=>'#']];
require_once __DIR__.'/../../templates/header.php';
?>
<meta name="base-url" content="<?=BASE_URL?>">
<meta name="csrf-token" content="<?=$csrf?>">
<?php require_once __DIR__.'/../../templates/sidebar.php'; ?>
<div class="main-content">
<?php require_once __DIR__.'/../../templates/topbar.php'; ?>
<div style="padding:2rem">

<ul class="nav nav-pills mb-4" id="adminTabs" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);border-radius:14px;padding:.4rem">
  <li class="nav-item"><a class="nav-link active" href="#users" data-bs-toggle="tab" style="border-radius:10px;font-size:.9rem"><i class="fas fa-users me-2"></i>Pengguna</a></li>
  <li class="nav-item"><a class="nav-link" href="#logo" data-bs-toggle="tab" style="border-radius:10px;font-size:.9rem"><i class="fas fa-image me-2"></i>Logo Sektor</a></li>
  <li class="nav-item"><a class="nav-link" href="#units" data-bs-toggle="tab" style="border-radius:10px;font-size:.9rem"><i class="fas fa-building me-2"></i>Unit & Subunit</a></li>
  <li class="nav-item"><a class="nav-link" href="#logs" data-bs-toggle="tab" style="border-radius:10px;font-size:.9rem"><i class="fas fa-list me-2"></i>Log Aktiviti</a></li>
</ul>

<div class="tab-content">
<div class="tab-pane fade show active" id="users">
<div class="content-card">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <h3 style="font-size:1rem;font-weight:700;color:#fff;margin:0">Senarai Pengguna</h3>
    <button class="btn btn-primary btn-sm" onclick="showUserModal()"><i class="fas fa-plus me-1"></i>Tambah Pengguna</button>
  </div>
  <div class="table-responsive">
  <table class="table" id="usersTable">
    <thead><tr><th>Username</th><th>Email</th><th>Role</th><th>Unit</th><th>Status</th><th>Log Masuk Terakhir</th><th>Tindakan</th></tr></thead>
    <tbody>
    <?php foreach($users as $u): ?>
    <tr>
      <td style="font-weight:600;color:#fff"><?=htmlspecialchars($u['username'])?></td>
      <td style="color:#888"><?=htmlspecialchars($u['email'])?></td>
      <td><span class="badge" style="background:rgba(204,0,1,0.15);color:#cc0001;border:1px solid rgba(204,0,1,0.3)"><?=strtoupper($u['role'])?></span></td>
      <td style="color:#888;font-size:.85rem"><?=$u['nama_pegawai']??'-'?></td>
      <td><?=$u['status']?'<span class="badge bg-success">Aktif</span>':'<span class="badge bg-secondary">Tidak Aktif</span>'?></td>
      <td style="color:#555;font-size:.8rem"><?=$u['last_login']?formatDate($u['last_login'],'d M Y H:i'):'-'?></td>
      <td>
        <button onclick="resetPwd(<?=$u['id']?>,`<?=addslashes($u['username'])?>`)" class="btn btn-sm" title="Reset Kata Laluan" style="background:rgba(255,200,7,0.1);border:1px solid rgba(255,200,7,0.3);color:#ffc107;border-radius:8px;font-size:.75rem"><i class="fas fa-key"></i></button>
        <button onclick="deleteUser(<?=$u['id']?>,`<?=addslashes($u['username'])?>`)" class="btn btn-sm" title="Padam Pengguna" style="background:rgba(204,0,1,0.1);border:1px solid rgba(204,0,1,0.3);color:#cc0001;border-radius:8px;font-size:.75rem"><i class="fas fa-trash"></i></button>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  </div>
</div>
</div>

<div class="tab-pane fade" id="logo">
<?php $sektorData=getSektorData(); ?>
<div class="row g-4">
  <!-- LOGO UTAMA 1 -->
  <div class="col-lg-4">
    <div class="content-card h-100">
      <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:1.5rem"><i class="fas fa-image me-2" style="color:#cc0001"></i>Logo 1 (Sidebar / Menu)</h3>
      <div style="min-height:120px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.03);border:1px dashed rgba(255,255,255,0.1);border-radius:16px;padding:2rem;margin-bottom:1.5rem">
        <?php if(!empty($sektorData['logo'])&&file_exists(UPLOAD_PATH.'logo/'.$sektorData['logo'])): ?>
        <img src="<?=UPLOAD_URL.'logo/'.$sektorData['logo']?>" style="max-height:100px;max-width:100%;object-fit:contain" id="currentLogo_logo">
        <?php else: ?>
        <div id="currentLogo_logo"><?=getSektorLogo('large')?></div>
        <?php endif; ?>
      </div>
      <form id="logoForm_logo" enctype="multipart/form-data" class="mb-3">
        <input type="hidden" name="csrf_token" value="<?=$csrf?>">
        <input type="hidden" name="action" value="upload_logo">
        <input type="hidden" name="target" value="logo">
        <div class="input-group">
          <input type="file" name="logo" class="form-control" accept="image/*,.svg" onchange="previewLogo(this, 'logo')">
          <button type="button" onclick="submitLogoUpload('logo')" class="btn btn-primary"><i class="fas fa-upload"></i></button>
        </div>
      </form>
      <div id="preview_logo" style="display:none;margin-bottom:1rem;padding:.5rem;background:rgba(0,0,0,0.2);border-radius:8px;text-align:center">
        <img id="imgPreview_logo" style="max-height:60px">
      </div>
      <?php if(!empty($sektorData['logo'])): ?>
      <button onclick="deleteLogo('logo')" class="btn btn-sm btn-outline-danger w-100"><i class="fas fa-trash me-1"></i>Padam & Guna Teks</button>
      <?php endif; ?>
    </div>
  </div>

  <!-- LOGO UTAMA 2 -->
  <div class="col-lg-4">
    <div class="content-card h-100">
      <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:1.5rem"><i class="fas fa-star me-2" style="color:#ffc107"></i>Logo 2 (Halaman Utama Portal)</h3>
      <div style="min-height:120px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.03);border:1px dashed rgba(255,255,255,0.1);border-radius:16px;padding:2rem;margin-bottom:1.5rem">
        <?php if(!empty($sektorData['logo_2'])&&file_exists(UPLOAD_PATH.'logo/'.$sektorData['logo_2'])): ?>
        <img src="<?=UPLOAD_URL.'logo/'.$sektorData['logo_2']?>" style="max-height:100px;max-width:100%;object-fit:contain" id="currentLogo_logo_2">
        <?php else: ?>
        <div id="currentLogo_logo_2" style="font-size:1.5rem;font-weight:900;color:#fff">Sektor Pembangunan Murid</div>
        <?php endif; ?>
      </div>
      <form id="logoForm_logo_2" enctype="multipart/form-data" class="mb-3">
        <input type="hidden" name="csrf_token" value="<?=$csrf?>">
        <input type="hidden" name="action" value="upload_logo">
        <input type="hidden" name="target" value="logo_2">
        <div class="input-group">
          <input type="file" name="logo_2" class="form-control" accept="image/*,.svg" onchange="previewLogo(this, 'logo_2')">
          <button type="button" onclick="submitLogoUpload('logo_2')" class="btn btn-primary"><i class="fas fa-upload"></i></button>
        </div>
      </form>
      <div id="preview_logo_2" style="display:none;margin-bottom:1rem;padding:.5rem;background:rgba(0,0,0,0.2);border-radius:8px;text-align:center">
        <img id="imgPreview_logo_2" style="max-height:60px">
      </div>
      <?php if(!empty($sektorData['logo_2'])): ?>
      <button onclick="deleteLogo('logo_2')" class="btn btn-sm btn-outline-danger w-100"><i class="fas fa-trash me-1"></i>Padam & Guna Teks</button>
      <?php endif; ?>
    </div>
  </div>

  <!-- LOGO UTAMA 3 (LOADING) -->
  <div class="col-lg-4">
    <div class="content-card h-100">
      <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:1.5rem"><i class="fas fa-spinner me-2" style="color:#0d6efd"></i>Logo 3 (Loading Screen)</h3>
      <div style="min-height:120px;display:flex;align-items:center;justify-content:center;background:rgba(255,255,255,0.03);border:1px dashed rgba(255,255,255,0.1);border-radius:16px;padding:2rem;margin-bottom:1.5rem">
        <?php if(!empty($sektorData['logo_3'])&&file_exists(UPLOAD_PATH.'logo/'.$sektorData['logo_3'])): ?>
        <img src="<?=UPLOAD_URL.'logo/'.$sektorData['logo_3']?>" style="max-height:100px;max-width:100%;object-fit:contain" id="currentLogo_logo_3">
        <?php else: ?>
        <div id="currentLogo_logo_3" style="font-size:1.5rem;font-weight:900;color:#fff"><?=getSektorLogo('large')?></div>
        <?php endif; ?>
      </div>
      <form id="logoForm_logo_3" enctype="multipart/form-data" class="mb-3">
        <input type="hidden" name="csrf_token" value="<?=$csrf?>">
        <input type="hidden" name="action" value="upload_logo">
        <input type="hidden" name="target" value="logo_3">
        <div class="input-group">
          <input type="file" name="logo_3" class="form-control" accept="image/*,.svg" onchange="previewLogo(this, 'logo_3')">
          <button type="button" onclick="submitLogoUpload('logo_3')" class="btn btn-primary"><i class="fas fa-upload"></i></button>
        </div>
      </form>
      <div id="preview_logo_3" style="display:none;margin-bottom:1rem;padding:.5rem;background:rgba(0,0,0,0.2);border-radius:8px;text-align:center">
        <img id="imgPreview_logo_3" style="max-height:60px">
      </div>
      <?php if(!empty($sektorData['logo_3'])): ?>
      <button onclick="deleteLogo('logo_3')" class="btn btn-sm btn-outline-danger w-100"><i class="fas fa-trash me-1"></i>Padam & Guna Teks</button>
      <?php endif; ?>
    </div>
  </div>
</div>
</div>

<div class="tab-pane fade" id="logs">
<div class="content-card">
  <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:1.5rem">Log Aktiviti Terkini</h3>
  <div class="timeline">
  <?php foreach($logs as $l): ?>
  <div class="timeline-item">
    <div style="background:rgba(26,26,46,0.5);border:1px solid rgba(255,255,255,0.05);border-radius:12px;padding:1rem">
      <div style="display:flex;align-items:center;gap:.75rem;margin-bottom:.4rem">
        <span style="background:rgba(204,0,1,0.1);color:#cc0001;border-radius:6px;padding:.2rem .5rem;font-size:.75rem;font-weight:600"><?=htmlspecialchars($l['modul'])?></span>
        <span style="font-size:.8rem;font-weight:600;color:#fff"><?=htmlspecialchars($l['username']??'Sistem')?></span>
        <span style="font-size:.75rem;color:#444;margin-left:auto"><?=timeAgo($l['created_at'])?></span>
      </div>
      <div style="font-size:.85rem;color:#666"><?=htmlspecialchars($l['aksi'])?> — <?=htmlspecialchars($l['deskripsi']??'')?></div>
    </div>
  </div>
  <?php endforeach; ?>
  </div>
</div>
</div></div>
</div>

<div class="tab-pane fade" id="units">
  <div class="row g-4">
    <div class="col-md-6">
      <div class="content-card">
        <div class="d-flex align-items-center justify-content-between mb-3">
          <h3 style="font-size:1rem;font-weight:700;color:#fff;margin:0">Senarai Unit</h3>
          <button class="btn btn-primary btn-sm" onclick="showUnitModal()"><i class="fas fa-plus me-1"></i>Tambah Unit</button>
        </div>
        <div class="table-responsive">
          <table class="table">
            <thead><tr><th>Nama Unit</th><th>Kod</th><th>Urutan</th><th>Tindakan</th></tr></thead>
            <tbody>
            <?php foreach($units as $u): ?>
            <tr>
              <td><i class="<?=htmlspecialchars($u['ikon'])?> me-2" style="color:<?=$u['warna']?>"></i><?=htmlspecialchars($u['nama_unit'])?></td>
              <td><?=htmlspecialchars($u['kod'])?></td>
              <td><?=$u['urutan']?></td>
              <td>
                <button onclick="editUnit(<?=$u['id']?>, `<?=htmlspecialchars(addslashes(json_encode($u)))?>`)" class="btn btn-sm" style="background:rgba(13,110,253,0.1);color:#0d6efd;border-radius:8px"><i class="fas fa-edit"></i></button>
                <button onclick="deleteData(<?=$u['id']?>, 'unit', '<?=addslashes($u['nama_unit'])?>')" class="btn btn-sm" style="background:rgba(204,0,1,0.1);color:#cc0001;border-radius:8px"><i class="fas fa-trash"></i></button>
              </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <div class="content-card">
        <div class="d-flex align-items-center justify-content-between mb-3">
          <h3 style="font-size:1rem;font-weight:700;color:#fff;margin:0">Senarai Subunit</h3>
          <button class="btn btn-primary btn-sm" onclick="showSubunitModal()"><i class="fas fa-plus me-1"></i>Tambah Subunit</button>
        </div>
        <div class="table-responsive">
          <table class="table">
            <thead><tr><th>Subunit</th><th>Unit Induk</th><th>Tindakan</th></tr></thead>
            <tbody>
            <?php foreach($subunits as $su): ?>
            <tr>
              <td><?=htmlspecialchars($su['nama_subunit'])?></td>
              <td><span class="badge bg-secondary"><?=htmlspecialchars($su['nama_unit'])?></span></td>
              <td>
                <button onclick="editSubunit(<?=$su['id']?>, `<?=htmlspecialchars(addslashes(json_encode($su)))?>`)" class="btn btn-sm" style="background:rgba(13,110,253,0.1);color:#0d6efd;border-radius:8px"><i class="fas fa-edit"></i></button>
                <button onclick="deleteData(<?=$su['id']?>, 'subunit', '<?=addslashes($su['nama_subunit'])?>')" class="btn btn-sm" style="background:rgba(204,0,1,0.1);color:#cc0001;border-radius:8px"><i class="fas fa-trash"></i></button>
              </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

</div></div>

<div class="modal fade" id="userModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<div class="modal-header"><h5 class="modal-title" style="color:#fff;font-weight:700">Tambah Pengguna</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
<form id="userForm"><div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <div class="mb-3"><label class="form-label">Username *</label><input type="text" name="username" class="form-control" required></div>
  <div class="mb-3"><label class="form-label">Email *</label><input type="email" name="email" class="form-control" required></div>
  <div class="mb-3"><label class="form-label">Kata Laluan *</label><input type="password" name="password" class="form-control" required minlength="8"></div>
  <div class="mb-3"><label class="form-label">Role</label><select name="role" class="form-select"><option value="pegawai">Pegawai</option><option value="admin_unit">Admin Unit</option><option value="superadmin">Super Admin</option></select></div>
  <div class="mb-3"><label class="form-label">Unit</label><select name="unit_id" class="form-select"><option value="">- Pilih Unit -</option><?php foreach($units as $u): ?><option value="<?=$u['id']?>"><?=htmlspecialchars($u['nama_unit'])?></option><?php endforeach; ?></select></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">Cipta Pengguna</button></div>
</form></div></div></div>

<div class="modal fade" id="unitModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<div class="modal-header"><h5 class="modal-title" style="color:#fff;font-weight:700" id="unitModalTitle">Tambah Unit</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
<form id="unitForm" onsubmit="simpanUnit(event)"><div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <input type="hidden" name="action" id="unitAction" value="add">
  <input type="hidden" name="type" value="unit">
  <input type="hidden" name="id" id="unitId">
  <div class="mb-3"><label class="form-label">Nama Unit *</label><input type="text" name="nama" id="unitNama" class="form-control" required></div>
  <div class="row g-2 mb-3">
    <div class="col-6"><label class="form-label">Kod</label><input type="text" name="kod" id="unitKod" class="form-control"></div>
    <div class="col-6"><label class="form-label">Urutan</label><input type="number" name="urutan" id="unitUrutan" class="form-control" value="99"></div>
  </div>
  <div class="row g-2 mb-3">
    <div class="col-6"><label class="form-label">Warna</label><input type="color" name="warna" id="unitWarna" class="form-control form-control-color w-100" value="#0d6efd"></div>
    <div class="col-6"><label class="form-label">Ikon (FontAwesome)</label><input type="text" name="ikon" id="unitIkon" class="form-control" value="fas fa-building"></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">Simpan</button></div>
</form></div></div></div>

<div class="modal fade" id="subunitModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<div class="modal-header"><h5 class="modal-title" style="color:#fff;font-weight:700" id="subunitModalTitle">Tambah Subunit</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
<form id="subunitForm" onsubmit="simpanSubunit(event)"><div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <input type="hidden" name="action" id="subunitAction" value="add">
  <input type="hidden" name="type" value="subunit">
  <input type="hidden" name="id" id="subunitId">
  <div class="mb-3"><label class="form-label">Unit Induk *</label><select name="unit_id" id="subunitUnitId" class="form-select" required><option value="">- Pilih Unit -</option><?php foreach($units as $u): ?><option value="<?=$u['id']?>"><?=htmlspecialchars($u['nama_unit'])?></option><?php endforeach; ?></select></div>
  <div class="mb-3"><label class="form-label">Nama Subunit *</label><input type="text" name="nama" id="subunitNama" class="form-control" required></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">Simpan</button></div>
</form></div></div></div>

<script>
function showUserModal(){new bootstrap.Modal(document.getElementById('userModal')).show();}
document.getElementById('userForm').addEventListener('submit',function(e){
  e.preventDefault();const fd=new FormData(this);
  fetch('ajax_user.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    bootstrap.Modal.getInstance(document.getElementById('userModal'))?.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 resetPwd(id,name){
  Swal.fire({title:'Set Semula Kata Laluan',html:`Set semula kata laluan untuk <b>${name}</b>?`,icon:'question',background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#ffc107',cancelButtonColor:'#333',showCancelButton:true,confirmButtonText:'Reset'}).then(r=>{
    if(r.isConfirmed){fetch('ajax_user.php?action=reset&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:3000,background:'#0f0f1a',color:'#e0e0e0'}));}
  });
}
function deleteUser(id,name){
  Swal.fire({title:'Padam Pengguna?',html:`Padam akaun <b>${name}</b>?<br><small class="text-danger">Tindakan ini tidak boleh diundur!</small>`,icon:'warning',background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#cc0001',cancelButtonColor:'#333',showCancelButton:true,confirmButtonText:'Padam'}).then(r=>{
    if(r.isConfirmed){
      fetch('ajax_user.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:3000,background:'#0f0f1a',color:'#e0e0e0'});
        if(d.success)setTimeout(()=>location.reload(),1000);
      });
    }
  });
}
document.addEventListener('DOMContentLoaded', () => { if(typeof $ !== 'undefined') $('#usersTable').DataTable({language:{url:'//cdn.datatables.net/plug-ins/1.13.7/i18n/ms.json'},pageLength:10}); });
function previewLogo(input, target){
  if(!input.files||!input.files[0])return;
  const r=new FileReader();r.onload=e=>{
    document.getElementById('imgPreview_'+target).src=e.target.result;
    document.getElementById('preview_'+target).style.display='';
  };r.readAsDataURL(input.files[0]);
}
function deleteLogo(target){
  Swal.fire({title:'Padam Logo?',text:'Logo akan dipadam dan digantikan dengan teks.',icon:'warning',background:'#0f0f1a',color:'#e0e0e0',showCancelButton:true,confirmButtonColor:'#cc0001',cancelButtonColor:'#333',confirmButtonText:'Ya, Padam'}).then(r=>{
    if(!r.isConfirmed)return;
    const fd=new FormData();fd.append('csrf_token','<?=$csrf?>');fd.append('action','delete_logo');fd.append('target', target);
    fetch('ajax_logo.php',{method:'POST',body:fd}).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)setTimeout(()=>location.reload(),1000);
    });
  });
}
function submitLogoUpload(target){
  const form=document.getElementById('logoForm_'+target);
  const fd=new FormData(form);
  
  Swal.fire({title:'Muat naik...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
  
  fetch('ajax_logo.php',{method:'POST',body:fd})
  .then(r=>r.json())
  .then(d=>{
    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(),800);
  })
  .catch(err=>Swal.fire('Ralat',err.message,'error'));
}

function showUnitModal(){document.getElementById('unitForm').reset();document.getElementById('unitAction').value='add';document.getElementById('unitModalTitle').textContent='Tambah Unit';new bootstrap.Modal(document.getElementById('unitModal')).show();}
function editUnit(id, data){const u=JSON.parse(data);document.getElementById('unitForm').reset();document.getElementById('unitAction').value='edit';document.getElementById('unitId').value=id;document.getElementById('unitNama').value=u.nama_unit;document.getElementById('unitKod').value=u.kod;document.getElementById('unitUrutan').value=u.urutan;document.getElementById('unitWarna').value=u.warna;document.getElementById('unitIkon').value=u.ikon;document.getElementById('unitModalTitle').textContent='Edit Unit';new bootstrap.Modal(document.getElementById('unitModal')).show();}
function showSubunitModal(){document.getElementById('subunitForm').reset();document.getElementById('subunitAction').value='add';document.getElementById('subunitModalTitle').textContent='Tambah Subunit';new bootstrap.Modal(document.getElementById('subunitModal')).show();}
function editSubunit(id, data){const su=JSON.parse(data);document.getElementById('subunitForm').reset();document.getElementById('subunitAction').value='edit';document.getElementById('subunitId').value=id;document.getElementById('subunitNama').value=su.nama_subunit;document.getElementById('subunitUnitId').value=su.unit_id;document.getElementById('subunitModalTitle').textContent='Edit Subunit';new bootstrap.Modal(document.getElementById('subunitModal')).show();}
function refreshUnitsTab(){
  fetch(window.location.href).then(r=>r.text()).then(html=>{
    const doc = new DOMParser().parseFromString(html, 'text/html');
    document.getElementById('units').innerHTML = doc.getElementById('units').innerHTML;
    document.getElementById('subunitUnitId').innerHTML = doc.getElementById('subunitUnitId').innerHTML;
  });
}

function deleteData(id, type, name){Swal.fire({title:'Padam Rekod?',html:`Padam <b>${name}</b>?`,icon:'warning',background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#cc0001',showCancelButton:true,confirmButtonText:'Padam'}).then(r=>{if(r.isConfirmed)fetch(`ajax_unit_subunit.php?action=delete&type=${type}&id=${id}&csrf=<?=$csrf?>`).then(r=>r.json()).then(d=>{if(d.success){Swal.fire({toast:true,position:'top-end',icon:'success',title:d.message,showConfirmButton:false,timer:2000,background:'#0f0f1a',color:'#e0e0e0'});refreshUnitsTab();}else Swal.fire('Gagal',d.message,'error');});});}

function simpanUnit(e){
  e.preventDefault();
  fetch('ajax_unit_subunit.php',{method:'POST',body:new FormData(document.getElementById('unitForm'))})
  .then(r=>r.json()).then(d=>{
    if(d.success){
      bootstrap.Modal.getInstance(document.getElementById('unitModal'))?.hide();
      Swal.fire({toast:true,position:'top-end',icon:'success',title:d.message,showConfirmButton:false,timer:2000,background:'#0f0f1a',color:'#e0e0e0'});
      refreshUnitsTab();
    }else Swal.fire('Gagal',d.message,'error');
  }).catch(err=>Swal.fire('Ralat',err.message,'error'));
}
function simpanSubunit(e){
  e.preventDefault();
  fetch('ajax_unit_subunit.php',{method:'POST',body:new FormData(document.getElementById('subunitForm'))})
  .then(r=>r.json()).then(d=>{
    if(d.success){
      bootstrap.Modal.getInstance(document.getElementById('subunitModal'))?.hide();
      Swal.fire({toast:true,position:'top-end',icon:'success',title:d.message,showConfirmButton:false,timer:2000,background:'#0f0f1a',color:'#e0e0e0'});
      refreshUnitsTab();
    }else Swal.fire('Gagal',d.message,'error');
  }).catch(err=>Swal.fire('Ralat',err.message,'error'));
}
</script>
<?php require_once __DIR__.'/../../templates/footer.php'; ?>
