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

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/ApiIntegrationService.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Login required.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $auth = new Auth($conn);
    if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized.']);
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
        exit;
    }

    $integrationId = (int)($_POST['integration_id'] ?? 0);
    $providerKey = trim((string)($_POST['provider_key'] ?? 'custom'));
    $apiKey = (string)($_POST['api_key'] ?? '');
    $baseUrl = trim((string)($_POST['api_base_url'] ?? ''));
    $modelName = trim((string)($_POST['model_name'] ?? ''));

    // If the key field was left blank/masked, fall back to the stored (decrypted) key for this integration.
    $isMasked = ($apiKey === '' || preg_match('/^\*+$/', $apiKey));
    if ($integrationId > 0 && $isMasked) {
        $service = new ApiIntegrationService($conn, $integrationId);
        $stored = $service->getRawSettings();
        $apiKey = $stored['api_key'];
        if ($providerKey === '') {
            $providerKey = $stored['provider_key'];
        }
        if ($baseUrl === '') {
            $baseUrl = $stored['api_base_url'];
        }
        if ($modelName === '') {
            $modelName = $stored['model_name'];
        }
    }

    $result = ApiIntegrationService::testConnection($providerKey, $apiKey, $baseUrl, $modelName);
    echo json_encode($result);
} catch (Throwable $e) {
    error_log('API integration test failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
