<?php
require_once __DIR__ . '/db.php';

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

if (!in_array($jabatan, audit_bahagian_list(), true)) {
    echo "<script>alert('Sila pilih bahagian / unit yang sah.'); window.history.back();</script>";
    exit();
}

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

$role = 'Pengguna Biasa';
$approvalStatus = 'pending';
$accountStatus = 'inactive';
$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()) {
    $newUserId = (int) $conn->insert_id;
    add_user_log($conn, $newUserId, $nama, $jabatan, $role, 'Pendaftaran akaun baharu');
    header('Location: login.php?success=pending_approval');
    exit();
}

if ($conn->errno === 1062) {
    echo "<script>alert('IC atau emel telah didaftarkan.'); window.history.back();</script>";
    exit();
}

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