<?php
$pageTitle='Informasi';
require_once __DIR__.'/../../config/functions.php';
requireLogin();
$units=$pdo->query("SELECT * FROM unit WHERE status=1 ORDER BY urutan ASC, id ASC")->fetchAll();
$infos=$pdo->query("SELECT i.*,p.nama as nama_pegawai,p.gambar,u.id as unit_id,u.nama_unit,u.warna FROM informasi i JOIN pegawai p ON i.pegawai_id=p.id JOIN unit u ON p.unit_id=u.id WHERE i.status=1 ORDER BY i.created_at DESC")->fetchAll();
$infosByUnit = [];
foreach($units as $u) $infosByUnit[$u['id']] = [];
foreach($infos as $i) {
    if(isset($infosByUnit[$i['unit_id']])) {
        $infosByUnit[$i['unit_id']][] = $i;
    }
}
$breadcrumb=[['label'=>'Utama','url'=>BASE_URL],['label'=>'Informasi','url'=>'#']];
require_once __DIR__.'/../../templates/header.php';
?>
<meta name="base-url" content="<?=BASE_URL?>">
<?php require_once __DIR__.'/../../templates/sidebar.php'; ?>
<div class="main-content">
<?php require_once __DIR__.'/../../templates/topbar.php'; ?>
<div style="padding:2rem">
<div class="d-flex align-items-center justify-content-between mb-4">
  <h2 class="section-title" style="margin:0">Informasi</h2>
  <?php if(currentUserId() && !empty($_SESSION['pegawai_id'])): ?>
  <button class="btn btn-primary" onclick="showInfoModal()"><i class="fas fa-plus me-2"></i>Tambah Informasi</button>
  <?php endif; ?>
</div>

<ul class="nav nav-pills mb-4" id="infoTabs" style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);border-radius:14px;padding:.4rem;overflow-x:auto;flex-wrap:nowrap">
  <?php $first=true; foreach($units as $u): ?>
  <li class="nav-item"><a class="nav-link <?=$first?'active':''?>" href="#unit_<?=$u['id']?>" data-bs-toggle="tab" style="border-radius:10px;font-size:.9rem;white-space:nowrap"><i class="<?=htmlspecialchars($u['ikon'])?> me-2" style="color:<?=$u['warna']?>"></i><?=htmlspecialchars($u['nama_unit'])?></a></li>
  <?php $first=false; endforeach; ?>
</ul>

<div class="tab-content">
  <?php $first=true; foreach($units as $u): ?>
  <div class="tab-pane fade <?=$first?'show active':''?>" id="unit_<?=$u['id']?>">
    <div class="row g-3">
    <?php if(empty($infosByUnit[$u['id']])): ?>
      <div class="col-12 text-center py-5" style="color:#555"><i class="fas fa-info-circle fa-3x mb-3"></i><p>Tiada maklumat</p></div>
    <?php else: ?>
      <?php foreach($infosByUnit[$u['id']] as $i):
        $jCol=['umum'=>'#888','pengumuman'=>'#0d6efd','pencapaian'=>'#198754','aktiviti'=>'#ffc107','dokumen'=>'#6f42c1'][$i['jenis']]??'#888';
      ?>
      <div class="col-md-6 col-lg-4">
      <div class="content-card h-100" style="border-top:2px solid <?=$jCol?>;position:relative">
        <?php if(isSuperAdmin() || (!empty($_SESSION['pegawai_id']) && $_SESSION['pegawai_id'] == $i['pegawai_id'])): ?>
        <div style="position:absolute;top:1rem;right:1rem;display:flex;gap:.5rem;z-index:2">
          <button class="btn btn-xs btn-outline-light" onclick='editInfo(<?=json_encode($i)?>)' style="padding:.2rem .4rem;font-size:.65rem;border-color:rgba(255,255,255,0.1);background:rgba(0,0,0,0.3)"><i class="fas fa-edit"></i></button>
          <button class="btn btn-xs btn-outline-danger" onclick="deleteInfo(<?=$i['id']?>)" style="padding:.2rem .4rem;font-size:.65rem;background:rgba(0,0,0,0.3)"><i class="fas fa-trash"></i></button>
        </div>
        <?php endif; ?>
        <div style="display:flex;align-items:center;gap:.75rem;margin-bottom:1rem">
          <img src="<?=getPegawaiImage($i['gambar'])?>" style="width:40px;height:40px;border-radius:50%;object-fit:cover;border:2px solid <?=$i['warna']??'#888'?>44">
          <div style="min-width:0">
            <div style="font-size:.85rem;font-weight:600;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?=htmlspecialchars($i['nama_pegawai'])?></div>
            <div style="font-size:.7rem;color:#555">
              <?php if($i['tarikh']): ?>
                <i class="far fa-calendar-alt me-1"></i><?=date('d/m/Y', strtotime($i['tarikh']))?> • 
              <?php endif; ?>
              <?=timeAgo($i['created_at'])?>
            </div>
          </div>
          <span style="margin-left:auto;background:<?=$jCol?>22;color:<?=$jCol?>;border-radius:6px;padding:.2rem .5rem;font-size:.7rem;font-weight:600;flex-shrink:0"><?=ucfirst($i['jenis'])?></span>
        </div>
        <h3 style="font-size:.95rem;font-weight:700;color:#fff;margin-bottom:.5rem"><?=htmlspecialchars($i['tajuk'])?></h3>
        <p style="font-size:.82rem;color:#666;line-height:1.6;margin:0"><?=nl2br(htmlspecialchars(substr($i['kandungan']??'',0,200)))?></p>
        <?php if($i['lampiran']): 
          $ext = strtolower(pathinfo($i['lampiran'], PATHINFO_EXTENSION));
          if(in_array($ext, ['jpg','jpeg','png','gif','webp'])): ?>
            <div style="margin-top:1rem"><a href="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" target="_blank"><img src="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" style="width:100%;max-height:200px;object-fit:contain;border-radius:8px;background:rgba(0,0,0,0.2)"></a></div>
          <?php else: ?>
            <div style="margin-top:.75rem"><a href="<?=UPLOAD_URL.'documents/'.$i['lampiran']?>" target="_blank" class="btn btn-sm" style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.08);color:#ccc;border-radius:8px;font-size:.75rem"><i class="fas fa-paperclip me-1"></i>Lampiran (<?=$ext?>)</a></div>
          <?php endif; 
        endif; ?>
      </div>
      </div>
      <?php endforeach; ?>
    <?php endif; ?>
    </div>
  </div>
  <?php $first=false; endforeach; ?>
</div>
</div></div>

<?php if(currentUserId() && !empty($_SESSION['pegawai_id'])): ?>
<div class="modal fade" id="infoModal" 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-bullhorn me-2" style="color:#0d6efd"></i>Tambah Informasi</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
<form id="infoForm" enctype="multipart/form-data"><div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <input type="hidden" name="id" id="info_id" value="">
  <input type="hidden" name="pegawai_id" value="<?=$_SESSION['pegawai_id']?>">
  <div class="row g-2">
    <div class="col-md-5"><label class="form-label">Tajuk *</label><input type="text" name="tajuk" class="form-control" required placeholder="Tajuk informasi..."></div>
    <div class="col-md-3"><label class="form-label">Tarikh</label><input type="date" name="tarikh" class="form-control" value="<?=date('Y-m-d')?>"></div>
    <div class="col-md-4"><label class="form-label">Jenis</label><select name="jenis" class="form-select"><option value="umum">Umum</option><option value="pengumuman">Pengumuman</option><option value="pencapaian">Pencapaian</option><option value="aktiviti">Aktiviti</option><option value="dokumen">Dokumen</option></select></div>
    <div class="col-12"><label class="form-label">Kandungan / Penerangan</label><textarea name="kandungan" class="form-control" rows="4" placeholder="Kandungan..."></textarea></div>
    <div class="col-12"><label class="form-label">Lampiran (Pilihan)</label><input type="file" name="lampiran" class="form-control"></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-1"></i>Simpan</button></div>
</form></div></div></div>
<script>
function showInfoModal(){
  document.getElementById('infoForm').reset();
  document.getElementById('info_id').value = '';
  document.querySelector('#infoModal .modal-title').innerHTML = '<i class="fas fa-bullhorn me-2" style="color:#0d6efd"></i>Tambah Informasi';
  new bootstrap.Modal(document.getElementById('infoModal')).show();
}
function editInfo(data){
  const form = document.getElementById('infoForm');
  form.reset();
  document.getElementById('info_id').value = data.id;
  form.querySelector('[name="tajuk"]').value = data.tajuk;
  form.querySelector('[name="tarikh"]').value = data.tarikh || '';
  form.querySelector('[name="jenis"]').value = data.jenis;
  form.querySelector('[name="kandungan"]').value = data.kandungan;
  document.querySelector('#infoModal .modal-title').innerHTML = '<i class="fas fa-edit me-2" style="color:#0d6efd"></i>Kemaskini Informasi';
  new bootstrap.Modal(document.getElementById('infoModal')).show();
}
function deleteInfo(id){
  Swal.fire({
    title: 'Padam Informasi?',
    text: "Rekod ini akan dipadam secara kekal!",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#dc3545',
    cancelButtonColor: '#6c757d',
    confirmButtonText: 'Ya, Padam!',
    cancelButtonText: 'Batal',
    background: '#0f0f1a',
    color: '#e0e0e0'
  }).then((result) => {
    if (result.isConfirmed) {
      const fd = new FormData();
      fd.append('id', id);
      fd.append('csrf_token', '<?=$csrf?>');
      fetch('ajax_delete.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:2500,background:'#0f0f1a',color:'#e0e0e0'});
        if(d.success) setTimeout(()=>location.reload(), 1000);
      });
    }
  });
}
document.getElementById('infoForm').addEventListener('submit',function(e){
  e.preventDefault();const fd=new FormData(this);
  fetch('ajax_add.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    bootstrap.Modal.getInstance(document.getElementById('infoModal'))?.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);
  }).catch(err=>Swal.fire('Ralat',err.message,'error'));
});
</script>
<?php endif; ?>
<?php require_once __DIR__.'/../../templates/footer.php'; ?>
