<?php
require_once __DIR__ . '/../../config/config.php';
requireAuth();

if (!isset($_GET['csrf_token']) || !verifyCSRFToken($_GET['csrf_token'])) {
    header('Location: ../api-keys.php?error=' . urlencode('Invalid request'));
    exit;
}

$apiId = intval($_GET['id'] ?? 0);

if ($apiId <= 0) {
    header('Location: ../api-keys.php?error=' . urlencode('Invalid API ID'));
    exit;
}

try {
    $db = getDB();
    
    // Delete API key (cascade will delete api_server_access entries)
    $stmt = $db->prepare("DELETE FROM api_keys WHERE id = ?");
    $stmt->execute([$apiId]);
    
    logActivity("API key deleted (ID: $apiId) by " . $_SESSION['admin_email']);
    
    header('Location: ../api-keys.php?success=' . urlencode('API key deleted successfully'));
} catch (PDOException $e) {
    logActivity("Delete API error: " . $e->getMessage(), 'error');
    header('Location: ../api-keys.php?error=' . urlencode('Failed to delete API key'));
}
