<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();
if(!isAdmin())jsonResponse(false,'Akses ditolak.');
$action=$_GET['action']??$_POST['action']??'';

// Semak info login pegawai
if($action==='info'){
  $pegawai_id=intval($_GET['pegawai_id']??0);
  $u=$pdo->prepare("SELECT id,username,email,role,status,last_login,created_at FROM users WHERE pegawai_id=?");
  $u->execute([$pegawai_id]);$u=$u->fetch();
  if(!$u)jsonResponse(false,'Tiada akaun login untuk pegawai ini.');
  jsonResponse(true,'',$u);
}

// Reset password
if($action==='reset'){
  if(!verifyCsrfToken($_GET['csrf']??$_POST['csrf_token']??''))jsonResponse(false,'CSRF Error');
  $pegawai_id=intval($_POST['pegawai_id']??0);
  $new_pass=trim($_POST['new_pass']??'');
  if(!$pegawai_id)jsonResponse(false,'ID tidak sah.');
  if(strlen($new_pass)<6)jsonResponse(false,'Password mesti sekurang-kurangnya 6 aksara.');
  $u=$pdo->prepare("SELECT id FROM users WHERE pegawai_id=?");
  $u->execute([$pegawai_id]);$u=$u->fetch();
  if(!$u)jsonResponse(false,'Tiada akaun untuk pegawai ini.');
  $hashed=password_hash($new_pass,PASSWORD_BCRYPT);
  $pdo->prepare("UPDATE users SET password=?,token_reset=NULL WHERE pegawai_id=?")->execute([$hashed,$pegawai_id]);
  logActivity('Reset Password','users',$u['id'],'Reset password untuk pegawai ID: '.$pegawai_id);
  jsonResponse(true,'Password berjaya direset kepada: '.$new_pass,['password'=>$new_pass]);
}

// Reset ke default
if($action==='reset_default'){
  if(!verifyCsrfToken($_GET['csrf']??''))jsonResponse(false,'CSRF Error');
  $pegawai_id=intval($_GET['pegawai_id']??0);
  $u=$pdo->prepare("SELECT id FROM users WHERE pegawai_id=?");
  $u->execute([$pegawai_id]);$u=$u->fetch();
  if(!$u)jsonResponse(false,'Tiada akaun untuk pegawai ini.');
  $hashed=password_hash('password123',PASSWORD_BCRYPT);
  $pdo->prepare("UPDATE users SET password=?,token_reset=NULL WHERE pegawai_id=?")->execute([$hashed,$pegawai_id]);
  logActivity('Reset Password Default','users',$u['id'],'Reset ke default untuk pegawai ID: '.$pegawai_id);
  jsonResponse(true,'Password direset ke: password123',['password'=>'password123']);
}

// Toggle status akaun
if($action==='toggle_status'){
  if(!verifyCsrfToken($_GET['csrf']??''))jsonResponse(false,'CSRF Error');
  $pegawai_id=intval($_GET['pegawai_id']??0);
  $u=$pdo->prepare("SELECT id,status FROM users WHERE pegawai_id=?");
  $u->execute([$pegawai_id]);$u=$u->fetch();
  if(!$u)jsonResponse(false,'Tiada akaun untuk pegawai ini.');
  $new=$u['status']?0:1;
  $pdo->prepare("UPDATE users SET status=? WHERE pegawai_id=?")->execute([$new,$pegawai_id]);
  jsonResponse(true,$new?'Akaun diaktifkan.':'Akaun dilumpuhkan.',['status'=>$new]);
}

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