<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();
if(!verifyCsrfToken($_POST['csrf_token']??''))jsonResponse(false,'CSRF Error');

$userId=currentUserId();
// Dapatkan pegawai_id user ini
$u=$pdo->prepare("SELECT pegawai_id FROM users WHERE id=?");
$u->execute([$userId]);$u=$u->fetch();
$pegawai_id=$u['pegawai_id']??0;
if(!$pegawai_id)jsonResponse(false,'Akaun anda tidak dikaitkan dengan profil pegawai.');

$action=$_POST['action']??'update_profil';

// Update maklumat profil pegawai
if($action==='update_profil'){
  $no_telefon=sanitize($_POST['no_telefon']??'');
  $no_telefon_pejabat=sanitize($_POST['no_telefon_pejabat']??'');
  $bio=sanitize($_POST['bio']??'');
  $tugas_utama=sanitize($_POST['tugas_utama']??'');
  $facebook=sanitize($_POST['facebook']??'');
  $twitter=sanitize($_POST['twitter']??'');
  $linkedin=sanitize($_POST['linkedin']??'');
  $instagram=sanitize($_POST['instagram']??'');
  // Update gambar jika ada
  $gambar_sql='';$gambar_params=[];
  if(!empty($_FILES['gambar']['name'])){
    $r=uploadImage($_FILES['gambar'],'pegawai');
    if(!$r['success'])jsonResponse(false,$r['message']);
    // Padam gambar lama
    $old=$pdo->prepare("SELECT gambar FROM pegawai WHERE id=?");$old->execute([$pegawai_id]);$old=$old->fetch();
    if($old['gambar']&&$old['gambar']!='default.png')deleteFile('pegawai/'.$old['gambar']);
    $gambar_sql=',gambar=?';$gambar_params[]=$r['filename'];
  }
  $stmt=$pdo->prepare("UPDATE pegawai SET no_telefon=?,no_telefon_pejabat=?,bio=?,tugas_utama=?,facebook=?,twitter=?,linkedin=?,instagram=?$gambar_sql WHERE id=?");
  $params=[$no_telefon,$no_telefon_pejabat,$bio,$tugas_utama,$facebook,$twitter,$linkedin,$instagram];
  if($gambar_params)$params=array_merge($params,$gambar_params);
  $params[]=$pegawai_id;
  $stmt->execute($params);
  logActivity('Kemaskini Profil','pegawai',$pegawai_id,'Kemaskini profil sendiri');
  jsonResponse(true,'Profil berjaya dikemaskini!');
}

// Tukar password
if($action==='tukar_password'){
  $cur=$_POST['current_password']??'';
  $new=$_POST['new_password']??'';
  $con=$_POST['confirm_password']??'';
  $pw=$pdo->prepare("SELECT password FROM users WHERE id=?");$pw->execute([$userId]);$pw=$pw->fetch();
  if(!password_verify($cur,$pw['password']))jsonResponse(false,'Kata laluan semasa tidak betul.');
  if(strlen($new)<6)jsonResponse(false,'Kata laluan baru minimum 6 aksara.');
  if($new!==$con)jsonResponse(false,'Pengesahan kata laluan tidak sepadan.');
  $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($new,PASSWORD_BCRYPT),$userId]);
  logActivity('Tukar Password','users',$userId,'Tukar password sendiri');
  jsonResponse(true,'Kata laluan berjaya ditukar!');
}

// Get profil data
if($_SERVER['REQUEST_METHOD']==='GET'||$action==='get'){
  $p=$pdo->prepare("SELECT p.*,j.nama_jawatan,u.nama_unit,u.warna FROM pegawai p JOIN jawatan j ON p.jawatan_id=j.id LEFT JOIN unit u ON p.unit_id=u.id WHERE p.id=?");
  $p->execute([$pegawai_id]);$p=$p->fetch();
  if(!$p)jsonResponse(false,'Profil tidak dijumpai.');
  $p['gambar_url']=getPegawaiImage($p['gambar']);
  jsonResponse(true,'',$p);
}

jsonResponse(false,'Tindakan tidak sah.');
