<?php
// ajax/wa_verificar_config.php - Verifica a configuração da Evolution API
require_once __DIR__ . '/../functions.php';
require_once __DIR__ . '/../auth.php';
requireLogin();

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

$waApiUrl = getConfig('wa_api_url', '');
$waToken = getConfig('wa_api_token', '');
$waInstancia = getConfig('wa_instancia', '');

if (empty($waApiUrl) || empty($waToken) || empty($waInstancia)) {
    echo json_encode([
        'success' => false,
        'message' => 'WhatsApp não configurado',
        'config' => [
            'api_url' => $waApiUrl ? '✅ Configurado' : '❌ Não configurado',
            'token' => $waToken ? '✅ Configurado' : '❌ Não configurado',
            'instancia' => $waInstancia ? '✅ Configurado' : '❌ Não configurado'
        ]
    ]);
    exit;
}

// Testar conexão com a Evolution API
$url = rtrim($waApiUrl, '/') . "/instance/connectionState/{$waInstancia}";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'apikey: ' . $waToken
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

echo json_encode([
    'success' => true,
    'http_code' => $httpCode,
    'response' => json_decode($response, true),
    'curl_error' => $curlError,
    'config' => [
        'api_url' => $waApiUrl,
        'instancia' => $waInstancia,
        'token' => substr($waToken, 0, 10) . '...'
    ]
]);