<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
header('Access-Control-Allow-Headers: Content-Type');

require_once __DIR__ . '/../config/config.php';

// Suprimir errores para obtener JSON limpio
error_reporting(E_ERROR | E_PARSE);

try {
    // Modo debug: desactivar autenticación si existe el parámetro debug
    $debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
    
    if (!$debugMode) {
        requireAuthentication();
    }
    
    // Obtener configuración de WhatsApp
    $whatsappConfig = getWhatsAppConfigFromDB();
    
    $diagnostic = [
        'success' => true,
        'timestamp' => date('Y-m-d H:i:s'),
        'config_status' => [],
        'template_status' => [],
        'api_status' => []
    ];
    
    // 1. Verificar configuración básica
    $diagnostic['config_status'] = [
        'phone_number_id' => !empty($whatsappConfig['phone_number_id']),
        'webhook_verify_token' => !empty($whatsappConfig['webhook_verify_token']),
        'whatsapp_api_url' => !empty($whatsappConfig['whatsapp_api_url']),
        'whatsapp_token' => !empty($whatsappConfig['whatsapp_token'])
    ];
    
    $diagnostic['config_status']['complete'] = array_reduce($diagnostic['config_status'], function($carry, $item) {
        return $carry && $item;
    }, true);
    
    // 2. Verificar plantillas en base de datos
    $db = Database::getInstance();
    $stmt = $db->query("SELECT status, COUNT(*) as count FROM message_templates GROUP BY status");
    $templateCounts = $stmt->fetchAll();
    
    $diagnostic['template_status'] = [
        'total' => 0,
        'approved' => 0,
        'pending' => 0,
        'rejected' => 0
    ];
    
    foreach ($templateCounts as $count) {
        $status = $count['status'] ?: 'pending';
        $diagnostic['template_status'][$status] = (int)$count['count'];
        $diagnostic['template_status']['total'] += (int)$count['count'];
    }
    
    // 3. Test básico de API (solo si hay configuración completa)
    if ($diagnostic['config_status']['complete']) {
        $apiUrl = "https://graph.facebook.com/v22.0/{$whatsappConfig['phone_number_id']}";
        $headers = [
            'Authorization: Bearer ' . $whatsappConfig['whatsapp_token'],
            'Content-Type: application/json'
        ];
        
        // Crear contexto para la solicitud HTTP
        $context = stream_context_create([
            'http' => [
                'method' => 'GET',
                'header' => implode("\r\n", $headers),
                'timeout' => 10
            ]
        ]);
        
        $response = @file_get_contents($apiUrl, false, $context);
        
        if ($response !== false) {
            $apiData = json_decode($response, true);
            $diagnostic['api_status'] = [
                'reachable' => true,
                'phone_number' => $apiData['display_phone_number'] ?? 'N/A',
                'verified_name' => $apiData['verified_name'] ?? 'N/A',
                'quality_rating' => $apiData['quality_rating'] ?? 'N/A'
            ];
        } else {
            $diagnostic['api_status'] = [
                'reachable' => false,
                #'error' => 'No se pudo conectar con la API de WhatsApp',
                'error' => error_get_last()

            ];
        }
    } else {
        $diagnostic['api_status'] = [
            'reachable' => false,
            'error' => 'Configuración incompleta'
        ];
    }
    
    // 4. Recomendaciones
    $diagnostic['recommendations'] = [];
    
    if (!$diagnostic['config_status']['complete']) {
        $diagnostic['recommendations'][] = 'Completa la configuración de WhatsApp en la pestaña Configuración';
    }
    
    if ($diagnostic['template_status']['approved'] === 0) {
        $diagnostic['recommendations'][] = 'Necesitas plantillas aprobadas para enviar mensajes';
        $diagnostic['recommendations'][] = 'Crea plantillas en WhatsApp Business Manager y espera su aprobación';
    }
    
    if (!$diagnostic['api_status']['reachable']) {
        $diagnostic['recommendations'][] = 'Verifica que el token de acceso sea válido';
        $diagnostic['recommendations'][] = 'Confirma que el Phone Number ID sea correcto';
    }
    
    if (empty($diagnostic['recommendations'])) {
        $diagnostic['recommendations'][] = 'Todo parece estar configurado correctamente';
    }
    
    // Agregar compatibilidad con la estructura esperada en index.php
    $configComplete = $diagnostic['config_status']['complete'];
    $completionPercentage = 0;
    $configFields = ['phone_number_id', 'whatsapp_token', 'webhook_verify_token', 'whatsapp_api_url'];
    $completedFields = 0;
    
    foreach ($configFields as $field) {
        if (isset($diagnostic['config_status'][$field]) && $diagnostic['config_status'][$field]) {
            $completedFields++;
        }
    }
    $completionPercentage = round(($completedFields / count($configFields)) * 100);
    
    // Estructura adicional para compatibilidad
    $diagnostic['config'] = [
        'status' => $configComplete ? 'complete' : 'incomplete',
        'message' => $configComplete ? 'Configuración completa' : 'Configuración incompleta',
        'completion' => $completionPercentage
    ];
    
    $diagnostic['templates'] = [
        'approved' => $diagnostic['template_status']['approved'],
        'pending' => $diagnostic['template_status']['pending'],
        'rejected' => $diagnostic['template_status']['rejected'],
        'total' => $diagnostic['template_status']['total'],
        'message' => $diagnostic['template_status']['approved'] > 0 
            ? 'Plantillas configuradas correctamente' 
            : ($diagnostic['template_status']['total'] > 0 
                ? 'Tienes plantillas pendientes de aprobación' 
                : 'No hay plantillas configuradas')
    ];
    
    // Estructura API para compatibilidad
    $diagnostic['api'] = [
        'status' => $diagnostic['api_status']['reachable'] ? 'ready' : 'error',
        'message' => $diagnostic['api_status']['reachable'] 
            ? 'Conexión API establecida correctamente' 
            : ($diagnostic['api_status']['error'] ?? 'No conectado')
    ];
    
    echo json_encode($diagnostic, JSON_PRETTY_PRINT);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error en diagnóstico: ' . $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
}
?>