<?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);
$status = $_GET['status'] ?? '';

if ($apiId <= 0 || !in_array($status, ['active', 'inactive'])) {
    header('Location: ../api-keys.php?error=' . urlencode('Invalid parameters'));
    exit;
}

try {
    $db = getDB();
    $stmt = $db->prepare("UPDATE api_keys SET status = ? WHERE id = ?");
    $stmt->execute([$status, $apiId]);
    
    logActivity("API status changed to $status (ID: $apiId) by " . $_SESSION['admin_email']);
    
    header('Location: ../api-keys.php?success=' . urlencode('API key status updated successfully'));
} catch (PDOException $e) {
    logActivity("Toggle API error: " . $e->getMessage(), 'error');
    header('Location: ../api-keys.php?error=' . urlencode('Failed to update API key status'));
}
