<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();
if (empty($_POST) && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0) {
    jsonResponse(false, 'Ralat: Saiz fail melebihi had maksimum pelayan. Sila muat naik gambar yang lebih kecil (bawah 30MB).');
}
if(!isAdmin())jsonResponse(false,'Akses ditolak.');
if(!verifyCsrfToken($_POST['csrf_token']??''))jsonResponse(false,'CSRF Error');
$id=intval($_POST['id']??0);
$nama=sanitize($_POST['nama']??'');
if(!$id||!$nama)jsonResponse(false,'Data tidak lengkap.');
$existing=$pdo->prepare("SELECT gambar FROM pegawai WHERE id=?");$existing->execute([$id]);$existing=$existing->fetch();
if(!$existing)jsonResponse(false,'Rekod tidak dijumpai.');
$gambar=$existing['gambar'];
if(!empty($_FILES['gambar']['name'])){
  $r=uploadImage($_FILES['gambar'],'pegawai');
  if(!$r['success']) jsonResponse(false, $r['message']);
  if($gambar && $gambar != 'default.png') deleteFile('pegawai/'.$gambar);
  $gambar=$r['filename'];
}
$unit_id=($_POST['unit_id']!==''&&isset($_POST['unit_id']))?intval($_POST['unit_id']):null;
$subunit_id=($_POST['subunit_id']!==''&&isset($_POST['subunit_id']))?intval($_POST['subunit_id']):null;
$stmt=$pdo->prepare("UPDATE pegawai SET nama=?,unit_id=?,subunit_id=?,jawatan_id=?,email=?,no_telefon=?,no_telefon_pejabat=?,bio=?,tugas_utama=?,facebook=?,twitter=?,linkedin=?,instagram=?,status=?,gambar=? WHERE id=?");
$stmt->execute([sanitize($_POST['nama']??''),$unit_id,$subunit_id,intval($_POST['jawatan_id']),sanitize($_POST['email']??''),sanitize($_POST['no_telefon']??''),sanitize($_POST['no_telefon_pejabat']??''),sanitize($_POST['bio']??''),sanitize($_POST['tugas_utama']??''),sanitize($_POST['facebook']??''),sanitize($_POST['twitter']??''),sanitize($_POST['linkedin']??''),sanitize($_POST['instagram']??''),intval($_POST['status']??1),$gambar,$id]);
logActivity('Kemaskini','pegawai',$id,'Kemaskini pegawai: '.$nama);
jsonResponse(true,'Pegawai berjaya dikemaskini!');
