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

// Include database connection from parent directory
require_once "../database.php";

// Make sure it's a POST request (or you can use DELETE method if you prefer)
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["error" => "Only POST method allowed"]);
    exit;
}

// Get JSON input
$data = json_decode(file_get_contents("php://input"));

// Validate user ID
if (!isset($data->id) || !is_numeric($data->id)) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid or missing user ID"]);
    exit;
}

$userId = intval($data->id);

try {
    $stmt = $conn->prepare("DELETE FROM users WHERE id = :id");
    $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        echo json_encode(["message" => "User deleted successfully"]);
    } else {
        http_response_code(404);
        echo json_encode(["error" => "User not found"]);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to delete user", "details" => $e->getMessage()]);
}
?>