<?php
$pageTitle='Profil Pegawai';
require_once __DIR__.'/../../config/functions.php';
requireLogin();
$id=intval($_GET['id']??0);
$stmt=$pdo->prepare("SELECT p.*,j.nama_jawatan,j.gred,u.nama_unit,u.warna,s.nama_sektor,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 sektor s ON p.sektor_id=s.id LEFT JOIN subunit su ON p.subunit_id=su.id WHERE p.id=?");
$stmt->execute([$id]);$p=$stmt->fetch();
if(!$p){header('Location: index.php');exit;}
$pageTitle='Profil - '.htmlspecialchars($p['nama']);
$infos=$pdo->prepare("SELECT * FROM informasi WHERE pegawai_id=? AND status=1 ORDER BY created_at DESC");$infos->execute([$id]);$infos=$infos->fetchAll();
$breadcrumb=[['label'=>'Utama','url'=>BASE_URL],['label'=>'Pegawai','url'=>'index.php'.($p['unit_id']?'?unit='.$p['unit_id']:'')],['label'=>$p['nama'],'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">
<div class="row g-4">
  <div class="col-lg-4">
    <div class="content-card text-center mb-3" style="border-top:3px solid <?=$p['warna']??'#cc0001'?>">
      <img src="<?=getPegawaiImage($p['gambar'])?>" style="width:130px;height:130px;border-radius:50%;object-fit:cover;border:4px solid <?=$p['warna']??'#cc0001'?>44;margin:1rem auto;display:block;box-shadow:0 0 30px <?=$p['warna']??'#cc0001'?>33">
      <h1 style="font-size:1.2rem;font-weight:800;color:#fff;margin-bottom:.25rem"><?=htmlspecialchars($p['nama'])?></h1>
      <div style="font-size:.9rem;color:#888;margin-bottom:.5rem"><?=htmlspecialchars($p['nama_jawatan'])?> <?=$p['gred']?'('.$p['gred'].')':''?></div>
      <?php if($p['nama_unit']): ?>
      <span style="background:<?=$p['warna']??'#888'?>22;color:<?=$p['warna']??'#888'?>;border:1px solid <?=$p['warna']??'#888'?>44;border-radius:50px;padding:.3rem 1rem;font-size:.8rem;font-weight:600"><?=htmlspecialchars($p['nama_unit'])?><?=!empty($p['nama_subunit'])?' - '.htmlspecialchars($p['nama_subunit']):''?></span>
      <?php else: ?>
      <span style="background:rgba(204,0,1,0.1);color:#cc0001;border:1px solid rgba(204,0,1,0.2);border-radius:50px;padding:.3rem 1rem;font-size:.8rem;font-weight:600"><i class="fas fa-crown me-1"></i>Ketua Sektor</span>
      <?php endif; ?>
      <div style="margin-top:.5rem;font-size:.8rem;color:#555"><?=htmlspecialchars($p['nama_sektor'])?></div>
      <div class="mt-3" style="font-size:.75rem">
        <?php if($p['status']): ?><span class="badge bg-success">Aktif</span><?php else: ?><span class="badge bg-secondary">Tidak Aktif</span><?php endif; ?>
      </div>
      <hr style="border-color:rgba(255,255,255,0.06);margin:1.5rem 0">
      <?php if($p['email']): ?><div style="padding:.5rem;font-size:.85rem;color:#888"><i class="fas fa-envelope me-2" style="color:<?=$p['warna']??'#cc0001'?>"></i><?=htmlspecialchars($p['email'])?></div><?php endif; ?>
      <?php if($p['no_telefon']): ?><div style="padding:.5rem;font-size:.85rem;color:#888"><i class="fas fa-phone me-2" style="color:<?=$p['warna']??'#cc0001'?>"></i><?=htmlspecialchars($p['no_telefon'])?></div><?php endif; ?>
      <?php if($p['no_telefon_pejabat']): ?><div style="padding:.5rem;font-size:.85rem;color:#888"><i class="fas fa-building me-2" style="color:<?=$p['warna']??'#cc0001'?>"></i><?=htmlspecialchars($p['no_telefon_pejabat'])?></div><?php endif; ?>
      <?php $socials=[['facebook','fab fa-facebook','#1877f2'],['twitter','fab fa-twitter','#1da1f2'],['linkedin','fab fa-linkedin','#0077b5'],['instagram','fab fa-instagram','#e4405f']];
      $hasSocial=array_filter($socials,fn($s)=>!empty($p[$s[0]]));
      if($hasSocial): ?><hr style="border-color:rgba(255,255,255,0.06)"><div style="display:flex;gap:.75rem;justify-content:center"><?php foreach($hasSocial as $s): ?><a href="<?=htmlspecialchars($p[$s[0]])?>" target="_blank" style="width:36px;height:36px;background:<?=$s[2]?>22;border:1px solid <?=$s[2]?>44;border-radius:10px;display:flex;align-items:center;justify-content:center;color:<?=$s[2]?>;text-decoration:none;transition:all .3s" onmouseover="this.style.background='<?=$s[2]?>44'" onmouseout="this.style.background='<?=$s[2]?>22'"><i class="<?=$s[1]?>"></i></a><?php endforeach; ?></div><?php endif; ?>
    </div>
    <!-- QR Code -->
    <div class="content-card text-center">
      <div style="font-size:.85rem;color:#666;margin-bottom:1rem;font-weight:600;text-transform:uppercase;letter-spacing:1px">QR Code Pegawai</div>
      <div id="qrcode" style="display:inline-block;background:#fff;padding:12px;border-radius:12px"></div>
      <div style="font-size:.7rem;color:#444;margin-top:.75rem">Imbas untuk lihat profil</div>
    </div>
  </div>
  <div class="col-lg-8">
    <?php if($p['bio']): ?>
    <div class="content-card mb-3">
      <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:1rem"><i class="fas fa-user me-2" style="color:<?=$p['warna']??'#cc0001'?>"></i>Bio</h3>
      <p style="color:#888;font-size:.9rem;line-height:1.7"><?=nl2br(htmlspecialchars($p['bio']))?></p>
    </div>
    <?php endif; ?>
    <?php if($p['tugas_utama']): ?>
    <div class="content-card mb-3">
      <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:1rem"><i class="fas fa-tasks me-2" style="color:<?=$p['warna']??'#cc0001'?>"></i>Tugas Utama</h3>
      <p style="color:#888;font-size:.9rem;line-height:1.7"><?=nl2br(htmlspecialchars($p['tugas_utama']))?></p>
    </div>
    <?php endif; ?>
    <!-- Informasi Timeline -->
    <div class="content-card">
      <div class="d-flex align-items-center justify-content-between mb-3">
        <a href="<?=BASE_URL?>modules/informasi/" style="text-decoration:none">
          <h3 style="font-size:1rem;font-weight:700;color:#fff;margin:0">
            <i class="fas fa-info-circle me-2" style="color:<?=$p['warna']??'#cc0001'?>"></i>Informasi
          </h3>
        </a>
        <?php if(isLoggedIn()&&(isSuperAdmin()||isAdmin()||currentUserId()==$p['id'])): ?>
        <button class="btn btn-sm btn-outline-primary" onclick="showInfoModal()"><i class="fas fa-plus me-1"></i>Tambah</button>
        <?php endif; ?>
      </div>
      <?php if($infos): ?>
      <div class="timeline">
      <?php foreach($infos as $info):
        $jCol=['umum'=>'#888','pengumuman'=>'#0d6efd','pencapaian'=>'#198754','aktiviti'=>'#ffc107','dokumen'=>'#6f42c1'][$info['jenis']]??'#888';
        $jIcon=['umum'=>'fas fa-info-circle','pengumuman'=>'fas fa-bullhorn','pencapaian'=>'fas fa-award','aktiviti'=>'fas fa-calendar','dokumen'=>'fas fa-file'][$info['jenis']]??'fas fa-info-circle';
      ?>
      <div class="timeline-item">
        <div style="background:rgba(26,26,46,0.8);border:1px solid rgba(255,255,255,0.06);border-radius:16px;padding:1.25rem;position:relative">
          <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:.75rem">
            <div style="display:flex;align-items:center;gap:.75rem">
              <span style="background:<?=$jCol?>22;color:<?=$jCol?>;border:1px solid <?=$jCol?>44;border-radius:8px;padding:.25rem .6rem;font-size:.7rem;font-weight:600;text-transform:capitalize"><i class="<?=$jIcon?> me-1"></i><?=ucfirst($info['jenis'])?></span>
              <span style="font-size:.75rem;color:#444"><?=timeAgo($info['created_at'])?></span>
            </div>
            <?php if(isSuperAdmin() || (!empty($_SESSION['pegawai_id']) && $_SESSION['pegawai_id'] == $info['pegawai_id'])): ?>
            <div style="display:flex;gap:.5rem">
              <button class="btn btn-xs btn-outline-light" onclick='editInfo(<?=json_encode($info)?>)' 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(<?=$info['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>
          <h4 style="font-size:.95rem;font-weight:700;color:#fff;margin-bottom:.5rem"><?=htmlspecialchars($info['tajuk'])?></h4>
          <p style="font-size:.85rem;color:#666;line-height:1.6;margin:0"><?=nl2br(htmlspecialchars(substr($info['kandungan']??'',0,300)))?></p>
          <?php if($info['lampiran']): ?><div style="margin-top:.75rem"><a href="<?=UPLOAD_URL.'documents/'.$info['lampiran']?>" target="_blank" class="btn btn-sm" style="background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,0.1);color:#ccc;border-radius:8px;font-size:.75rem"><i class="fas fa-paperclip me-1"></i>Lampiran</a></div><?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
      </div>
      <?php else: ?><div style="text-align:center;padding:2rem;color:#444"><i class="fas fa-stream fa-2x mb-2"></i><p>Tiada maklumat lagi</p></div><?php endif; ?>
    </div>
  </div>
</div>
</div></div>

<!-- Info Modal -->
<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="<?=$id?>">
  <div class="row g-2">
    <div class="col-md-8"><label class="form-label">Tajuk *</label><input type="text" name="tajuk" class="form-control" required placeholder="Tajuk informasi..."></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 src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
new QRCode(document.getElementById("qrcode"),{text:window.location.href,width:128,height:128,colorDark:"#cc0001",colorLight:"#ffffff"});
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="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',confirmButtonText:'Ya, Padam!',background:'#0f0f1a',color:'#e0e0e0'}).then(r=>{
    if(r.isConfirmed){
      const fd=new FormData();fd.append('id',id);fd.append('csrf_token','<?=$csrf?>');
      fetch('<?=BASE_URL?>modules/informasi/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('<?=BASE_URL?>modules/informasi/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);
  });
});
</script>
<?php require_once __DIR__.'/../../templates/footer.php'; ?>
