<?php

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

$nama = trim($_POST['nama'] ?? '');
$ic = trim($_POST['ic'] ?? '');
$emel = trim($_POST['emel'] ?? '');
$role = trim($_POST['role'] ?? '');
$jabatan = trim($_POST['jabatan'] ?? '');
$password = $_POST['password'] ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';

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

if (!in_array($role, $allowedRoles, true) || !in_array($jabatan, audit_bahagian_list(), true)) {
    header('Location: daftar_pengguna.php?error=invalid_role');
    exit();
}

if ($password !== $confirmPassword) {
    echo "<script>alert('Kata laluan tidak sepadan.'); window.history.back();</script>";
    exit();
}

$approvalStatus = 'active';
$accountStatus = 'active';
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

$stmt = $conn->prepare("
    INSERT INTO users (nama, ic, emel, role, jabatan, approval_status, account_status, password)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");
$stmt->bind_param('ssssssss', $nama, $ic, $emel, $role, $jabatan, $approvalStatus, $accountStatus, $hashedPassword);

if ($stmt->execute()) {
    add_current_user_log($conn, 'Mendaftar pengguna: ' . $nama . ' (' . $role . ')');
    header('Location: login.php?success=registered');
    exit();
}

if ($conn->errno === 1062) {
    header('Location: daftar_pengguna.php?error=duplicate');
    exit();
}

die('Ralat pendaftaran pengguna: ' . $stmt->error);
