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

// Check database connection
if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// Allow only POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

// Read and decode JSON input
$postData = json_decode(file_get_contents('php://input'), true);

// Validate userId
if (!isset($postData['userId'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid userId']);
    exit;
}

$userId = intval($postData['userId']); // Convert to integer for safety

// Prepare the DELETE query
$sql = "DELETE FROM users WHERE id = ?";
$stmt = mysqli_prepare($db, $sql);

if ($stmt) {
    mysqli_stmt_bind_param($stmt, "i", $userId);
    if (mysqli_stmt_execute($stmt)) {
        echo json_encode(['status' => 'success', 'message' => 'User deleted successfully']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to delete user']);
    }
    mysqli_stmt_close($stmt);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Query preparation failed']);
}

mysqli_close($db);
?>
