<?php
/**
 * Instalador del Sistema de Eventos Institucionales
 *
 * Un solo paso: base de datos + URL opcional. El administrador configura
 * el resto desde el panel. Compatible con cPanel.
 */

session_start();

// Bloqueo 1: archivo installed.flag
if (file_exists(dirname(__DIR__) . '/config/installed.flag')) {
    header('HTTP/1.1 403 Forbidden');
    die('El sistema ya está instalado. Elimine el archivo config/installed.flag para reinstalar.');
}

// Bloqueo 2: si config existe y podemos conectar, verificar que no haya datos
$configPath = dirname(__DIR__) . '/config/config.php';
if (file_exists($configPath)) {
    $configContent = file_get_contents($configPath);
    if (preg_match("/define\('DB_HOST',\s*'([^']*)'\)/", $configContent, $mHost) &&
        preg_match("/define\('DB_NAME',\s*'([^']*)'\)/", $configContent, $mName) &&
        preg_match("/define\('DB_USER',\s*'([^']*)'\)/", $configContent, $mUser) &&
        preg_match("/define\('DB_PASS',\s*'([^']*)'\)/", $configContent, $mPass)) {
        $dbHost = $mHost[1];
        $dbName = $mName[1];
        $dbUser = $mUser[1];
        $dbPass = str_replace(["\\'", "''"], ["'", "'"], $mPass[1]);
        if (!empty($dbName)) {
            try {
                $pdoCheck = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8mb4", $dbUser, $dbPass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
                $count = (int) $pdoCheck->query("SELECT COUNT(*) FROM eventos_base")->fetchColumn();
                if ($count > 0) {
                    header('HTTP/1.1 403 Forbidden');
                    die('La base de datos ya contiene eventos. El instalador está deshabilitado por seguridad.');
                }
            } catch (Exception $e) {
                // No se pudo conectar, permitir continuar (instalación nueva)
            }
        }
    }
}

$errors = [];
$success = false;
$sqlDumpPath = dirname(__DIR__) . '/eventos_unejud.sql';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $db_host = trim($_POST['db_host'] ?? 'localhost');
    $db_name = trim($_POST['db_name'] ?? '');
    $db_user = trim($_POST['db_user'] ?? 'root');
    $db_pass = $_POST['db_pass'] ?? '';
    $base_url = trim($_POST['base_url'] ?? '');

    if (empty($db_name)) {
        $errors[] = 'El nombre de la base de datos es requerido';
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $db_name)) {
        $errors[] = 'El nombre de la base de datos solo puede contener letras, números y guión bajo';
    } elseif (!is_readable($sqlDumpPath)) {
        $errors[] = 'No se encuentra eventos_unejud.sql en la raíz del proyecto.';
    } else {
        try {
            $pdo = new PDO("mysql:host=" . $db_host, $db_user, $db_pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            ]);
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");

            $schema = file_get_contents($sqlDumpPath);
            $schema = preg_replace('/CREATE DATABASE IF NOT EXISTS `eventos_unejud`/i', 'CREATE DATABASE IF NOT EXISTS `' . $db_name . '`', $schema);
            $schema = preg_replace('/USE `eventos_unejud`/i', 'USE `' . $db_name . '`', $schema);
            $metadatosPos = strpos($schema, "\n-- Metadatos\n");
            if ($metadatosPos !== false) {
                $schema = substr($schema, 0, $metadatosPos);
            }
            $schema .= "\nCOMMIT;\n";
            $schema .= "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n";
            $schema .= "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n";
            $schema .= "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n";

            $mysqli = new mysqli($db_host, $db_user, $db_pass);
            if ($mysqli->connect_error) {
                throw new Exception('Conexión MySQL: ' . $mysqli->connect_error);
            }
            $mysqli->set_charset('utf8mb4');
            if (!$mysqli->multi_query($schema)) {
                throw new Exception('Error al importar la base de datos: ' . $mysqli->error);
            }
            do {
                if ($result = $mysqli->store_result()) {
                    $result->free();
                }
            } while ($mysqli->next_result() && $mysqli->more_results());
            if ($mysqli->errno) {
                throw new Exception('Error durante la importación: ' . $mysqli->error);
            }
            $mysqli->close();

            if ($base_url !== '') {
                $base_url = rtrim($base_url, '/');
                if (!preg_match('#^https?://#i', $base_url)) {
                    $base_url = 'https://' . $base_url;
                }
            }

            $configPath = dirname(__DIR__) . '/config/config.php';
            $configContent = file_get_contents($configPath);
            if ($configContent === false) {
                throw new Exception('No se pudo leer config/config.php');
            }
            $configContent = preg_replace("/define\('DB_HOST',\s*'[^']*'\);/", "define('DB_HOST', '" . addslashes($db_host) . "');", $configContent);
            $configContent = preg_replace("/define\('DB_NAME',\s*'[^']*'\);/", "define('DB_NAME', '" . addslashes($db_name) . "');", $configContent);
            $configContent = preg_replace("/define\('DB_USER',\s*'[^']*'\);/", "define('DB_USER', '" . addslashes($db_user) . "');", $configContent);
            $configContent = preg_replace("/define\('DB_PASS',\s*'[^']*'\);/", "define('DB_PASS', '" . addslashes($db_pass) . "');", $configContent);
            $configContent = str_replace(
                "// INSTALL_BASE_URL",
                $base_url !== '' ? "define('BASE_URL', '" . addslashes($base_url) . "'); // Definido en instalación" : "// Sin definir: se detecta por dominio",
                $configContent
            );
            if (file_put_contents($configPath, $configContent) === false) {
                throw new Exception('No se pudo escribir config/config.php. Compruebe permisos.');
            }
            file_put_contents(dirname(__DIR__) . '/config/installed.flag', date('Y-m-d H:i:s'));

            $success = true;
            $finalBaseUrl = $base_url !== '' ? $base_url : (
                (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' .
                ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost') .
                rtrim(str_replace('\\', '/', dirname(dirname($_SERVER['SCRIPT_NAME'] ?? ''))), '/')
            );
        } catch (PDOException $e) {
            $errors[] = 'Error de conexión: ' . $e->getMessage();
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

$adminLoginUrl = $success && isset($finalBaseUrl) ? $finalBaseUrl . '/admin/login.php' : '../admin/login.php';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instalador - Sistema de Eventos Institucionales</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: #f8f9fa;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .install-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.08);
            padding: 48px 40px;
            width: 100%;
            max-width: 420px;
        }
        .logo-container {
            display: flex;
            justify-content: center;
            margin-bottom: 32px;
        }
        .logo-placeholder {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
            font-size: 32px;
        }
        h1 {
            text-align: center;
            color: #212529;
            font-size: 22px;
            margin-bottom: 8px;
        }
        .subtitle {
            text-align: center;
            color: #6c757d;
            font-size: 14px;
            margin-bottom: 28px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            color: #495057;
            font-size: 14px;
            font-weight: 500;
        }
        input[type="text"],
        input[type="password"],
        input[type="url"] {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            font-size: 15px;
            transition: all 0.2s;
            background: #fff;
        }
        input:focus {
            outline: none;
            border-color: #495057;
            box-shadow: 0 0 0 3px rgba(73, 80, 87, 0.1);
        }
        .hint {
            font-size: 12px;
            color: #6c757d;
            margin-top: 4px;
        }
        .btn-install {
            width: 100%;
            padding: 14px;
            background: #212529;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.2s;
        }
        .btn-install:hover {
            background: #000;
        }
        .error {
            background: #fff5f5;
            color: #c53030;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            border: 1px solid #fed7d7;
            font-size: 14px;
        }
        .success-box {
            text-align: center;
        }
        .success-box h2 {
            color: #212529;
            font-size: 18px;
            margin-bottom: 12px;
        }
        .success-box p {
            color: #495057;
            font-size: 14px;
            line-height: 1.5;
            margin-bottom: 8px;
        }
        .success-box .note {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 12px;
            font-size: 13px;
            color: #495057;
            margin-top: 20px;
            text-align: left;
        }
        .success-box .note strong { color: #212529; }
        .btn-admin {
            display: inline-block;
            margin-top: 24px;
            padding: 14px 28px;
            background: #212529;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 15px;
            transition: background 0.2s;
        }
        .btn-admin:hover {
            background: #000;
        }
    </style>
</head>
<body>
    <div class="install-container">
        <div class="logo-container">
            <div class="logo-placeholder">📋</div>
        </div>
        <h1>Instalador</h1>
        <p class="subtitle">Sistema de gestión de eventos institucionales</p>

        <?php if ($success): ?>
            <div class="success-box">
                <h2>Instalación completada</h2>
                <p>La base de datos y la configuración han sido guardadas. El resto lo configuras desde el panel.</p>
                <a href="<?php echo htmlspecialchars($adminLoginUrl); ?>" class="btn-admin">Ir al panel de administración</a>
                <div class="note">
                    <strong>Recomendado:</strong> Eliminar o renombrar la carpeta <code>install/</code> después de instalar por seguridad.<br><br>
                    <strong>Emails:</strong> Si quieres usar envío de correos, ejecuta <code>composer install</code> en la raíz del proyecto o sube la carpeta <code>vendor</code>.
                </div>
            </div>
        <?php else: ?>
            <?php if (!empty($errors)): ?>
                <?php foreach ($errors as $err): ?>
                    <div class="error"><?php echo htmlspecialchars($err); ?></div>
                <?php endforeach; ?>
            <?php endif; ?>

            <form method="POST" action="">
                <div class="form-group">
                    <label for="db_host">Host de base de datos</label>
                    <input type="text" id="db_host" name="db_host" value="localhost" required>
                </div>
                <div class="form-group">
                    <label for="db_name">Nombre de la base de datos *</label>
                    <input type="text" id="db_name" name="db_name" placeholder="ej: eventos_unejud" value="eventos_unejud" required>
                    <span class="hint">En cPanel suele ser tu_usuario_nombrebd</span>
                </div>
                <div class="form-group">
                    <label for="db_user">Usuario</label>
                    <input type="text" id="db_user" name="db_user" value="root" required>
                </div>
                <div class="form-group">
                    <label for="db_pass">Contraseña</label>
                    <input type="password" id="db_pass" name="db_pass" placeholder="Contraseña de MySQL">
                </div>
                <div class="form-group">
                    <label for="base_url">URL del sitio (opcional)</label>
                    <input type="url" id="base_url" name="base_url" placeholder="https://eventos.juanadedios.com">
                    <span class="hint">Si se deja vacío, se usa el dominio actual</span>
                </div>
                <button type="submit" class="btn-install">Instalar</button>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>
