<?php
require_once __DIR__.'/../../config/functions.php';
$action=$_POST['action'] ?? $_GET['action'] ?? 'list';

// Only require login for modifications (add, update, delete, move)
if($action !== 'list' && $_SERVER['REQUEST_METHOD'] === 'POST'){
  requireLogin();
}

if($action==='list'||$_SERVER['REQUEST_METHOD']==='GET'){
  $where="WHERE t.status=1";$params=[];
  if(!empty($_GET['start'])){$where.=" AND t.tarikh_mula>=?";$params[]=$_GET['start'];}
  if(!empty($_GET['end'])){$where.=" AND t.tarikh_mula<=?";$params[]=$_GET['end'];}
  
  if(!empty($_GET['units'])){
    $units = explode(',', $_GET['units']);
    $units = array_filter($units, 'is_numeric');
    if(!empty($units)){
      $placeholders = implode(',', array_fill(0, count($units), '?'));
      $where .= " AND t.unit_id IN ($placeholders)";
      $params = array_merge($params, $units);
    }
  }
  $stmt=$pdo->prepare("SELECT t.*, u.nama_unit, u.warna as unit_warna, s.nama_subunit, p.nama as nama_pegawai 
    FROM takwim t 
    LEFT JOIN unit u ON t.unit_id=u.id 
    LEFT JOIN subunit s ON t.subunit_id=s.id
    LEFT JOIN pegawai p ON t.pegawai_id=p.id
    $where ORDER BY t.tarikh_mula");
  $stmt->execute($params);$events=$stmt->fetchAll();
  $out=[];
  foreach($events as $e){
    $start = $e['tarikh_mula'].($e['masa_mula']?' '.$e['masa_mula']:'');
    $end = $e['tarikh_tamat']?$e['tarikh_tamat'].($e['masa_tamat']?' '.$e['masa_tamat']:''):null;
    
    // FullCalendar end date is exclusive. If it's an all-day event, add 1 day to the end date
    // so that it shows correctly in the calendar (e.g. 8 to 9 shows on 8 and 9).
    if((bool)$e['semua_hari'] && $e['tarikh_tamat']){
       $endDate = new DateTime($e['tarikh_tamat']);
       $endDate->modify('+1 day');
       $end = $endDate->format('Y-m-d');
    }

    $out[]=['id'=>$e['id'],'title'=>$e['tajuk'],'start'=>$start,'end'=>$end,
      'allDay'=>(bool)$e['semua_hari'],'backgroundColor'=>$e['warna']??$e['unit_warna']??'#0d6efd',
      'borderColor'=>'transparent',
      'extendedProps'=>[
        'tempat'=>$e['tempat'],
        'deskripsi'=>$e['deskripsi'],
        'unit_id'=>$e['unit_id'],
        'nama_unit'=>$e['nama_unit'],
        'subunit_id'=>$e['subunit_id'],
        'nama_subunit'=>$e['nama_subunit'],
        'pegawai_id'=>$e['pegawai_id'],
        'nama_pegawai'=>$e['nama_pegawai'],
        'peringkat'=>$e['peringkat'],
        'pengelola_keb'=>$e['pengelola_keb'],
        'bidang'=>$e['bidang'],
        'masa_mula'=>$e['masa_mula'],
        'masa_tamat'=>$e['masa_tamat'],
        'tarikh_tamat_asli'=>$e['tarikh_tamat']
      ]];
  }
  header('Content-Type: application/json');echo json_encode($out);exit;
}

if(!verifyCsrfToken($_POST['csrf_token']??$_POST['csrf']??''))jsonResponse(false,'CSRF Error');

if($action==='add'){
  $semua_hari = isset($_POST['semua_hari']) ? 1 : (empty($_POST['masa_mula']) ? 1 : 0);
  $stmt=$pdo->prepare("INSERT INTO takwim (tajuk,unit_id,subunit_id,pegawai_id,tarikh_mula,tarikh_tamat,masa_mula,masa_tamat,tempat,peringkat,pengelola_keb,bidang,warna,deskripsi,semua_hari,created_by) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
  $stmt->execute([
    sanitize($_POST['tajuk']),
    ($_POST['unit_id']??null)?:null,
    ($_POST['subunit_id']??null)?:null,
    ($_POST['pegawai_id']??null)?:null,
    $_POST['tarikh_mula'],
    ($_POST['tarikh_tamat']??null)?:null,
    ($_POST['masa_mula']??null)?:null,
    ($_POST['masa_tamat']??null)?:null,
    sanitize($_POST['tempat']??''),
    sanitize($_POST['peringkat']??''),
    sanitize($_POST['pengelola_keb']??''),
    sanitize($_POST['bidang']??''),
    sanitize($_POST['warna']??'#0d6efd'),
    sanitize($_POST['deskripsi']??''),
    $semua_hari,
    currentUserId()
  ]);
  logActivity('Tambah','takwim',$pdo->lastInsertId(),'Tambah: '.sanitize($_POST['tajuk']));
  jsonResponse(true,'Aktiviti ditambah!');
}
if($action==='update'){
  $id=intval($_POST['event_id']);
  // Permission check
  $event = $pdo->prepare("SELECT unit_id FROM takwim WHERE id=?");
  $event->execute([$id]);
  $event = $event->fetch();
  if(!$event) jsonResponse(false, 'Rekod tidak dijumpai.');
  if(!isSuperAdmin() && $event['unit_id'] != currentUnitId()) jsonResponse(false, 'Akses ditolak. Anda hanya boleh mengubah aktiviti unit anda sahaja.');

  $semua_hari = isset($_POST['semua_hari']) ? 1 : (empty($_POST['masa_mula']) ? 1 : 0);
  $stmt=$pdo->prepare("UPDATE takwim SET tajuk=?,unit_id=?,subunit_id=?,pegawai_id=?,tarikh_mula=?,tarikh_tamat=?,masa_mula=?,masa_tamat=?,tempat=?,peringkat=?,pengelola_keb=?,bidang=?,warna=?,deskripsi=?,semua_hari=? WHERE id=?");
  $stmt->execute([
    sanitize($_POST['tajuk']),
    ($_POST['unit_id']??null)?:null,
    ($_POST['subunit_id']??null)?:null,
    ($_POST['pegawai_id']??null)?:null,
    $_POST['tarikh_mula'],
    ($_POST['tarikh_tamat']??null)?:null,
    ($_POST['masa_mula']??null)?:null,
    ($_POST['masa_tamat']??null)?:null,
    sanitize($_POST['tempat']??''),
    sanitize($_POST['peringkat']??''),
    sanitize($_POST['pengelola_keb']??''),
    sanitize($_POST['bidang']??''),
    sanitize($_POST['warna']??'#0d6efd'),
    sanitize($_POST['deskripsi']??''),
    $semua_hari,
    $id
  ]);
  jsonResponse(true,'Aktiviti dikemaskini!');
}
if($action==='move'){
  $id=intval($_POST['id']);
  // Permission check
  $event = $pdo->prepare("SELECT unit_id FROM takwim WHERE id=?");
  $event->execute([$id]);
  $event = $event->fetch();
  if(!$event || (!isSuperAdmin() && $event['unit_id'] != currentUnitId())) jsonResponse(false, 'Akses ditolak.');

  $pdo->prepare("UPDATE takwim SET tarikh_mula=?,tarikh_tamat=? WHERE id=?")->execute([$_POST['tarikh_mula'],$_POST['tarikh_tamat']?:null,$id]);
  jsonResponse(true,'Tarikh dikemaskini!');
}
if($action==='delete'){
  $id = intval($_POST['id']);
  // Permission check
  $event = $pdo->prepare("SELECT unit_id FROM takwim WHERE id=?");
  $event->execute([$id]);
  $event = $event->fetch();
  if(!$event) jsonResponse(false, 'Rekod tidak dijumpai.');
  if(!isSuperAdmin() && $event['unit_id'] != currentUnitId()) jsonResponse(false, 'Akses ditolak. Anda hanya boleh memadam aktiviti unit anda sahaja.');

  $pdo->prepare("UPDATE takwim SET status=0 WHERE id=?")->execute([$id]);
  jsonResponse(true,'Aktiviti dipadam!');
}
jsonResponse(false,'Tindakan tidak sah.');
