<?php
/**
 * Instalador Simplificado para Hosting Compartido
 * Version mínima y robusta para HestiaCP/cPanel
 * Desarrollado por U-Site.app
 * Fecha: 13 de noviembre de 2025
 */

// Configuración básica
error_reporting(E_ALL);
ini_set('display_errors', 1);

$step = $_GET['step'] ?? 'form';
$errors = [];
$success = [];

// Generar contraseña admin
function generatePassword($length = 12) {
    return bin2hex(random_bytes($length / 2));
}

$adminPassword = generatePassword(12);

if ($step === 'install' && $_POST) {
    $dbHost = trim($_POST['db_host'] ?? 'localhost');
    $dbPort = trim($_POST['db_port'] ?? '3306');
    $dbName = trim($_POST['db_name'] ?? '');
    $dbUser = trim($_POST['db_user'] ?? '');
    $dbPass = $_POST['db_pass'] ?? '';
    
    // Validar campos
    if (empty($dbName)) $errors[] = "Nombre de BD requerido";
    if (empty($dbUser)) $errors[] = "Usuario de BD requerido"; 
    if (empty($dbPass)) $errors[] = "Contraseña de BD requerida";
    
    if (empty($errors)) {
        try {
            // 1. Conectar a BD
            $dsn = "mysql:host={$dbHost};port={$dbPort};dbname={$dbName};charset=utf8mb4";
            $pdo = new PDO($dsn, $dbUser, $dbPass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            ]);
            $success[] = "✅ Conexión exitosa";
            
            // 2. Aplicar schema básico
            $basicSchema = "
                CREATE TABLE IF NOT EXISTS users (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    phone_number VARCHAR(20) UNIQUE NOT NULL,
                    name VARCHAR(100),
                    status ENUM('active', 'inactive') DEFAULT 'active',
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                );
                
                CREATE TABLE IF NOT EXISTS conversations (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT,
                    direction ENUM('incoming', 'outgoing') NOT NULL,
                    content TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (user_id) REFERENCES users(id)
                );
                
                CREATE TABLE IF NOT EXISTS system_config (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    config_key VARCHAR(100) UNIQUE NOT NULL,
                    config_value TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                );
                
                INSERT IGNORE INTO system_config (config_key, config_value) VALUES
                ('app_installed', '1'),
                ('install_date', NOW()),
                ('admin_user', 'admin');
            ";
            
            $statements = array_filter(explode(';', $basicSchema));
            foreach ($statements as $stmt) {
                if (trim($stmt)) {
                    $pdo->exec(trim($stmt));
                }
            }
            $success[] = "✅ Tablas creadas";
            
            // 3. Actualizar config.php
            $configFile = 'config/config.php';
            if (file_exists($configFile)) {
                $config = file_get_contents($configFile);
                
                $config = preg_replace("/define\('DB_HOST',\s*'[^']*'\);/", "define('DB_HOST', '$dbHost');", $config);
                $config = preg_replace("/define\('DB_PORT',\s*'[^']*'\);/", "define('DB_PORT', '$dbPort');", $config);
                $config = preg_replace("/define\('DB_NAME',\s*'[^']*'\);/", "define('DB_NAME', '$dbName');", $config);
                $config = preg_replace("/define\('DB_USER',\s*'[^']*'\);/", "define('DB_USER', '$dbUser');", $config);
                $config = preg_replace("/define\('DB_PASS',\s*'[^']*'\);/", "define('DB_PASS', '$dbPass');", $config);
                $config = preg_replace("/define\('ADMIN_PASSWORD',\s*'[^']*'\);/", "define('ADMIN_PASSWORD', '" . password_hash($adminPassword, PASSWORD_DEFAULT) . "');", $config);
                
                file_put_contents($configFile, $config);
                $success[] = "✅ Configuración actualizada";
            }
            
            // 4. Crear archivo de instalación completada
            file_put_contents('.installation_completed', date('Y-m-d H:i:s'));
            $success[] = "✅ Instalación completada";
            
            // 5. Crear credenciales
            $creds = "USUARIO ADMIN: admin\nCONTRASEÑA: $adminPassword\nFECHA: " . date('Y-m-d H:i:s');
            file_put_contents('CREDENCIALES.txt', $creds);
            $success[] = "✅ Credenciales guardadas en CREDENCIALES.txt";
            
            $step = 'completed';
            
        } catch (Exception $e) {
            $errors[] = "❌ 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>📦 Instalador Simplificado</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; }
        .card { background: rgba(255,255,255,0.95); border-radius: 15px; }
        .btn-primary { background: #667eea; border: none; }
    </style>
</head>
<body class="d-flex align-items-center">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="card shadow-lg p-4">
                    
                    <?php if ($step === 'form'): ?>
                    <div class="text-center mb-4">
                        <h2>📦 Instalador Simplificado</h2>
                        <p class="text-muted">Para hosting compartido (HestiaCP/cPanel)</p>
                    </div>
                    
                    <div class="alert alert-info">
                        <strong>Antes de continuar:</strong> Asegúrate de haber creado la base de datos y usuario en tu panel de control.
                    </div>
                    
                    <form method="POST" action="?step=install">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Host</label>
                                <input type="text" class="form-control" name="db_host" value="localhost" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Puerto</label>
                                <input type="text" class="form-control" name="db_port" value="3306" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Base de datos</label>
                                <input type="text" class="form-control" name="db_name" placeholder="mi_basedatos" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Usuario</label>
                                <input type="text" class="form-control" name="db_user" placeholder="mi_usuario" required>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Contraseña</label>
                                <input type="password" class="form-control" name="db_pass" required>
                            </div>
                        </div>
                        
                        <div class="text-center mt-4">
                            <div class="alert alert-success">
                                <strong>Contraseña de administrador:</strong><br>
                                <code><?= $adminPassword ?></code>
                            </div>
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-play"></i> Instalar Sistema
                            </button>
                        </div>
                    </form>
                    
                    <?php elseif ($step === 'install'): ?>
                    <div class="text-center mb-4">
                        <h2>⚙️ Instalando...</h2>
                    </div>
                    
                    <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger">
                        <h5>❌ Errores:</h5>
                        <?php foreach ($errors as $error): ?>
                        <div><?= htmlspecialchars($error) ?></div>
                        <?php endforeach; ?>
                        <hr>
                        <a href="?step=form" class="btn btn-outline-danger">Reintentar</a>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($success)): ?>
                    <div class="alert alert-success">
                        <h5>✅ Progreso:</h5>
                        <?php foreach ($success as $msg): ?>
                        <div><?= htmlspecialchars($msg) ?></div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php elseif ($step === 'completed'): ?>
                    <div class="text-center mb-4">
                        <h2 class="text-success">🎉 ¡Instalación Exitosa!</h2>
                    </div>
                    
                    <div class="row g-4">
                        <div class="col-md-6">
                            <h5>🔐 Credenciales de Acceso</h5>
                            <div class="alert alert-success">
                                <strong>Usuario:</strong> admin<br>
                                <strong>Contraseña:</strong> <code><?= $adminPassword ?></code>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h5>🚀 Próximos Pasos</h5>
                            <div class="d-grid gap-2">
                                <a href="index.php" class="btn btn-primary">Panel de Control</a>
                                <a href="test.php" class="btn btn-outline-success">Probar Sistema</a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="alert alert-warning mt-4">
                        <strong>Importante:</strong> Guarda las credenciales. El archivo CREDENCIALES.txt contiene toda la información.
                    </div>
                    <?php endif; ?>
                    
                </div>
            </div>
        </div>
    </div>
</body>
</html>