<?php
/**
 * Herramienta para encontrar el Phone Number ID correcto
 * Fecha: 5 de enero de 2026
 */

require_once 'config/config.php';

if (!isUserLoggedIn()) {
    header('Location: login.php');
    exit;
}

$result = null;
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'find_numbers') {
        $token = $_POST['token'] ?? getConfigFromDB('whatsapp_token', WHATSAPP_TOKEN);
        
        if (empty($token) || $token === 'TU_TOKEN_DE_WHATSAPP_AQUI') {
            $error = 'Token de WhatsApp requerido';
        } else {
            $result = findAvailablePhoneNumbers($token);
        }
    } elseif ($action === 'update_config') {
        $newPhoneId = $_POST['phone_id'] ?? '';
        
        if (empty($newPhoneId)) {
            $error = 'Phone Number ID requerido';
        } else {
            try {
                $db = Database::getInstance();
                
                // Actualizar en base de datos
                $existing = $db->fetch("SELECT id FROM system_config WHERE config_key = 'whatsapp_phone_number_id'");
                
                if ($existing) {
                    $db->query(
                        "UPDATE system_config SET config_value = ?, updated_at = NOW() WHERE config_key = 'whatsapp_phone_number_id'",
                        [$newPhoneId]
                    );
                } else {
                    $db->query(
                        "INSERT INTO system_config (config_key, config_value, created_at, updated_at) VALUES ('whatsapp_phone_number_id', ?, NOW(), NOW())",
                        [$newPhoneId]
                    );
                }
                
                $result = ['success' => true, 'message' => 'Phone Number ID actualizado correctamente'];
                
                // Probar nueva configuración
                $testResult = testNewConfig($newPhoneId);
                $result['test'] = $testResult;
                
            } catch (Exception $e) {
                $error = 'Error actualizando configuración: ' . $e->getMessage();
            }
        }
    }
}

function findAvailablePhoneNumbers($token) {
    try {
        // Método 1: Buscar a través de Business Account
        $ch = curl_init();
        $url = 'https://graph.facebook.com/v18.0/me/businesses';
        
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $token,
                'Content-Type: application/json'
            ],
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => true
        ]);
        
        $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) {
            // Método 2: Intentar obtener info de la app directamente
            return findPhoneNumbersFromApp($token);
        }
        
        $phoneNumbers = [];
        
        if (isset($decoded['data']) && is_array($decoded['data'])) {
            foreach ($decoded['data'] as $business) {
                $businessId = $business['id'];
                $phoneNumbersData = getPhoneNumbersFromBusiness($token, $businessId);
                
                if ($phoneNumbersData['success']) {
                    $phoneNumbers = array_merge($phoneNumbers, $phoneNumbersData['numbers']);
                }
            }
        }
        
        return [
            'success' => true,
            'numbers' => $phoneNumbers,
            'method' => 'business_account'
        ];
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function findPhoneNumbersFromApp($token) {
    try {
        // Intentar con diferentes endpoints
        $endpoints = [
            'https://graph.facebook.com/v18.0/me',
            'https://graph.facebook.com/v18.0/me/accounts',
            'https://graph.facebook.com/v18.0/me/applications'
        ];
        
        foreach ($endpoints as $endpoint) {
            $ch = curl_init();
            
            curl_setopt_array($ch, [
                CURLOPT_URL => $endpoint,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_HTTPHEADER => [
                    'Authorization: Bearer ' . $token,
                    'Content-Type: application/json'
                ],
                CURLOPT_TIMEOUT => 10,
                CURLOPT_SSL_VERIFYPEER => true
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200) {
                $decoded = json_decode($response, true);
                // Aquí podrías analizar la respuesta para encontrar números
            }
        }
        
        return [
            'success' => false,
            'error' => 'No se pudieron encontrar números automáticamente. Debe obtenerlos manualmente de Facebook for Developers.',
            'manual_steps' => [
                '1. Ve a https://developers.facebook.com/apps',
                '2. Selecciona tu aplicación WhatsApp Business',
                '3. Ve a Productos > WhatsApp > Configuración',
                '4. En la sección "Números de teléfono", copia el Phone Number ID',
                '5. Pega el ID en el formulario de abajo'
            ]
        ];
        
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function getPhoneNumbersFromBusiness($token, $businessId) {
    try {
        $ch = curl_init();
        $url = "https://graph.facebook.com/v18.0/{$businessId}/phone_numbers";
        
        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
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode === 200) {
            $decoded = json_decode($response, true);
            
            if (isset($decoded['data'])) {
                return [
                    'success' => true,
                    'numbers' => $decoded['data']
                ];
            }
        }
        
        return ['success' => false, 'numbers' => []];
        
    } catch (Exception $e) {
        return ['success' => false, 'numbers' => []];
    }
}

function testNewConfig($phoneId) {
    try {
        $token = getConfigFromDB('whatsapp_token', WHATSAPP_TOKEN);
        
        $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
        ]);
        
        $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: ' . $curlError];
        }
        
        $decoded = json_decode($response, true);
        
        if ($httpCode === 200) {
            $displayName = $decoded['display_phone_number'] ?? 'N/A';
            return ['success' => true, 'message' => "✅ Configuración válida. Número: $displayName"];
        } else {
            $errorMsg = $decoded['error']['message'] ?? 'Error desconocido';
            return ['success' => false, 'message' => "❌ Error: $errorMsg"];
        }
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buscar Phone Number ID Correcto</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .whatsapp-green { background: linear-gradient(135deg, #25D366, #128C7E); }
        .phone-card { border: 2px solid #ddd; transition: all 0.3s; }
        .phone-card:hover { border-color: #25D366; box-shadow: 0 4px 15px rgba(37,211,102,0.2); }
        .phone-card.selected { border-color: #25D366; background: #f0fff4; }
    </style>
</head>
<body class="bg-light">
    <div class="container my-4">
        
        <!-- Header -->
        <div class="card whatsapp-green text-white mb-4">
            <div class="card-body text-center">
                <h1><i class="fab fa-whatsapp me-2"></i>Buscar Phone Number ID Correcto</h1>
                <p class="mb-0">Encuentra y configura el Phone Number ID válido para tu cuenta</p>
            </div>
        </div>

        <!-- Problema Detectado -->
        <div class="alert alert-danger">
            <h5><i class="fas fa-exclamation-triangle me-2"></i>Problema Detectado</h5>
            <p class="mb-1"><strong>Phone Number ID Actual:</strong> <code>858157464051987</code></p>
            <p class="mb-0"><strong>Error:</strong> Este ID no existe, no tienes permisos, o no soporta la operación solicitada.</p>
        </div>

        <?php if ($error): ?>
        <div class="alert alert-danger">
            <i class="fas fa-times-circle me-2"></i><?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <?php if ($result && isset($result['success']) && $result['success']): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle me-2"></i><?= htmlspecialchars($result['message'] ?? 'Operación exitosa') ?>
            <?php if (isset($result['test'])): ?>
                <br><strong>Prueba:</strong> <?= htmlspecialchars($result['test']['message']) ?>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="row">
            <!-- Paso 1: Buscar números automáticamente -->
            <div class="col-md-6">
                <div class="card mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5><i class="fas fa-search me-2"></i>Paso 1: Buscar Automáticamente</h5>
                    </div>
                    <div class="card-body">
                        <p>Intentar encontrar números de WhatsApp asociados a tu token:</p>
                        
                        <form method="POST">
                            <input type="hidden" name="action" value="find_numbers">
                            
                            <div class="mb-3">
                                <label class="form-label">Token de WhatsApp</label>
                                <input type="text" class="form-control" name="token" 
                                       value="<?= substr(getConfigFromDB('whatsapp_token', WHATSAPP_TOKEN), 0, 30) ?>..." readonly>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search me-2"></i>Buscar Números
                            </button>
                        </form>

                        <?php if ($result && isset($result['numbers'])): ?>
                        <hr>
                        <h6>Números Encontrados:</h6>
                        <?php if (empty($result['numbers'])): ?>
                            <div class="alert alert-warning">
                                <p>No se encontraron números automáticamente.</p>
                                <?php if (isset($result['manual_steps'])): ?>
                                    <strong>Pasos manuales:</strong>
                                    <ol>
                                        <?php foreach ($result['manual_steps'] as $step): ?>
                                            <li><?= htmlspecialchars($step) ?></li>
                                        <?php endforeach; ?>
                                    </ol>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <?php foreach ($result['numbers'] as $number): ?>
                            <div class="phone-card card mb-2 p-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <strong><?= htmlspecialchars($number['display_phone_number'] ?? $number['id']) ?></strong><br>
                                        <small class="text-muted">ID: <?= htmlspecialchars($number['id']) ?></small>
                                    </div>
                                    <button class="btn btn-success btn-sm" 
                                            onclick="selectPhoneNumber('<?= htmlspecialchars($number['id']) ?>')">
                                        <i class="fas fa-check me-1"></i>Usar Este
                                    </button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Paso 2: Configuración manual -->
            <div class="col-md-6">
                <div class="card mb-4">
                    <div class="card-header bg-success text-white">
                        <h5><i class="fas fa-edit me-2"></i>Paso 2: Configuración Manual</h5>
                    </div>
                    <div class="card-body">
                        <p>Si conoces el Phone Number ID correcto, ingrésalo aquí:</p>
                        
                        <form method="POST">
                            <input type="hidden" name="action" value="update_config">
                            
                            <div class="mb-3">
                                <label class="form-label">Nuevo Phone Number ID</label>
                                <input type="text" class="form-control" name="phone_id" id="phone_id"
                                       placeholder="123456789012345" required>
                                <small class="text-muted">Debe ser numérico, 10-20 dígitos</small>
                            </div>
                            
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-save me-2"></i>Actualizar y Probar
                            </button>
                        </form>
                        
                        <hr>
                        
                        <h6>¿Cómo obtener el Phone Number ID?</h6>
                        <ol class="small">
                            <li>Ve a <a href="https://developers.facebook.com/apps" target="_blank">Facebook for Developers</a></li>
                            <li>Selecciona tu aplicación WhatsApp Business</li>
                            <li>Ve a <strong>Productos → WhatsApp → Configuración</strong></li>
                            <li>En "Números de teléfono", encuentra tu número</li>
                            <li>Copia el <strong>Phone Number ID</strong></li>
                            <li>Pégalo en el campo de arriba</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Enlaces útiles -->
        <div class="text-center">
            <a href="index.php" class="btn btn-outline-primary me-2">
                <i class="fas fa-arrow-left me-2"></i>Volver al Panel
            </a>
            <a href="diagnostico_whatsapp_avanzado.php" class="btn btn-outline-info me-2">
                <i class="fas fa-stethoscope me-2"></i>Diagnóstico Completo
            </a>
            <a href="solucionador_whatsapp.php" class="btn btn-outline-warning">
                <i class="fas fa-tools me-2"></i>Herramientas de Solución
            </a>
        </div>
    </div>

    <script>
        function selectPhoneNumber(phoneId) {
            document.getElementById('phone_id').value = phoneId;
            
            // Highlight selected
            document.querySelectorAll('.phone-card').forEach(card => {
                card.classList.remove('selected');
            });
            event.target.closest('.phone-card').classList.add('selected');
            
            // Scroll to form
            document.getElementById('phone_id').scrollIntoView({behavior: 'smooth'});
            document.getElementById('phone_id').focus();
        }
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>