<?php
/**
 * Verificador automático de configuración WhatsApp
 * Fecha: 5 de enero de 2026
 */

require_once 'config/config.php';

function verifyAndFixWhatsAppConfig() {
    $issues = [];
    $fixes = [];
    
    try {
        $db = Database::getInstance();
        
        // Verificar configuración actual
        $currentToken = getConfigFromDB('whatsapp_token', WHATSAPP_TOKEN);
        $currentPhoneId = getConfigFromDB('whatsapp_phone_number_id', WHATSAPP_PHONE_NUMBER_ID);
        
        // Issue 1: Token por defecto
        if ($currentToken === 'TU_TOKEN_DE_WHATSAPP_AQUI' || empty($currentToken)) {
            $issues[] = "Token de WhatsApp no configurado";
        }
        
        // Issue 2: Phone ID por defecto
        if ($currentPhoneId === 'TU_PHONE_ID_AQUI' || empty($currentPhoneId)) {
            $issues[] = "Phone Number ID no configurado";
        }
        
        // Issue 3: Phone ID problemático específico
        if ($currentPhoneId === '858157464051987') {
            $issues[] = "Phone Number ID problemático detectado: $currentPhoneId";
            $fixes[] = "Este ID específico está generando errores. Necesita ser reemplazado por el correcto.";
        }
        
        // Issue 4: Probar conectividad si hay configuración
        if ($currentToken !== 'TU_TOKEN_DE_WHATSAPP_AQUI' && $currentPhoneId !== 'TU_PHONE_ID_AQUI' && !empty($currentToken) && !empty($currentPhoneId)) {
            $testResult = testWhatsAppAPI($currentToken, $currentPhoneId);
            if (!$testResult['success']) {
                $issues[] = "Fallo en prueba de conectividad: " . $testResult['error'];
            } else {
                $fixes[] = "✅ Configuración verificada correctamente: " . $testResult['message'];
            }
        }
        
        return [
            'success' => count($issues) === 0,
            'issues' => $issues,
            'fixes' => $fixes,
            'current_config' => [
                'token_configured' => $currentToken !== 'TU_TOKEN_DE_WHATSAPP_AQUI' && !empty($currentToken),
                'phone_id_configured' => $currentPhoneId !== 'TU_PHONE_ID_AQUI' && !empty($currentPhoneId),
                'phone_id_value' => $currentPhoneId
            ]
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'issues' => ["Error al verificar configuración: " . $e->getMessage()],
            'fixes' => [],
            'current_config' => []
        ];
    }
}

function testWhatsAppAPI($token, $phoneId) {
    try {
        $ch = curl_init();
        $url = WHATSAPP_API_URL . $phoneId;
        
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json'
            ],
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_USERAGENT => 'WhatsApp-Bot-Verifier/1.0'
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            return ['success' => false, 'error' => 'Error cURL: ' . $curlError];
        }
        
        $decoded = json_decode($response, true);
        
        if ($httpCode === 200 && $decoded) {
            $displayName = $decoded['display_phone_number'] ?? $phoneId;
            return ['success' => true, 'message' => "Número verificado: $displayName"];
        } else {
            $errorMsg = 'Error HTTP ' . $httpCode;
            if ($decoded && isset($decoded['error'])) {
                $errorMsg = $decoded['error']['message'] ?? $errorMsg;
            }
            return ['success' => false, 'error' => $errorMsg];
        }
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

// Si se llama directamente, mostrar diagnóstico
if (basename($_SERVER['PHP_SELF']) === basename(__FILE__)) {
    header('Content-Type: application/json; charset=utf-8');
    $result = verifyAndFixWhatsAppConfig();
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
?>