<?php
// Set response type to JSON
header('Content-Type: application/json');

// File path where roles are stored
$rolesFilePath = __DIR__ . '/../database/roles.json';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Invalid request method. Only POST is allowed.']);
    exit;
}

// Read incoming JSON data
$rawData = file_get_contents('php://input');
$rolesData = json_decode($rawData, true);

// Validate decoded data
if (!is_array($rolesData)) {
    echo json_encode(['error' => 'Invalid JSON data']);
    exit;
}

// Save JSON to file
if (file_put_contents($rolesFilePath, json_encode($rolesData, JSON_PRETTY_PRINT))) {
    echo json_encode(['status' => 'success', 'message' => 'Roles saved successfully']);
} else {
    echo json_encode(['error' => 'Failed to write to roles.json']);
}
?>
