<?php
session_start();
include 'database.php';

if (!isset($_SESSION['username'])) {
    header('Location: ../adminx');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $json_data = file_get_contents("php://input");

    $data = json_decode($json_data, true);

    if ($data === null) {
        echo json_encode(["success" => false, "message" => "Invalid JSON data"]);
        exit;
    }

    $apiKey = isset($data['apiKey']) ? $data['apiKey'] : null;

    if (!$apiKey) {
        echo json_encode(["success" => false, "message" => "API key is required"]);
        exit;
    }

    $sql = "DELETE FROM users WHERE apiKey = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $apiKey);

    if ($stmt->execute()) {
        echo json_encode(["success" => true, "message" => "API key deleted successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Error deleting the API key"]);
    }

    $stmt->close();
    exit;
}
?>