<?php
include "../../include/auth.php"; // Authentication
include "../../include/lskfjwfe.php"; // Database connection

header('Content-Type: application/json');

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Validate required fields
if (!isset($_POST['user_display'], $_POST['user_pass'], $_POST['user_role'], $_POST['user_station'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

// Sanitize input
$username = trim($_POST['user_display']);
$password = password_hash($_POST['user_pass'], PASSWORD_BCRYPT); // Hash the password
$userrole = intval($_POST['user_role']);
$stationid = ($_POST['user_station'] == "0") ? null : intval($_POST['user_station']); 

// Check if username already exists
$sql_check = "SELECT id FROM users WHERE username = ?";
$stmt_check = $db->prepare($sql_check);
$stmt_check->bind_param("s", $username);
$stmt_check->execute();
$result_check = $stmt_check->get_result();
if ($result_check->num_rows > 0) {
    echo json_encode(['success' => false, 'message' => 'Username already exists']);
    exit();
}
$stmt_check->close();

// Insert new user
$sql_insert = "INSERT INTO users (username, password, userrole, stationid, created_at) VALUES (?, ?, ?, ?, NOW())";
$stmt_insert = $db->prepare($sql_insert);
$stmt_insert->bind_param("ssii", $username, $password, $userrole, $stationid);
$insert_success = $stmt_insert->execute();

if ($insert_success) {
    // Fetch role name for logging
    $sql_role = "SELECT role_name FROM user_roles WHERE role_id = ?";
    $stmt_role = $db2->prepare($sql_role);
    $stmt_role->bind_param("i", $userrole);
    $stmt_role->execute();
    $result_role = $stmt_role->get_result();
    $role_name = $result_role->fetch_assoc()['role_name'] ?? "Unknown";
    $stmt_role->close();

    // Log the user creation
    $admin_username = $_SESSION['username'];
    $log_action = "Created new user";
    $log_message = "User Creation: $username ($role_name) added by $admin_username";

    $log_sql = "INSERT INTO settings_log (username, action, setting_name, old_value, new_value, timestamp)
                VALUES (?, ?, 'User Creation', NULL, ?, NOW())";
    $stmt_log = $db2->prepare($log_sql);
    $stmt_log->bind_param("sss", $admin_username, $log_action, $log_message);
    $stmt_log->execute();
    $stmt_log->close();

    echo json_encode(['success' => true, 'message' => 'User added successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to add user']);
}
?>
