<?php
// Set the path to the users.json file.
// __DIR__ gives the directory of the current file.
$usersFilePath = __DIR__ . '/../database/users.json';

// Set the Content-Type header to application/json for all responses.
header('Content-Type: application/json');

// Check if the necessary POST data exists.
if (isset($_POST['userName'], $_POST['userPhone'], $_POST['userEmail'], $_POST['userRole'])) {
    // Read the existing data from the JSON file.
    $jsonData = file_get_contents($usersFilePath);
    $users = json_decode($jsonData, true) ?: [];

    // Validate if the email already exists to prevent duplicates.
    foreach ($users as $user) {
        if ($user['email'] === $_POST['userEmail']) {
            echo json_encode(['success' => false, 'message' => 'Email already exists.']);
            exit;
        }
    }

    // Construct the new user array using data from the POST request.
    // The password field is included, using a default value if not provided.
    $newUser = [
        'name' => $_POST['userName'],
        'email' => $_POST['userEmail'],
        'phone' => $_POST['userPhone'],
        'role' => $_POST['userRole'],
        'password' => $_POST['userPassword'] ?? 'default_password'
    ];

    // Add the new user to the end of the users array.
    $users[] = $newUser;

    // Encode the updated array back into a JSON string with pretty printing.
    $updatedJson = json_encode($users, JSON_PRETTY_PRINT);

    // Save the new JSON string to the file.
    if (file_put_contents($usersFilePath, $updatedJson) !== false) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to save data to file.']);
    }
} else {
    // Return an error if required data is missing.
    echo json_encode(['success' => false, 'message' => 'Invalid or missing data.']);
}
?>
