<?php
require '../vendor/autoload.php';
require '../db_config.php';
require 'authenticate.php'; // Secure API

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

// Authenticate user
$user_id = authenticate(); // Get authenticated user ID

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Retrieve all API keys for the user
    $stmt = $pdo->prepare("SELECT id, app_name, api_key FROM api_keys WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $apiKeys = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(["api_keys" => $apiKeys]);
} elseif ($method === 'POST') {
    // Generate new API key
    $data = json_decode(file_get_contents("php://input"), true);
    $app_name = $data['app_name'] ?? null;

    if (!$app_name) {
        echo json_encode(["error" => "App name is required"]);
        exit;
    }

    $api_key = bin2hex(random_bytes(16)); // Generate secure API key

    $stmt = $pdo->prepare("INSERT INTO api_keys (user_id, app_name, api_key) VALUES (?, ?, ?)");
    $stmt->execute([$user_id, $app_name, $api_key]);

    echo json_encode(["message" => "API key generated successfully", "api_key" => $api_key]);
} elseif ($method === 'DELETE') {
    // Delete an API key
    $data = json_decode(file_get_contents("php://input"), true);
    $api_key = $data['api_key'] ?? null;

    if (!$api_key) {
        echo json_encode(["error" => "API key is required"]);
        exit;
    }

    $stmt = $pdo->prepare("DELETE FROM api_keys WHERE user_id = ? AND api_key = ?");
    $stmt->execute([$user_id, $api_key]);

    echo json_encode(["message" => "API key deleted successfully"]);
} else {
    echo json_encode(["error" => "Invalid request method"]);
}
?>
