<?php
require_once __DIR__ . '/db.php';
require_login();
require_roles(['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']);
require_department_access($conn, 'senarai_pengguna', 'update');

$userId = (int) ($_POST['user_id'] ?? 0);
$actionType = trim($_POST['action_type'] ?? 'profile');
$nama = trim($_POST['nama'] ?? '');
$emel = trim($_POST['emel'] ?? '');
$role = trim($_POST['role'] ?? '');
$jabatan = trim($_POST['jabatan'] ?? '');
$newPassword = $_POST['new_password'] ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';

if ($userId <= 0) {
    header('Location: senarai_pengguna.php?error=invalid_role');
    exit();
}

$currentManagerRole = current_user_role();
$allowedRoles = $currentManagerRole === 'Pentadbir Sistem'
    ? ['Pengguna Biasa', 'Admin Audit', 'Pentadbir Sistem']
    : ['Pengguna Biasa', 'Admin Audit'];

if (!in_array($role, $allowedRoles, true)) {
    if ($actionType === 'profile') {
        header('Location: edit_pengguna.php?id=' . $userId . '&error=invalid_role');
        exit();
    }
}

$userStmt = $conn->prepare("SELECT nama, role FROM users WHERE id = ? LIMIT 1");
$userStmt->bind_param('i', $userId);
$userStmt->execute();
$targetUser = $userStmt->get_result()->fetch_assoc();

if (!$targetUser) {
    header('Location: senarai_pengguna.php');
    exit();
}

if ($currentManagerRole === 'Admin Audit' && ($targetUser['role'] ?? '') === 'Pentadbir Sistem') {
    header('Location: senarai_pengguna.php?error=protected_system_admin');
    exit();
}

$checkStmt = $conn->prepare("SELECT id FROM users WHERE emel = ? AND id <> ? LIMIT 1");
if ($actionType === 'password') {
    if ($newPassword === '' || $confirmPassword === '' || $newPassword !== $confirmPassword) {
        header('Location: edit_pengguna.php?id=' . $userId . '&error=password_mismatch');
        exit();
    }
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    $passwordStmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
    $passwordStmt->bind_param('si', $hashedPassword, $userId);
    $passwordStmt->execute();
    add_current_user_log($conn, 'Mengemaskini kata laluan pengguna ' . ($targetUser['nama'] ?? 'Tidak Diketahui'));
    header('Location: edit_pengguna.php?id=' . $userId . '&success=password_updated');
    exit();
}

if (!in_array($jabatan, audit_bahagian_list(), true)) {
    header('Location: edit_pengguna.php?id=' . $userId . '&error=invalid_role');
    exit();
}

$checkStmt->bind_param('si', $emel, $userId);
$checkStmt->execute();
if ($checkStmt->get_result()->fetch_assoc()) {
    header('Location: edit_pengguna.php?id=' . $userId . '&error=duplicate');
    exit();
}

$stmt = $conn->prepare("UPDATE users SET nama = ?, emel = ?, role = ?, jabatan = ? WHERE id = ?");
$stmt->bind_param('ssssi', $nama, $emel, $role, $jabatan, $userId);
$stmt->execute();

add_current_user_log($conn, 'Mengemaskini maklumat pengguna ' . ($targetUser['nama'] ?? 'Tidak Diketahui'));

header('Location: edit_pengguna.php?id=' . $userId . '&success=updated');
exit();
