<?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');
$nama=sanitize($_POST['nama']??'');
$unit_id=($_POST['unit_id']!==''&&$_POST['unit_id']!==null)?intval($_POST['unit_id']):null;
$jawatan_id=intval($_POST['jawatan_id']??0);
$email=sanitize($_POST['email']??'');
if(!$nama||!$jawatan_id)jsonResponse(false,'Sila isi semua medan wajib.');
if(!$email)jsonResponse(false,'Email diperlukan untuk menjana akaun login.');
// Semak email unik dalam users
$chk=$pdo->prepare("SELECT id FROM users WHERE email=? OR username=?");
$chk->execute([$email,$email]);
if($chk->fetch())jsonResponse(false,'Email ini sudah didaftarkan sebagai akaun login. Sila gunakan email lain.');
$gambar='';
if(!empty($_FILES['gambar']['name'])){
  $r=uploadImage($_FILES['gambar'],'pegawai');
  if(!$r['success'])jsonResponse(false,$r['message']);
  $gambar=$r['filename'];
}
$subunit_id=($_POST['subunit_id']!==''&&$_POST['subunit_id']!==null)?intval($_POST['subunit_id']):null;
$fields=['nama'=>$nama,'unit_id'=>$unit_id,'subunit_id'=>$subunit_id,'sektor_id'=>1,'jawatan_id'=>$jawatan_id,
  'email'=>$email,'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']??''),
  'status'=>intval($_POST['status']??1),'gambar'=>$gambar];
$cols=implode(',',array_keys($fields));
$phs=implode(',',array_fill(0,count($fields),'?'));
$stmt=$pdo->prepare("INSERT INTO pegawai ($cols) VALUES ($phs)");
$stmt->execute(array_values($fields));
$pegawai_id=$pdo->lastInsertId();
// Jana akaun login automatik
$defaultPass='password123';
$hashedPass=password_hash($defaultPass,PASSWORD_BCRYPT);
$role='pegawai';
$pdo->prepare("INSERT INTO users (pegawai_id,username,email,password,role,unit_id) VALUES (?,?,?,?,?,?)")
  ->execute([$pegawai_id,$email,$email,$hashedPass,$role,$unit_id]);
logActivity('Tambah','pegawai',$pegawai_id,'Tambah pegawai & akaun: '.$nama);
jsonResponse(true,'Pegawai berjaya ditambah! Akaun login telah dijana.',['email'=>$email,'password'=>$defaultPass]);
