";
echo "
🗄️ Instalador BD";
echo "";
echo "🗄️ INSTALADOR DE BASE DE DATOS
";
// Cargar configuración
try {
require_once 'config/config.php';
} catch (Exception $e) {
echo "❌ Error cargando configuración: " . htmlspecialchars($e->getMessage()) . "
";
exit;
}
// Verificar que existe el archivo schema.sql
if (!file_exists('database/schema.sql')) {
echo "❌ CRÍTICO: database/schema.sql no encontrado
";
exit;
}
// Conectar a la base de datos
try {
$dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET;
$pdo = new PDO($dsn, DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
echo "✅ Conectado a la base de datos
";
} catch (PDOException $e) {
echo "❌ Error de conexión: " . htmlspecialchars($e->getMessage()) . "
";
exit;
}
// Leer archivo SQL
$sql_content = file_get_contents('database/schema.sql');
if (!$sql_content) {
echo "❌ No se pudo leer database/schema.sql
";
exit;
}
echo "";
echo "
📋 EJECUTANDO SCHEMA SQL...
";
// Separar comandos SQL
$commands = array_filter(
array_map('trim', explode(';', $sql_content)),
function($cmd) {
return !empty($cmd) && !preg_match('/^\s*--/', $cmd);
}
);
$success_count = 0;
$error_count = 0;
foreach ($commands as $i => $command) {
if (empty(trim($command))) continue;
// Mostrar progreso cada 5 comandos
if ($i % 5 === 0) {
echo "
Procesando comando " . ($i + 1) . "/" . count($commands) . "...
";
flush();
}
try {
$pdo->exec($command);
$success_count++;
// Solo mostrar detalles de CREATE TABLE y INSERT importantes
if (preg_match('/CREATE TABLE (\w+)/', $command, $matches)) {
echo "
✅ Tabla '{$matches[1]}' creada
";
} elseif (preg_match('/INSERT INTO (\w+)/', $command, $matches) && $i < 10) {
echo "
✅ Datos insertados en '{$matches[1]}'
";
}
} catch (PDOException $e) {
$error_count++;
// Si es error de tabla existente, es OK
if (strpos($e->getMessage(), 'already exists') !== false) {
if (preg_match('/CREATE TABLE (\w+)/', $command, $matches)) {
echo "
⚠️ Tabla '{$matches[1]}' ya existe
";
}
} else {
echo "
❌ Error en comando " . ($i + 1) . ": " . htmlspecialchars($e->getMessage()) . "
";
if (strlen($command) < 200) {
echo "
" . htmlspecialchars($command) . "
";
}
}
}
}
echo "
📊 Comandos exitosos: $success_count
";
echo "
📊 Errores: $error_count
";
echo "
";
// Ahora crear tablas adicionales que faltan
echo "";
echo "
🔧 CREANDO TABLAS FALTANTES...
";
// Crear tabla 'conversations' como alias de conversations
try {
$pdo->exec("
CREATE TABLE IF NOT EXISTS conversations (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
phone_number VARCHAR(20) NOT NULL,
message_text TEXT,
direction ENUM('incoming', 'outgoing') NOT NULL,
message_type ENUM('text', 'image', 'audio', 'video', 'document', 'template') DEFAULT 'text',
status ENUM('sent', 'delivered', 'read', 'failed') DEFAULT 'sent',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_phone (phone_number),
INDEX idx_direction (direction),
INDEX idx_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
echo "
✅ Tabla 'conversations' creada
";
} catch (PDOException $e) {
if (strpos($e->getMessage(), 'already exists') === false) {
echo "
❌ Error creando tabla conversations: " . htmlspecialchars($e->getMessage()) . "
";
} else {
echo "
⚠️ Tabla 'conversations' ya existe
";
}
}
// Crear tabla 'system_config' como alias de system_config
try {
$pdo->exec("
CREATE TABLE IF NOT EXISTS system_config (
id INT AUTO_INCREMENT PRIMARY KEY,
setting_key VARCHAR(100) UNIQUE NOT NULL,
setting_value TEXT,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
echo "
✅ Tabla 'system_config' creada
";
} catch (PDOException $e) {
if (strpos($e->getMessage(), 'already exists') === false) {
echo "
❌ Error creando tabla system_config: " . htmlspecialchars($e->getMessage()) . "
";
} else {
echo "
⚠️ Tabla 'system_config' ya existe
";
}
}
echo "
";
// Copiar datos de system_config a system_config si no existen
echo "";
echo "
📊 SINCRONIZANDO CONFIGURACIÓN...
";
try {
// Copiar datos de system_config a system_config
$pdo->exec("
INSERT IGNORE INTO system_config (setting_key, setting_value, description, created_at)
SELECT config_key, config_value, description, created_at
FROM system_config
WHERE config_key IS NOT NULL
");
$affected = $pdo->lastInsertId();
echo "
✅ Configuraciones sincronizadas
";
} catch (PDOException $e) {
echo "
⚠️ Error sincronizando: " . htmlspecialchars($e->getMessage()) . "
";
}
// Verificar que el SECRET_KEY esté definido
try {
if (!defined('SECRET_KEY') || empty(SECRET_KEY)) {
$secret_key = bin2hex(random_bytes(32));
$pdo->prepare("INSERT INTO system_config (setting_key, setting_value, description) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)")
->execute(['SECRET_KEY', $secret_key, 'Clave secreta para encriptación']);
echo "
✅ SECRET_KEY generada y guardada
";
echo "
🔑 IMPORTANTE: Agrega esta línea a config/config.php:
";
echo "
define('SECRET_KEY', '$secret_key');";
}
} catch (Exception $e) {
echo "
❌ Error generando SECRET_KEY: " . htmlspecialchars($e->getMessage()) . "
";
}
echo "
";
// Verificación final
echo "";
echo "
✅ VERIFICACIÓN FINAL
";
$required_tables = ['conversations', 'conversations', 'system_config', 'message_templates', 'users', 'menus'];
$missing_tables = [];
foreach ($required_tables as $table) {
try {
$stmt = $pdo->query("SHOW TABLES LIKE '$table'");
if ($stmt->rowCount() > 0) {
// Contar registros
$count_stmt = $pdo->query("SELECT COUNT(*) as count FROM $table");
$count = $count_stmt->fetch()['count'];
echo "
✅ Tabla '$table' existe ($count registros)
";
} else {
$missing_tables[] = $table;
}
} catch (Exception $e) {
echo "
❌ Error verificando tabla '$table': " . htmlspecialchars($e->getMessage()) . "
";
$missing_tables[] = $table;
}
}
if (empty($missing_tables)) {
echo "
🎉 ¡TODAS LAS TABLAS ESTÁN LISTAS!
";
echo "
✅ Base de datos completamente configurada
";
echo "
✅ Sistema debería funcionar ahora
";
echo "
PRÓXIMO PASO:
";
echo "
";
echo "
";
} else {
echo "
❌ Faltan tablas: " . implode(', ', $missing_tables) . "
";
echo "
❌ Sistema NO puede funcionar
";
}
echo "
";
echo "