<?php
/**
 * Configurador automático para hosting compartido
 * Ejecuta este script una sola vez después de subir archivos
 */

$step = $_GET['step'] ?? 'welcome';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🚀 Configurador de Servidor - WhatsApp Bot</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.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: linear-gradient(135deg, #25d366 0%, #075e54 100%); min-height: 100vh; }
        .config-card { background: rgba(255,255,255,0.95); border-radius: 20px; backdrop-filter: blur(10px); }
        .btn-whatsapp { background: linear-gradient(135deg, #25d366, #075e54); border: none; }
        .step-active { background: #25d366; color: white; }
        .step-pending { background: #e9ecef; color: #6c757d; }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="config-card p-5">
                    
                    <?php if ($step === 'welcome'): ?>
                    <!-- Pantalla de Bienvenida -->
                    <div class="text-center mb-4">
                        <i class="fab fa-whatsapp text-success" style="font-size: 4rem;"></i>
                        <h1 class="mt-3">Configurador de Servidor</h1>
                        <p class="text-muted">Configura tu WhatsApp Bot Manager en el servidor</p>
                    </div>

                    <div class="row g-3 mb-4">
                        <div class="col-md-4">
                            <div class="text-center p-3 rounded step-pending">
                                <i class="fas fa-server fa-2x mb-2"></i>
                                <h6>1. Verificar Servidor</h6>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center p-3 rounded step-pending">
                                <i class="fas fa-database fa-2x mb-2"></i>
                                <h6>2. Configurar BD</h6>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="text-center p-3 rounded step-pending">
                                <i class="fas fa-cog fa-2x mb-2"></i>
                                <h6>3. WhatsApp API</h6>
                            </div>
                        </div>
                    </div>

                    <div class="alert alert-info">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>Antes de comenzar, asegúrate de tener:</strong>
                        <ul class="mb-0 mt-2">
                            <li>Credenciales de base de datos MySQL</li>
                            <li>Token de WhatsApp Business API</li>
                            <li>Phone Number ID de WhatsApp</li>
                            <li>Dominio con SSL/HTTPS activo</li>
                        </ul>
                    </div>

                    <div class="text-center">
                        <a href="?step=check" class="btn btn-whatsapp btn-lg text-white">
                            <i class="fas fa-play me-2"></i>Comenzar Configuración
                        </a>
                    </div>

                    <?php elseif ($step === 'check'): ?>
                    <!-- Verificación del Servidor -->
                    <h2 class="mb-4">
                        <i class="fas fa-server me-2 text-success"></i>Verificación del Servidor
                    </h2>

                    <?php
                    $checks = [
                        'PHP Version' => version_compare(PHP_VERSION, '8.0.0', '>='),
                        'PDO Extension' => extension_loaded('pdo'),
                        'PDO MySQL' => extension_loaded('pdo_mysql'),
                        'cURL Extension' => extension_loaded('curl'),
                        'JSON Extension' => extension_loaded('json'),
                        'mbstring Extension' => extension_loaded('mbstring'),
                        'OpenSSL Extension' => extension_loaded('openssl'),
                        'Write Permissions' => is_writable('.'),
                        'HTTPS' => (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
                    ];
                    
                    $allPassed = true;
                    foreach ($checks as $check => $status) {
                        if (!$status) $allPassed = false;
                    }
                    ?>

                    <div class="row g-3">
                        <?php foreach ($checks as $check => $status): ?>
                        <div class="col-md-6">
                            <div class="d-flex align-items-center p-3 border rounded">
                                <i class="fas fa-<?= $status ? 'check-circle text-success' : 'times-circle text-danger' ?> me-3"></i>
                                <div>
                                    <strong><?= $check ?></strong><br>
                                    <small class="text-muted">
                                        <?= $status ? 'OK' : 'Falta' ?>
                                        <?php if ($check === 'PHP Version'): ?>
                                            (<?= PHP_VERSION ?>)
                                        <?php endif; ?>
                                    </small>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="mt-4">
                        <?php if ($allPassed): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i>
                            ¡Excelente! Tu servidor cumple todos los requisitos.
                        </div>
                        <div class="text-center">
                            <a href="?step=database" class="btn btn-whatsapp btn-lg text-white">
                                <i class="fas fa-arrow-right me-2"></i>Configurar Base de Datos
                            </a>
                        </div>
                        <?php else: ?>
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Algunos requisitos no se cumplen. Contacta a tu proveedor de hosting.
                        </div>
                        <div class="text-center">
                            <a href="?step=check" class="btn btn-outline-primary">
                                <i class="fas fa-refresh me-2"></i>Verificar Nuevamente
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>

                    <?php elseif ($step === 'database'): ?>
                    <!-- Configuración de Base de Datos -->
                    <h2 class="mb-4">
                        <i class="fas fa-database me-2 text-primary"></i>Configuración de Base de Datos
                    </h2>

                    <?php if ($_POST): ?>
                        <?php
                        $host = $_POST['db_host'] ?? '';
                        $name = $_POST['db_name'] ?? '';
                        $user = $_POST['db_user'] ?? '';
                        $pass = $_POST['db_pass'] ?? '';
                        
                        try {
                            $pdo = new PDO("mysql:host=$host;dbname=$name;charset=utf8mb4", $user, $pass);
                            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                            
                            // Guardar configuración
                            $config = file_get_contents('config/config.php');
                            $config = preg_replace("/define\('DB_HOST',\s*'[^']*'\);/", "define('DB_HOST', '$host');", $config);
                            $config = preg_replace("/define\('DB_NAME',\s*'[^']*'\);/", "define('DB_NAME', '$name');", $config);
                            $config = preg_replace("/define\('DB_USER',\s*'[^']*'\);/", "define('DB_USER', '$user');", $config);
                            $config = preg_replace("/define\('DB_PASS',\s*'[^']*'\);/", "define('DB_PASS', '$pass');", $config);
                            
                            file_put_contents('config/config.php', $config);
                            
                            echo '<div class="alert alert-success">
                                    <i class="fas fa-check-circle me-2"></i>
                                    ¡Conexión exitosa! Configuración guardada.
                                  </div>';
                            echo '<div class="text-center">
                                    <a href="?step=whatsapp" class="btn btn-whatsapp btn-lg text-white">
                                        <i class="fas fa-arrow-right me-2"></i>Configurar WhatsApp
                                    </a>
                                  </div>';
                        } catch (PDOException $e) {
                            echo '<div class="alert alert-danger">
                                    <i class="fas fa-exclamation-circle me-2"></i>
                                    Error de conexión: ' . htmlspecialchars($e->getMessage()) . '
                                  </div>';
                        }
                        ?>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Host de Base de Datos</label>
                                <input type="text" class="form-control" name="db_host" 
                                       value="localhost" required
                                       placeholder="localhost">
                                <small class="text-muted">Generalmente: localhost</small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Nombre de Base de Datos</label>
                                <input type="text" class="form-control" name="db_name" 
                                       required placeholder="whatsapp_bot">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Usuario de BD</label>
                                <input type="text" class="form-control" name="db_user" 
                                       required placeholder="usuario_db">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Contraseña de BD</label>
                                <input type="password" class="form-control" name="db_pass" 
                                       required placeholder="••••••••">
                            </div>
                        </div>
                        
                        <div class="alert alert-info mt-3">
                            <i class="fas fa-info-circle me-2"></i>
                            Estos datos los obtienes desde tu panel de hosting (cPanel, Plesk, etc.)
                        </div>

                        <div class="text-center mt-4">
                            <button type="submit" class="btn btn-whatsapp btn-lg text-white">
                                <i class="fas fa-plug me-2"></i>Probar Conexión
                            </button>
                        </div>
                    </form>

                    <?php elseif ($step === 'whatsapp'): ?>
                    <!-- Configuración de WhatsApp -->
                    <h2 class="mb-4">
                        <i class="fab fa-whatsapp me-2 text-success"></i>Configuración de WhatsApp
                    </h2>

                    <?php if ($_POST): ?>
                        <?php
                        $token = $_POST['whatsapp_token'] ?? '';
                        $phone_id = $_POST['phone_id'] ?? '';
                        $webhook_token = $_POST['webhook_token'] ?? 'mi_token_secreto_123';
                        $domain = $_POST['domain'] ?? '';
                        
                        // Actualizar configuración
                        $config = file_get_contents('config/config.php');
                        $config = preg_replace("/define\('WHATSAPP_TOKEN',\s*'[^']*'\);/", 
                                             "define('WHATSAPP_TOKEN', '$token');", $config);
                        $config = preg_replace("/define\('WHATSAPP_PHONE_NUMBER_ID',\s*'[^']*'\);/", 
                                             "define('WHATSAPP_PHONE_NUMBER_ID', '$phone_id');", $config);
                        $config = preg_replace("/define\('WEBHOOK_VERIFY_TOKEN',\s*'[^']*'\);/", 
                                             "define('WEBHOOK_VERIFY_TOKEN', '$webhook_token');", $config);
                        $config = preg_replace("/define\('APP_URL',\s*'[^']*'\);/", 
                                             "define('APP_URL', 'https://$domain');", $config);
                        
                        file_put_contents('config/config.php', $config);
                        
                        echo '<div class="alert alert-success">
                                <i class="fas fa-check-circle me-2"></i>
                                ¡Configuración de WhatsApp guardada correctamente!
                              </div>';
                        ?>
                        
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>Importante:</strong> Configura estos datos en Facebook Developers:
                            <ul class="mt-2 mb-0">
                                <li><strong>Webhook URL:</strong> https://<?= htmlspecialchars($domain) ?>/bot/api/webhook.php</li>
                                <li><strong>Verify Token:</strong> <?= htmlspecialchars($webhook_token) ?></li>
                                <li><strong>Subscribe to:</strong> conversations</li>
                            </ul>
                        </div>

                        <div class="text-center">
                            <a href="install.php" class="btn btn-success btn-lg me-3">
                                <i class="fas fa-database me-2"></i>Instalar Base de Datos
                            </a>
                            <a href="index.php" class="btn btn-whatsapp btn-lg text-white">
                                <i class="fas fa-rocket me-2"></i>Ir al Panel
                            </a>
                        </div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="row g-3">
                            <div class="col-12">
                                <label class="form-label">Token de WhatsApp Business</label>
                                <input type="text" class="form-control" name="whatsapp_token" 
                                       required placeholder="EAAxxxxxxxxxxxx...">
                                <small class="text-muted">Obténlo desde Facebook for Developers</small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Phone Number ID</label>
                                <input type="text" class="form-control" name="phone_id" 
                                       required placeholder="123456789012345">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Tu Dominio</label>
                                <input type="text" class="form-control" name="domain" 
                                       required placeholder="midominio.com"
                                       value="<?= htmlspecialchars($_SERVER['HTTP_HOST'] ?? '') ?>">
                            </div>
                            <div class="col-12">
                                <label class="form-label">Token de Verificación Webhook</label>
                                <input type="text" class="form-control" name="webhook_token" 
                                       value="mi_token_secreto_123" required>
                                <small class="text-muted">Usado para verificar el webhook</small>
                            </div>
                        </div>

                        <div class="text-center mt-4">
                            <button type="submit" class="btn btn-whatsapp btn-lg text-white">
                                <i class="fas fa-save me-2"></i>Guardar Configuración
                            </button>
                        </div>
                    </form>

                    <?php endif; ?>

                    <!-- Navigation -->
                    <div class="mt-5 pt-4 border-top text-center">
                        <div class="btn-group" role="group">
                            <?php if ($step !== 'welcome'): ?>
                            <a href="?step=welcome" class="btn btn-outline-secondary">
                                <i class="fas fa-home me-2"></i>Inicio
                            </a>
                            <?php endif; ?>
                            <?php if ($step === 'whatsapp'): ?>
                            <a href="?step=database" class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>Anterior
                            </a>
                            <?php endif; ?>
                        </div>
                        
                        <div class="mt-3">
                            <small class="text-muted">
                                WhatsApp Bot Manager v1.0 | 
                                <a href="DEPLOYMENT_GUIDE.md" target="_blank">Guía Completa</a>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>