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

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

$action = $_POST['action'] ?? '';

try {
    $db = getDB();
    
    switch ($action) {
        case 'generate':
            $appName = trim($_POST['app_name'] ?? '');
            $usageLimit = !empty($_POST['usage_limit']) ? intval($_POST['usage_limit']) : null;
            
            if (empty($appName)) {
                header('Location: ../api-keys.php?error=' . urlencode('App name is required'));
                exit;
            }
            
            // Generate unique API key
            $apiKey = generateAPIKey();
            
            $stmt = $db->prepare("
                INSERT INTO api_keys (api_key, app_name, usage_limit, status)
                VALUES (?, ?, ?, 'active')
            ");
            $stmt->execute([$apiKey, $appName, $usageLimit]);
            
            logActivity("API key generated for: $appName by " . $_SESSION['admin_email']);
            
            header('Location: ../api-keys.php?success=' . urlencode('API key generated successfully!'));
            break;
            
        case 'assign_servers':
            $apiId = intval($_POST['api_id'] ?? 0);
            $serverIds = $_POST['servers'] ?? [];
            
            if ($apiId <= 0) {
                header('Location: ../api-keys.php?error=' . urlencode('Invalid API ID'));
                exit;
            }
            
            // Begin transaction
            $db->beginTransaction();
            
            // Delete existing assignments
            $stmt = $db->prepare("DELETE FROM api_server_access WHERE api_key_id = ?");
            $stmt->execute([$apiId]);
            
            // Insert new assignments
            if (!empty($serverIds)) {
                $stmt = $db->prepare("INSERT INTO api_server_access (api_key_id, server_id) VALUES (?, ?)");
                foreach ($serverIds as $serverId) {
                    $stmt->execute([$apiId, intval($serverId)]);
                }
            }
            
            $db->commit();
            
            logActivity("Server access updated for API ID: $apiId by " . $_SESSION['admin_email']);
            
            header('Location: ../api-keys.php?success=' . urlencode('Server access updated successfully!'));
            break;
            
        default:
            header('Location: ../api-keys.php?error=' . urlencode('Invalid action'));
    }
    
} catch (PDOException $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    logActivity("API management error: " . $e->getMessage(), 'error');
    header('Location: ../api-keys.php?error=' . urlencode('Database error occurred'));
}
