<?php
header("Content-Type: application/json");
require_once '../config/db.php';

$emp_id = $_POST['emp_id'];
$user_id = !empty($_POST['user_id']) ? $_POST['user_id'] : null;
$role = $_POST['role'];
$user_name = $_POST['user_name'];
$mobile = $_POST['mobile_number'];

// Securely hash the password
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Check if username already exists
$check = $conn->prepare("SELECT id FROM team_grovia WHERE user_name = ?");
$check->bind_param("s", $user_name);
$check->execute();
if ($check->get_result()->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "Username '$user_name' is already taken."]);
    exit();
}

$sql = "INSERT INTO team_grovia (emp_id, user_id, role, password, user_name, mobile_number) VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sissss", $emp_id, $user_id, $role, $password, $user_name, $mobile);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Staff member $user_name ($emp_id) has been registered."]);
} else {
    echo json_encode(["success" => false, "message" => "Database Error: " . $conn->error]);
}