<?php
$pageTitle='Success Stories';
require_once __DIR__.'/../../config/functions.php';
requireLogin();
$stories=$pdo->query("SELECT s.*,u.nama_unit,u.warna,u.id as unit_id FROM success_stories s LEFT JOIN unit u ON s.unit_id=u.id WHERE s.status=1 ORDER BY s.tarikh DESC,s.id DESC")->fetchAll();
$units=$pdo->query("SELECT * FROM unit WHERE status=1 ORDER BY urutan ASC, id ASC")->fetchAll();
$storiesByUnit = [];
foreach($units as $u) $storiesByUnit[$u['id']] = [];
foreach($stories as $s) {
    if(isset($storiesByUnit[$s['unit_id']])) {
        $storiesByUnit[$s['unit_id']][] = $s;
    }
}
// Dapatkan unit pegawai semasa (untuk bukan admin)
$myUnitId=null;
if(!isAdmin()&&currentUserId()){
  $uq=$pdo->prepare("SELECT p.unit_id FROM users u LEFT JOIN pegawai p ON u.pegawai_id=p.id WHERE u.id=?");
  $uq->execute([currentUserId()]);$uq=$uq->fetch();
  $myUnitId=$uq['unit_id']??null;
}
$breadcrumb=[['label'=>'Utama','url'=>BASE_URL],['label'=>'Success Stories','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="d-flex align-items-center justify-content-between mb-4">
  <h2 class="section-title">Success Stories</h2>
  <button class="btn btn-primary" onclick="showStoryModal()"><i class="fas fa-plus me-2"></i>Tambah Story</button>
</div>
<ul class="nav nav-pills mb-4" id="storyTabs" 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-4">
    <?php if(empty($storiesByUnit[$u['id']])): ?>
      <div class="col-12 text-center py-5" style="color:#555"><i class="fas fa-award fa-3x mb-3"></i><p>Tiada success stories</p></div>
    <?php else: ?>
      <?php foreach($storiesByUnit[$u['id']] as $s): $col=$s['warna']??'#cc0001'; ?>
      <div class="col-md-6 col-lg-4">
      <div class="content-card h-100" style="border-top:3px solid <?=$col?>;position:relative">
        <?php if(isSuperAdmin() || (!empty($_SESSION['pegawai_id']) && $_SESSION['pegawai_id'] == $s['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='editStory(<?=json_encode($s)?>)' 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="deleteStory(<?=$s['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; ?>
        <?php if($s['gambar']&&file_exists(UPLOAD_PATH.'gallery/'.$s['gambar'])): ?>
        <img src="<?=UPLOAD_URL.'gallery/'.$s['gambar']?>" style="width:100%;height:180px;object-fit:cover;border-radius:12px;margin-bottom:1rem">
        <?php endif; ?>
        <?php if($s['tarikh']): ?><div style="font-size:.75rem;color:#555;margin-bottom:.5rem"><i class="fas fa-calendar me-1"></i><?=formatDate($s['tarikh'])?></div><?php endif; ?>
        <h3 style="font-size:1rem;font-weight:700;color:#fff;margin-bottom:.5rem"><?=htmlspecialchars($s['tajuk'])?></h3>
        <p style="font-size:.85rem;color:#666;line-height:1.6"><?=nl2br(htmlspecialchars(substr($s['kandungan']??'',0,200)))?></p>
      </div>
      </div>
      <?php endforeach; ?>
    <?php endif; ?>
    </div>
  </div>
  <?php $first=false; endforeach; ?>
</div>
</div></div>

<!-- Modal Tambah Success Story - untuk SEMUA pegawai login -->
<div class="modal fade" id="storyModal" 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-award me-2" style="color:#ffc107"></i>Tambah Success Story</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
<form id="storyForm" enctype="multipart/form-data"><div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <input type="hidden" name="id" id="story_id" value="">
  <div class="row g-2">
    <?php if(isAdmin()): ?>
    <div class="col-md-6"><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>
    <?php else: ?>
    <input type="hidden" name="unit_id" value="<?=$myUnitId?>">
    <?php endif; ?>
    <div class="col-md-6"><label class="form-label">Tarikh</label><input type="date" name="tarikh" class="form-control" value="<?=date('Y-m-d')?>"></div>
    <div class="col-12"><label class="form-label">Tajuk *</label><input type="text" name="tajuk" class="form-control" required placeholder="Tajuk success story..."></div>
    <div class="col-12"><label class="form-label">Kandungan / Penerangan</label><textarea name="kandungan" class="form-control" rows="4" placeholder="Ceritakan pencapaian ini..."></textarea></div>
    <div class="col-12"><label class="form-label">Gambar (Pilihan)</label><input type="file" name="gambar" class="form-control" accept="image/*"></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 showStoryModal(){
  document.getElementById('storyForm').reset();
  document.getElementById('story_id').value = '';
  document.querySelector('#storyModal .modal-title').innerHTML = '<i class="fas fa-award me-2" style="color:#ffc107"></i>Tambah Success Story';
  new bootstrap.Modal(document.getElementById('storyModal')).show();
}
function editStory(data){
  const form = document.getElementById('storyForm');
  form.reset();
  document.getElementById('story_id').value = data.id;
  form.querySelector('[name="tajuk"]').value = data.tajuk;
  form.querySelector('[name="tarikh"]').value = data.tarikh;
  form.querySelector('[name="kandungan"]').value = data.kandungan;
  if(form.querySelector('[name="unit_id"]')) form.querySelector('[name="unit_id"]').value = data.unit_id;
  document.querySelector('#storyModal .modal-title').innerHTML = '<i class="fas fa-edit me-2" style="color:#ffc107"></i>Kemaskini Success Story';
  new bootstrap.Modal(document.getElementById('storyModal')).show();
}
function deleteStory(id){
  Swal.fire({
    title: 'Padam Success Story?',
    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('storyForm').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('storyModal'))?.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'; ?>
