<?php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/helpers/EmailService.php';
require_once __DIR__ . '/controllers/IntegracionController.php';
header('Content-Type: application/json');

$db = getDB();

// 1. Check if there are API keys
$keys = $db->query("SELECT clave, valor FROM configuracion WHERE grupo = 'integracion' AND clave LIKE 'api_key_%'")->fetchAll(PDO::FETCH_ASSOC);

// 2. Check webhook route works
$webhookUrl = "https://ana.evolucionamos.com/api/v1/integracion/webhook/ticket";

// 3. Check IA config
$groqKey = $db->query("SELECT valor FROM configuracion WHERE clave = 'groq_api_key'")->fetchColumn();
$iaEnabled = $db->query("SELECT valor FROM configuracion WHERE clave = 'ia_clasificacion_enabled'")->fetchColumn();

// 4. Check N8N or external integrations
$n8nUrl = $db->query("SELECT valor FROM configuracion WHERE clave = 'n8n_webhook_url'")->fetchColumn();

echo json_encode([
    'api_keys_count' => count($keys),
    'api_keys' => array_map(function($k) {
        $data = json_decode($k['valor'], true);
        return ['id' => $k['clave'], 'nombre' => $data['nombre'] ?? '?', 'creado' => $data['creado'] ?? '?'];
    }, $keys),
    'webhook_url' => $webhookUrl,
    'groq_api_key_configured' => !empty($groqKey) && $groqKey !== '',
    'ia_clasificacion_enabled' => $iaEnabled == '1',
    'n8n_configured' => !empty($n8nUrl),
    'available_features' => [
        'webhook_crear_ticket' => true,
        'webhook_stats' => true,
        'ia_clasificacion' => !empty($groqKey),
        'api_key_auth' => count($keys) > 0,
    ]
], JSON_PRETTY_PRINT);
