<?php
// Set the path to the users.json 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 email to delete is provided in the POST request.
if (isset($_POST['email'])) {
    $emailToDelete = $_POST['email'];

    // Read the existing data from the JSON file.
    $jsonData = file_get_contents($usersFilePath);
    $users = json_decode($jsonData, true) ?: [];

    // Use array_filter to create a new array that excludes the user
    // with the specified email.
    $users = array_filter($users, function ($user) use ($emailToDelete) {
        return $user['email'] !== $emailToDelete;
    });

    // Re-index the array to ensure keys are sequential after deletion.
    $users = array_values($users);

    // Encode the new 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 write to file.']);
    }
} else {
    // Return an error if the email is missing.
    echo json_encode(['success' => false, 'message' => 'Invalid email provided.']);
}
?>
