<?php
$pageTitle='Takwim Interaktif';
require_once __DIR__.'/../../config/functions.php';
requireLogin();
$units=$pdo->query("SELECT * FROM unit WHERE status=1 ORDER BY urutan ASC, id ASC")->fetchAll();
$subunits=$pdo->query("SELECT * FROM subunit WHERE status=1 ORDER BY nama_subunit ASC")->fetchAll();
$pegawaiList=$pdo->query("SELECT id,nama,unit_id FROM pegawai WHERE status=1 ORDER BY nama")->fetchAll();
$breadcrumb=[['label'=>'Utama','url'=>BASE_URL],['label'=>'Takwim','url'=>'#']];
require_once __DIR__.'/../../templates/header.php';
?>
<meta name="base-url" content="<?=BASE_URL?>">
<meta name="csrf-token" content="<?=$csrf?>">
<link href="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.css" rel="stylesheet">
<style>
/* FullCalendar List View Dark Theme */
.fc-list, .fc-list-table, .fc-list-day, .fc-list-event td, .fc-list-day-cushion {
  background-color: transparent !important;
}
.fc-list-day {
  background: rgba(255, 255, 255, 0.05) !important;
}
.fc-list-table {
  border: none !important;
}
.fc-theme-standard .fc-list-day-cushion {
  background-color: rgba(255, 255, 255, 0.03) !important;
}
.fc-list-sticky .fc-list-day > * {
  background: #1a1a2e !important; /* Latar belakang gelap untuk header melekat */
}
.fc-list-day-text, .fc-list-day-side-text {
  color: #fff !important;
  font-weight: 700 !important;
  text-decoration: none !important;
}
.fc-list-event td {
  border-color: rgba(255, 255, 255, 0.05) !important;
  color: #e0e0e0 !important;
  padding: 1rem !important;
}
.fc-list-event-title {
  font-weight: 600 !important;
}
.fc-list-event-time {
  color: #888 !important;
  font-weight: 500 !important;
}
.event-action-btn {
  padding: .35rem .6rem;
  font-size: .75rem;
  border-radius: 8px;
  border: 1px solid rgba(255,255,255,0.1);
  background: rgba(255,255,255,0.05);
  color: #ccc;
  transition: all .2s;
  margin-left: .4rem;
  cursor: pointer;
}
.event-action-btn:hover {
  background: rgba(255,255,255,0.1);
  color: #fff;
}
.event-action-btn.edit:hover {
  background: rgba(13,110,253,0.15);
  border-color: rgba(13,110,253,0.3);
  color: #0d6efd;
}
.event-action-btn.delete:hover {
  background: rgba(204,0,1,0.15);
  border-color: rgba(204,0,1,0.3);
  color: #cc0001;
}
</style>
<?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 flex-wrap align-items-center justify-content-between gap-3 mb-4">
  <h2 class="section-title" style="margin:0">Takwim Interaktif</h2>
  <div style="display:flex;gap:.5rem">
    <a href="export_csv.php" class="btn btn-outline-success"><i class="fas fa-file-csv me-2"></i>Download CSV</a>
    <button class="btn btn-outline-primary" onclick="document.getElementById('importCsvInput').click()"><i class="fas fa-upload me-2"></i>Upload CSV</button>
    <button class="btn btn-primary" onclick="showAddEventModal()"><i class="fas fa-plus me-2"></i>Tambah Aktiviti</button>
  </div>
</div>
<div class="row g-3 mb-4">
  <div class="col-md-9">
    <div class="content-card" style="padding:1.5rem">
      <div id="calendar" style="min-height:600px"></div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="content-card mb-3">
      <h3 style="font-size:.95rem;font-weight:700;color:#fff;margin-bottom:1rem"><i class="fas fa-filter me-2" style="color:#cc0001"></i>Penapis Unit</h3>
      <div style="display:flex;flex-direction:column;gap:.5rem">
        <label style="display:flex;align-items:center;gap:.75rem;cursor:pointer;padding:.5rem;border-radius:8px;transition:background .2s" onmouseover="this.style.background='rgba(255,255,255,0.03)'" onmouseout="this.style.background=''">
          <input type="checkbox" class="unit-filter" id="allUnitsCb" value="" checked style="accent-color:#888"> <span style="font-size:.85rem;color:#888">Semua Unit</span>
        </label>
        <?php foreach($units as $u): ?>
        <label style="display:flex;align-items:center;gap:.75rem;cursor:pointer;padding:.5rem;border-radius:8px;transition:background .2s" onmouseover="this.style.background='rgba(255,255,255,0.03)'" onmouseout="this.style.background=''">
          <input type="checkbox" class="unit-filter" value="<?=$u['id']?>" checked style="accent-color:<?=$u['warna']?>">
          <span style="font-size:.85rem;color:#ccc"><?=htmlspecialchars($u['nama_unit'])?></span>
          <span style="width:10px;height:10px;border-radius:50%;background:<?=$u['warna']?>;margin-left:auto;flex-shrink:0"></span>
        </label>
        <?php endforeach; ?>
      </div>
    </div>
    <div class="content-card">
      <h3 style="font-size:.95rem;font-weight:700;color:#fff;margin-bottom:1rem"><i class="fas fa-info-circle me-2" style="color:#cc0001"></i>Legenda Warna</h3>
      <?php foreach($units as $u): ?>
      <div style="display:flex;align-items:center;gap:.75rem;margin-bottom:.5rem">
        <span style="width:14px;height:14px;border-radius:4px;background:<?=$u['warna']?>;flex-shrink:0"></span>
        <span style="font-size:.8rem;color:#888"><?=htmlspecialchars($u['nama_unit'])?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
</div></div>

<!-- Event Modal -->
<div class="modal fade" id="eventModal" tabindex="-1">
<div class="modal-dialog"><div class="modal-content">
<div class="modal-header">
  <h5 class="modal-title" style="color:#fff;font-weight:700"><i class="fas fa-calendar-plus me-2" style="color:#cc0001"></i><span id="eventModalTitle">Tambah Aktiviti</span></h5>
  <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<form id="eventForm">
<div class="modal-body">
  <input type="hidden" name="csrf_token" value="<?=$csrf?>">
  <input type="hidden" name="event_id" id="eventId">
  <div class="row g-2">
    <div class="col-12"><label class="form-label">Tajuk Program *</label><input type="text" name="tajuk" class="form-control" required></div>
    <div class="col-md-6">
      <label class="form-label">Unit</label>
      <select name="unit_id" id="event_unit_id" class="form-select">
        <option value="">- Pilih Unit -</option>
        <?php foreach($units as $u): ?>
        <option value="<?=$u['id']?>" data-color="<?=$u['warna']?>"><?=htmlspecialchars($u['nama_unit'])?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-md-6">
      <label class="form-label">Subunit</label>
      <select name="subunit_id" id="event_subunit_id" class="form-select">
        <option value="">- Pilih Subunit -</option>
        <?php foreach($subunits as $s): ?>
        <option value="<?=$s['id']?>" data-unit="<?=$s['unit_id']?>"><?=htmlspecialchars($s['nama_subunit'])?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-12"><label class="form-label">Pegawai Bertanggungjawab</label><select name="pegawai_id" class="form-select"><option value="">- Pilih Pegawai -</option><?php foreach($pegawaiList as $p): ?><option value="<?=$p['id']?>"><?=htmlspecialchars($p['nama'])?></option><?php endforeach; ?></select></div>
    <div class="col-md-6"><label class="form-label">Tarikh Mula *</label><input type="date" name="tarikh_mula" class="form-control" required></div>
    <div class="col-md-6"><label class="form-label">Masa Mula</label><input type="time" name="masa_mula" class="form-control"></div>
    <div class="col-md-6"><label class="form-label">Tarikh Tamat</label><input type="date" name="tarikh_tamat" class="form-control"></div>
    <div class="col-md-6"><label class="form-label">Masa Tamat</label><input type="time" name="masa_tamat" class="form-control"></div>
    <div class="col-md-6"><label class="form-label">Peringkat</label><input type="text" name="peringkat" class="form-control" placeholder="Contoh: Negeri/Kebangsaan"></div>
    <div class="col-md-6"><label class="form-label">Pengelola / Penganjur</label><input type="text" name="pengelola_keb" class="form-control" placeholder="Nama agensi pengelola"></div>
    <div class="col-12"><label class="form-label">Tempat</label><input type="text" name="tempat" class="form-control" placeholder="Nama tempat..."></div>
    <div class="col-12"><label class="form-label">Catatan</label><textarea name="deskripsi" class="form-control" rows="3"></textarea></div>
    <div class="col-md-8"><label class="form-label">Warna</label><input type="color" name="warna" id="eventColor" class="form-control form-control-color" value="#0d6efd" style="height:45px"></div>
    <div class="col-md-4 d-flex align-items-end pb-1"><label style="display:flex;align-items:center;gap:.5rem;cursor:pointer;color:#ccc;font-size:.85rem"><input type="checkbox" name="semua_hari" value="1" style="accent-color:#cc0001"> Semua Hari</label></div>
  </div>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-danger btn-sm" id="deleteEventBtn" style="display:none;margin-right:auto" onclick="deleteEvent()"><i class="fas fa-trash me-1"></i>Padam</button>
  <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-2"></i>Simpan</button>
</div>
</form>
</div></div></div>

<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.js"></script>
<script>
const CSRF='<?=$csrf?>';const BASE='<?=BASE_URL?>';
const USER_UNIT = <?=json_encode(currentUnitId())?>;
const IS_SUPERADMIN = <?=json_encode(isSuperAdmin())?>;
let calendar;
document.addEventListener('DOMContentLoaded',function(){
  const calEl=document.getElementById('calendar');
  calendar=new FullCalendar.Calendar(calEl,{
    initialView:'dayGridMonth',locale:'ms',
    headerToolbar:{left:'prev,next today',center:'title',right:'dayGridMonth,timeGridWeek,listWeek'},
    buttonText:{today:'Hari Ini',month:'Bulan',week:'Minggu',list:'Senarai'},
    editable:true,selectable:true,
    events:function(info,success,fail){
      const selectedUnits = Array.from(document.querySelectorAll('.unit-filter:checked'))
        .map(cb => cb.value)
        .filter(v => v !== '');
      
      let url = 'ajax_events.php?start='+info.startStr+'&end='+info.endStr;
      if(selectedUnits.length > 0) {
        url += '&units=' + selectedUnits.join(',');
      } else if (!document.getElementById('allUnitsCb').checked) {
        // If "Select All" is off and no individual units are selected, return empty
        success([]); return;
      }
      
      fetch(url).then(r=>r.json()).then(data=>success(data)).catch(()=>fail());
    },
    select:function(info){
      resetForm();document.getElementById('eventModalTitle').textContent='Tambah Aktiviti';
      document.querySelector('[name=tarikh_mula]').value=info.startStr;
      document.querySelector('[name=tarikh_tamat]').value=info.endStr;
      document.getElementById('deleteEventBtn').style.display='none';
      new bootstrap.Modal(document.getElementById('eventModal')).show();
    },
    eventClick:function(info){
      const e=info.event;
      const canEdit = IS_SUPERADMIN || (USER_UNIT && e.extendedProps.unit_id == USER_UNIT);
      
      const dateOptions = { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' };
      const dateStr = e.start.toLocaleDateString('ms-MY', dateOptions);
      const timeStr = e.allDay ? 'Sepanjang Hari' : e.start.toLocaleTimeString('ms-MY', {hour:'2-digit', minute:'2-digit'});
      
      let footer = '';
      if(canEdit) {
        footer = `<div style="display:flex;gap:10px;justify-content:center;width:100%;margin-top:10px">
          <button onclick="Swal.close();editEventById('${e.id}')" class="btn btn-primary btn-sm" style="padding:.4rem 1rem;border-radius:8px"><i class="fas fa-edit me-2"></i>Kemaskini</button>
          <button onclick="Swal.close();deleteEventById('${e.id}')" class="btn btn-danger btn-sm" style="padding:.4rem 1rem;border-radius:8px"><i class="fas fa-trash me-2"></i>Padam</button>
        </div>`;
      }

      Swal.fire({
        title: `<div style="font-weight:700;color:#fff;margin-bottom:10px;line-height:1.4">${e.title}</div>`,
        html: `<div style="text-align:left;font-size:.85rem;background:rgba(255,255,255,0.03);padding:1.25rem;border-radius:12px;border:1px solid rgba(255,255,255,0.05);max-height:60vh;overflow-y:auto">
          <div class="row g-3">
            <div class="col-6">
              <b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Tarikh</b>
              <span style="color:#e0e0e0">${dateStr}</span>
            </div>
            <div class="col-6">
              <b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Masa</b>
              <span style="color:#e0e0e0">${timeStr}</span>
            </div>
            <div class="col-12">
              <b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Unit / Subunit</b>
              <span style="color:#e0e0e0">${e.extendedProps.nama_unit||'-'} ${e.extendedProps.nama_subunit ? ' / '+e.extendedProps.nama_subunit : ''}</span>
            </div>
            <div class="col-12">
              <b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Tempat</b>
              <span style="color:#e0e0e0">${e.extendedProps.tempat||'-'}</span>
            </div>
            <div class="col-6">
              <b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Peringkat</b>
              <span style="color:#e0e0e0">${e.extendedProps.peringkat||'-'}</span>
            </div>
            <div class="col-6">
              <b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Pengelola</b>
              <span style="color:#e0e0e0">${e.extendedProps.pengelola_keb||'-'}</span>
            </div>
            <div class="col-12">
              <b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Pegawai Bertanggungjawab</b>
              <span style="color:#e0e0e0">${e.extendedProps.nama_pegawai||'-'}</span>
            </div>
            <div class="col-12">
              <b style="color:#cc0001;display:block;font-size:.65rem;text-transform:uppercase;margin-bottom:3px">Catatan</b>
              <span style="color:#e0e0e0">${e.extendedProps.deskripsi||'-'}</span>
            </div>
          </div>
        </div>`,
        showConfirmButton: !canEdit,
        confirmButtonText: 'Tutup',
        footer: footer,
        background: '#0f0f1a', 
        color: '#e0e0e0', 
        confirmButtonColor: '#333',
        width: '550px',
        padding: '1.5rem'
      });
    },
    eventContent: function(arg) {
      if (arg.view.type === 'listWeek') {
        const canEdit = IS_SUPERADMIN || (USER_UNIT && arg.event.extendedProps.unit_id == USER_UNIT);
        let buttons = '';
        if (canEdit) {
          buttons = `<div class="ms-auto d-flex align-items-center">
            <button onclick="event.stopPropagation();editEventById('${arg.event.id}')" class="event-action-btn edit" title="Edit"><i class="fas fa-edit"></i></button>
            <button onclick="event.stopPropagation();deleteEventById('${arg.event.id}')" class="event-action-btn delete" title="Padam"><i class="fas fa-trash"></i></button>
          </div>`;
        }
        return { html: `<div class="d-flex align-items-center w-100">
          <div class="flex-grow-1">${arg.event.title}</div>
          ${buttons}
        </div>` };
      }
      return true;
    },
    eventDrop:function(info){
      const e=info.event;
      const canEdit = IS_SUPERADMIN || (USER_UNIT && e.extendedProps.unit_id == USER_UNIT);
      if(!canEdit) {
        info.revert();
        Swal.fire({toast:true,position:'top-end',icon:'error',title:'Akses ditolak!',showConfirmButton:false,timer:2000,background:'#0f0f1a',color:'#e0e0e0'});
        return;
      }
      fetch('ajax_events.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:`action=move&id=${e.id}&tarikh_mula=${e.startStr}&tarikh_tamat=${e.endStr||''}&csrf=${CSRF}`}).then(r=>r.json()).then(d=>{if(!d.success){info.revert();Swal.fire({toast:true,position:'top-end',icon:'error',title:'Gagal!',showConfirmButton:false,timer:2000,background:'#0f0f1a',color:'#e0e0e0'});}});
    }
  });
  calendar.render();
  
  const allUnitsCb = document.getElementById('allUnitsCb');
  const unitCheckboxes = document.querySelectorAll('.unit-filter:not(#allUnitsCb)');

  allUnitsCb.addEventListener('change', function() {
    unitCheckboxes.forEach(cb => cb.checked = this.checked);
    calendar.refetchEvents();
  });

  unitCheckboxes.forEach(cb => {
    cb.addEventListener('change', function() {
      if(!this.checked) allUnitsCb.checked = false;
      else {
        const allChecked = Array.from(unitCheckboxes).every(c => c.checked);
        if(allChecked) allUnitsCb.checked = true;
      }
      calendar.refetchEvents();
    });
  });
});

document.getElementById('event_unit_id')?.addEventListener('change',function(){
  const sel=this.options[this.selectedIndex];
  const col=sel.dataset.color;
  if(col)document.getElementById('eventColor').value=col;
  
  const unitId = this.value;
  const subSel = document.getElementById('event_subunit_id');
  if(subSel) {
    subSel.value = '';
    Array.from(subSel.options).forEach(opt => {
      if(!opt.value) return;
      if(!unitId || opt.dataset.unit == unitId) opt.style.display = 'block';
      else opt.style.display = 'none';
    });
  }
});

document.getElementById('eventForm').addEventListener('submit',function(e){
  e.preventDefault();const fd=new FormData(this);
  const id=document.getElementById('eventId').value;
  fd.append('action',id?'update':'add');
  fetch('ajax_events.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    bootstrap.Modal.getInstance(document.getElementById('eventModal'))?.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){calendar.refetchEvents();resetForm();}
  });
});

function showEventModal(e) {
  document.getElementById('eventModalTitle').textContent='Edit Aktiviti';
  document.getElementById('eventId').value=e.id;
  document.querySelector('[name=tajuk]').value=e.title;
  document.querySelector('[name=tarikh_mula]').value=e.startStr?.split('T')[0]||'';
  document.querySelector('[name=masa_mula]').value=e.extendedProps.masa_mula||'';
  
  // Guna tarikh_tamat_asli jika ada (kerana e.endStr FullCalendar adalah exclusive +1 hari)
  document.querySelector('[name=tarikh_tamat]').value=e.extendedProps.tarikh_tamat_asli||e.endStr?.split('T')[0]||'';
  document.querySelector('[name=masa_tamat]').value=e.extendedProps.masa_tamat||'';
  
  document.querySelector('[name=tempat]').value=e.extendedProps.tempat||'';
  document.querySelector('[name=deskripsi]').value=e.extendedProps.deskripsi||'';
  document.querySelector('[name=unit_id]').value=e.extendedProps.unit_id||'';
  document.getElementById('event_unit_id')?.dispatchEvent(new Event('change'));
  document.querySelector('[name=subunit_id]').value=e.extendedProps.subunit_id||'';
  document.querySelector('[name=pegawai_id]').value=e.extendedProps.pegawai_id||'';
  document.querySelector('[name=peringkat]').value=e.extendedProps.peringkat||'';
  document.querySelector('[name=pengelola_keb]').value=e.extendedProps.pengelola_keb||'';
  document.getElementById('eventColor').value=e.backgroundColor||'#0d6efd';
  document.querySelector('[name=semua_hari]').checked = e.allDay;
  
  const canEdit = IS_SUPERADMIN || (USER_UNIT && e.extendedProps.unit_id == USER_UNIT);
  document.getElementById('deleteEventBtn').style.display = canEdit ? 'block' : 'none';
  
  new bootstrap.Modal(document.getElementById('eventModal')).show();
}

function editEventById(id) {
  const e = calendar.getEventById(id);
  if (e) showEventModal(e);
}

function deleteEventById(id) {
  document.getElementById('eventId').value = id;
  deleteEvent();
}

function deleteEvent(){
  const id=document.getElementById('eventId').value;
  Swal.fire({title:'Padam Aktiviti?',icon:'warning',background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#cc0001',cancelButtonColor:'#333',showCancelButton:true,confirmButtonText:'Padam'}).then(r=>{
    if(r.isConfirmed){
      fetch('ajax_events.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:`action=delete&id=${id}&csrf=${CSRF}`}).then(r=>r.json()).then(d=>{
        bootstrap.Modal.getInstance(document.getElementById('eventModal'))?.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)calendar.refetchEvents();
      });
    }
  });
}

function resetForm(){
  document.getElementById('eventForm').reset();
  document.getElementById('eventId').value='';
  const subSel = document.getElementById('event_subunit_id');
  if(subSel) Array.from(subSel.options).forEach(opt => opt.style.display = 'block');
}
function showAddEventModal(){
  resetForm();
  document.getElementById('eventModalTitle').textContent='Tambah Aktiviti';
  document.getElementById('deleteEventBtn').style.display='none';
  new bootstrap.Modal(document.getElementById('eventModal')).show();
}

function handleCsvUpload(input) {
  if(!input.files || !input.files[0]) return;
  const fd = new FormData();
  fd.append('file', input.files[0]);
  fd.append('csrf_token', CSRF);
  
  Swal.fire({title:'Memuat naik...',allowOutsideClick:false,didOpen:()=>{Swal.showLoading()}});
  
  fetch('import_csv.php', {method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    input.value='';
    Swal.fire({
      title: d.success?'Berjaya!':'Gagal',
      html: d.message,
      icon: d.success?'success':'error',
      background:'#0f0f1a',color:'#e0e0e0',confirmButtonColor:'#198754'
    });
    if(d.success) calendar.refetchEvents();
  }).catch(e=>{
    input.value='';
    Swal.fire('Ralat','Ralat semasa memuat naik fail','error');
  });
}
</script>
<!-- Hidden file input for CSV upload -->
<input type="file" id="importCsvInput" accept=".csv" style="display:none" onchange="handleCsvUpload(this)">
<?php require_once __DIR__.'/../../templates/footer.php'; ?>
