<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();if(!isSuperAdmin())jsonResponse(false,'Akses ditolak.');
$action=$_GET['action']??'create';
if($action==='reset'){
  if(!verifyCsrfToken($_GET['csrf']??''))jsonResponse(false,'CSRF Error');
  $defaultPwd=password_hash('Admin@1234',PASSWORD_DEFAULT);
  $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([$defaultPwd,intval($_GET['id'])]);
  jsonResponse(true,'Kata laluan direset ke: Admin@1234');
}
if($action==='delete'){
  if(!verifyCsrfToken($_GET['csrf']??''))jsonResponse(false,'CSRF Error');
  $id=intval($_GET['id']);
  if($id===$_SESSION['user_id'])jsonResponse(false,'Anda tidak boleh memadam akaun sendiri.');
  
  $stmt=$pdo->prepare("SELECT username FROM users WHERE id=?");
  $stmt->execute([$id]);
  $u=$stmt->fetch();
  if(!$u)jsonResponse(false,'Pengguna tidak ditemui.');

  $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$id]);
  logActivity('Padam','users',$id,'Memadam pengguna: '.$u['username']);
  jsonResponse(true,'Pengguna berjaya dipadam!');
}
if($_SERVER['REQUEST_METHOD']==='POST'){
  if(!verifyCsrfToken($_POST['csrf_token']??''))jsonResponse(false,'CSRF Error');
  $un=sanitize($_POST['username']??'');$em=sanitize($_POST['email']??'');$pw=$_POST['password']??'';
  if(!$un||!$em||strlen($pw)<8)jsonResponse(false,'Data tidak lengkap atau kata laluan terlalu pendek.');
  $chk=$pdo->prepare("SELECT id FROM users WHERE username=? OR email=?");$chk->execute([$un,$em]);
  if($chk->fetch())jsonResponse(false,'Username atau email sudah digunakan.');
  $stmt=$pdo->prepare("INSERT INTO users (username,email,password,role,unit_id) VALUES (?,?,?,?,?)");
  $stmt->execute([$un,$em,password_hash($pw,PASSWORD_DEFAULT),sanitize($_POST['role']??'pegawai'),($_POST['unit_id']??null)?:null]);
  logActivity('Cipta','users',$pdo->lastInsertId(),'Cipta pengguna: '.$un);
  jsonResponse(true,'Pengguna berjaya dicipta!');
}
