<?php
/**
 * Script de corrección rápida para WhatsApp API
 * Fecha: 5 de enero de 2026
 */

require_once 'config/config.php';

header('Content-Type: application/json; charset=utf-8');

// Verificar autenticación si es POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAuthentication();
}

try {
    $method = $_SERVER['REQUEST_METHOD'];
    
    if ($method === 'GET') {
        // Obtener configuración actual y diagnóstico
        $db = Database::getInstance();
        
        $currentConfig = [];
        $configKeys = ['whatsapp_token', 'whatsapp_phone_number_id', 'whatsapp_api_url', 'webhook_verify_token'];
        
        foreach ($configKeys as $key) {
            $config = $db->fetch("SELECT config_value FROM system_config WHERE config_key = ?", [$key]);
            $currentConfig[$key] = $config['config_value'] ?? null;
        }
        
        // Si no hay configuración en BD, usar constantes
        if (empty($currentConfig['whatsapp_token'])) {
            $currentConfig = [
                'whatsapp_token' => WHATSAPP_TOKEN,
                'whatsapp_phone_number_id' => WHATSAPP_PHONE_NUMBER_ID,
                'whatsapp_api_url' => WHATSAPP_API_URL,
                'webhook_verify_token' => WEBHOOK_VERIFY_TOKEN
            ];
        }
        
        // Diagnóstico del problema
        $diagnosis = [
            'has_valid_token' => $currentConfig['whatsapp_token'] !== 'TU_TOKEN_DE_WHATSAPP_AQUI' && !empty($currentConfig['whatsapp_token']),
            'has_valid_phone_id' => $currentConfig['whatsapp_phone_number_id'] !== 'TU_PHONE_ID_AQUI' && !empty($currentConfig['whatsapp_phone_number_id']),
            'problematic_phone_id' => $currentConfig['whatsapp_phone_number_id'] === '858157464051987',
            'error_message' => 'Object with ID \'858157464051987\' does not exist, cannot be loaded due to missing permissions, or does not support this operation'
        ];
        
        echo json_encode([
            'success' => true,
            'current_config' => $currentConfig,
            'diagnosis' => $diagnosis
        ]);
        
    } elseif ($method === 'POST') {
        // Actualizar configuración
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            throw new Exception('Datos inválidos');
        }
        
        $db = Database::getInstance();
        
        // Validar datos requeridos
        $token = trim($input['whatsapp_token'] ?? '');
        $phoneId = trim($input['whatsapp_phone_number_id'] ?? '');
        $apiUrl = trim($input['whatsapp_api_url'] ?? WHATSAPP_API_URL);
        $webhookToken = trim($input['webhook_verify_token'] ?? WEBHOOK_VERIFY_TOKEN);
        
        if (empty($token)) {
            throw new Exception('Token de WhatsApp es obligatorio');
        }
        
        if (empty($phoneId)) {
            throw new Exception('Phone Number ID es obligatorio');
        }
        
        // Validar formato del token
        if (!preg_match('/^EAA[A-Za-z0-9_-]+$/', $token)) {
            throw new Exception('Formato de token inválido. Debe empezar con EAA');
        }
        
        // Validar formato del Phone Number ID
        if (!preg_match('/^\d{10,20}$/', $phoneId)) {
            throw new Exception('Phone Number ID debe ser numérico (10-20 dígitos)');
        }
        
        // Probar conexión antes de guardar
        $testResult = testConnectionWithCredentials($token, $phoneId, $apiUrl);
        if (!$testResult['success']) {
            throw new Exception('Error al probar conexión: ' . $testResult['message']);
        }
        
        // Guardar configuración
        $configs = [
            'whatsapp_token' => $token,
            'whatsapp_phone_number_id' => $phoneId,
            'whatsapp_api_url' => $apiUrl,
            'webhook_verify_token' => $webhookToken
        ];
        
        foreach ($configs as $key => $value) {
            $existing = $db->fetch("SELECT id FROM system_config WHERE config_key = ?", [$key]);
            
            if ($existing) {
                $db->query(
                    "UPDATE system_config SET config_value = ?, updated_at = NOW() WHERE config_key = ?",
                    [$value, $key]
                );
            } else {
                $db->query(
                    "INSERT INTO system_config (config_key, config_value, created_at, updated_at) VALUES (?, ?, NOW(), NOW())",
                    [$key, $value]
                );
            }
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Configuración actualizada y probada correctamente',
            'test_result' => $testResult
        ]);
        
    } elseif ($method === 'PUT') {
        // Solo probar conexión con configuración actual
        $currentToken = getConfigFromDB('whatsapp_token', WHATSAPP_TOKEN);
        $currentPhoneId = getConfigFromDB('whatsapp_phone_number_id', WHATSAPP_PHONE_NUMBER_ID);
        $currentApiUrl = getConfigFromDB('whatsapp_api_url', WHATSAPP_API_URL);
        
        $testResult = testConnectionWithCredentials($currentToken, $currentPhoneId, $currentApiUrl);
        
        echo json_encode([
            'success' => true,
            'test_result' => $testResult
        ]);
        
    } else {
        throw new Exception('Método no permitido');
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

function testConnectionWithCredentials($token, $phoneId, $apiUrl) {
    try {
        if (empty($token) || empty($phoneId)) {
            return ['success' => false, 'message' => 'Token o Phone ID vacío'];
        }
        
        // Probar acceso al Phone Number ID
        $ch = curl_init();
        $url = $apiUrl . $phoneId;
        
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json'
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_USERAGENT => 'WhatsApp-Bot-Diagnostic/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, 'message' => 'Error de conexión: ' . $curlError];
        }
        
        $decoded = json_decode($response, true);
        
        if ($httpCode === 200 && $decoded) {
            $displayName = $decoded['display_phone_number'] ?? 'N/A';
            $verifiedName = $decoded['verified_name'] ?? 'No verificado';
            
            return [
                'success' => true, 
                'message' => "Conexión exitosa. Número: $displayName ($verifiedName)",
                'phone_info' => $decoded
            ];
        } else {
            $errorMsg = 'Error desconocido';
            if ($decoded && isset($decoded['error'])) {
                $errorMsg = $decoded['error']['message'] ?? $errorMsg;
                $errorCode = $decoded['error']['code'] ?? 'N/A';
                $errorType = $decoded['error']['type'] ?? 'N/A';
                
                $errorMsg = "[$errorCode/$errorType] $errorMsg";
            }
            
            return [
                'success' => false, 
                'message' => $errorMsg,
                'http_code' => $httpCode,
                'raw_response' => $response
            ];
        }
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Excepción: ' . $e->getMessage()];
    }
}
?>