<?php
include 'database.php';

header('Content-Type: application/json');

if (!isset($_GET['key'])) {
    echo json_encode(['error' => 'API key is required'], JSON_PRETTY_PRINT);
    exit;
}

$input = trim($_GET['key']);

if (empty($input)) {
    echo json_encode(['error' => 'Invalid input.'], JSON_PRETTY_PRINT);
    exit;
}

if (strpos($input, '') === 0) {
    $sql = "SELECT * FROM users WHERE apiKey = ?";
} else {
    echo json_encode(['error' => 'Invalid key. Please provide a valid key starting with'], JSON_PRETTY_PRINT);
    exit;
}

if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("s", $input);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        echo json_encode([
            'Username' => $user['username'],
            'key_status' => $user['status'],
            'create_date' => $user['createDate'],
            'exp_date' => $user['expiryDate'],
            'key_limit' => $user['limit'],
            'total_used' => $user['used'],
            'balance' => $user['balance'],
        
        ], JSON_PRETTY_PRINT);
    } else {
        echo json_encode(['error' => 'Invalid API key.'], JSON_PRETTY_PRINT);
    }

    $stmt->close();
} else {
    echo json_encode(['error' => 'Failed to prepare SQL statement.'], JSON_PRETTY_PRINT);
}

$conn->close();
?>