Files
whatsapp/crear_datos_prueba.php
T
2026-01-12 11:06:43 -05:00

175 lines
7.7 KiB
PHP

<?php
/**
* 🧪 CREADOR DE DATOS DE PRUEBA
* Crea usuarios y conversaciones de muestra para probar el sistema
*/
// Headers para mostrar errores
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo "<!DOCTYPE html><html><head><meta charset='UTF-8'>";
echo "<title>🧪 Datos de Prueba</title>";
echo "<style>body{font-family:monospace;margin:20px;background:#000;color:#00ff00}";
echo ".ok{color:#00ff00}.error{color:#ff0040}.warning{color:#ffaa00}";
echo ".section{background:#111;padding:15px;margin:10px 0;border:1px solid #333}";
echo "</style></head><body>";
echo "<h1>🧪 CREADOR DE DATOS DE PRUEBA</h1>";
try {
require_once 'config/config.php';
$pdo = new PDO(
"mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
DB_USER,
DB_PASS,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
echo "<div class='ok'>✅ Conectado a la base de datos</div>";
// Verificar si ya hay datos
$stmt = $pdo->query("SELECT COUNT(*) as count FROM users");
$userCount = $stmt->fetch()['count'];
$stmt = $pdo->query("SELECT COUNT(*) as count FROM conversations");
$convCount = $stmt->fetch()['count'];
echo "<div class='section'>";
echo "<h2>📊 ESTADO ACTUAL</h2>";
echo "<div class='warning'>Usuarios existentes: $userCount</div>";
echo "<div class='warning'>Conversaciones existentes: $convCount</div>";
echo "</div>";
if ($_POST && isset($_POST['create_data'])) {
echo "<div class='section'>";
echo "<h2>🔨 CREANDO DATOS DE PRUEBA...</h2>";
// Datos de usuarios de muestra - PERSONALIZA AQUÍ
$sampleUsers = [
['phone' => '+573168950803', 'name' => 'Usuario Principal']
];
$userIds = [];
foreach ($sampleUsers as $user) {
// Verificar si el usuario ya existe
$stmt = $pdo->prepare("SELECT id FROM users WHERE phone_number = ?");
$stmt->execute([$user['phone']]);
$existingUser = $stmt->fetch();
if ($existingUser) {
$userIds[] = $existingUser['id'];
echo "<div class='warning'>⚠️ Usuario ya existe: {$user['name']} ({$user['phone']})</div>";
} else {
$stmt = $pdo->prepare("
INSERT INTO users (phone_number, name, status, created_at)
VALUES (?, ?, 'active', NOW())
");
$stmt->execute([$user['phone'], $user['name']]);
$userIds[] = $pdo->lastInsertId();
echo "<div class='ok'>✅ Usuario creado: {$user['name']} ({$user['phone']})</div>";
}
}
// Crear conversaciones de muestra
$sampleMessages = [
['text' => 'Hola, necesito información sobre sus servicios', 'direction' => 'incoming'],
['text' => '¡Hola! Claro, te ayudo con gusto. ¿Qué tipo de servicio te interesa?', 'direction' => 'outgoing'],
['text' => 'Estoy buscando precios de desarrollo web', 'direction' => 'incoming'],
['text' => 'Perfecto, tenemos varios paquetes disponibles. Te envío la información.', 'direction' => 'outgoing'],
['text' => 'Gracias, muy amables', 'direction' => 'incoming'],
['text' => 'Buenos días, ¿están disponibles?', 'direction' => 'incoming'],
['text' => '¡Buenos días! Sí, estamos aquí para ayudarte. ¿En qué podemos asistirte?', 'direction' => 'outgoing'],
['text' => 'Quería hacer una consulta sobre horarios', 'direction' => 'incoming'],
['text' => 'Hola! Me pueden ayudar con un problema técnico?', 'direction' => 'incoming'],
['text' => 'Por supuesto! Cuéntanos qué problema tienes', 'direction' => 'outgoing']
];
$messagesCreated = 0;
foreach ($userIds as $index => $userId) {
// Crear 2-3 mensajes por usuario
$messageCount = rand(2, 4);
for ($i = 0; $i < $messageCount; $i++) {
$messageIndex = ($index * $messageCount + $i) % count($sampleMessages);
$message = $sampleMessages[$messageIndex];
$messageData = [
'user_id' => $userId,
'content' => $message['text'],
'direction' => $message['direction'],
'message_type' => 'text',
'status' => $message['direction'] === 'outgoing' ? 'delivered' : 'sent',
'created_at' => date('Y-m-d H:i:s', strtotime("-" . rand(1, 72) . " hours"))
];
// Intentar insertar en conversations
try {
$stmt = $pdo->prepare("
INSERT INTO conversations (user_id, content, direction, message_type, status, created_at)
VALUES (?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$messageData['user_id'],
$messageData['content'],
$messageData['direction'],
$messageData['message_type'],
$messageData['status'],
$messageData['created_at']
]);
$messagesCreated++;
} catch (Exception $e) {
// Si falla, intentar en messages
try {
$stmt = $pdo->prepare("
INSERT INTO messages (user_id, message_text, direction, message_type, status, created_at)
VALUES (?, ?, ?, ?, ?, ?)
");
$stmt->execute([
$messageData['user_id'],
$messageData['content'],
$messageData['direction'],
$messageData['message_type'],
$messageData['status'],
$messageData['created_at']
]);
$messagesCreated++;
} catch (Exception $e2) {
echo "<div class='error'>❌ Error creando mensaje: " . $e2->getMessage() . "</div>";
}
}
}
}
echo "<div class='ok'>✅ Usuarios creados: " . count($userIds) . "</div>";
echo "<div class='ok'>✅ Mensajes/conversaciones creados: $messagesCreated</div>";
echo "<div class='ok'>🎉 ¡Datos de prueba creados exitosamente!</div>";
echo "<br><div class='warning'><strong>SIGUIENTE PASO:</strong></div>";
echo "<div class='warning'>• Visita: <a href='conversations.php' style='color:#ffaa00'>conversations.php</a></div>";
echo "<div class='warning'>• O ve al panel: <a href='index.php' style='color:#ffaa00'>index.php</a></div>";
echo "</div>";
}
} catch (Exception $e) {
echo "<div class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</div>";
}
if (!$_POST) {
echo "<div class='section'>";
echo "<h2>⚠️ CREAR DATOS DE PRUEBA</h2>";
echo "<div class='warning'>Esto creará usuarios y conversaciones de muestra para probar el sistema</div>";
echo "<div class='warning'>Solo ejecuta esto si no tienes datos reales o quieres probar</div>";
echo "<form method='POST'>";
echo "<button type='submit' name='create_data' value='1' style='padding:10px 20px;background:#333;color:#fff;border:1px solid #555;cursor:pointer'>🧪 Crear Datos de Prueba</button>";
echo "</form>";
echo "</div>";
}
echo "</body></html>";
?>