<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instalador de Glado</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; }
        .card { border-radius: 15px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
        .step { display: none; }
        .step.active { display: block; }
        .test-result { margin-top: 10px; }
    </style>
</head>
<body>
    <div class="container vh-100 d-flex justify-content-center align-items-center">
        <div class="card p-4" style="width: 100%; max-width: 600px;">
            <h1 class="text-center mb-4">Instalador de Glado</h1>
            <form id="install-form">
                <!-- Paso 1: Base de Datos -->
                <div id="step-1" class="step active">
                    <h5 class="mb-3">Paso 1: Base de Datos</h5>
                    <div class="mb-3"><label for="db_host" class="form-label">Host</label><input type="text" class="form-control" id="db_host" name="db_host" required></div>
                    <div class="mb-3"><label for="db_name" class="form-label">Nombre de la BD</label><input type="text" class="form-control" id="db_name" name="db_name" required></div>
                    <div class="mb-3"><label for="db_user" class="form-label">Usuario</label><input type="text" class="form-control" id="db_user" name="db_user" required></div>
                    <div class="mb-3"><label for="db_pass" class="form-label">Contraseña</label><input type="password" class="form-control" id="db_pass" name="db_pass"></div>
                    <button type="button" class="btn btn-info" onclick="testConnection('db')">Probar Conexión</button>
                    <div id="db-test-result" class="test-result"></div>
                    <button type="button" class="btn btn-primary w-100 mt-3" id="btn-step1-next" onclick="nextStep(2)" disabled>Siguiente</button>
                </div>

                <!-- Paso 2: Administrador y Sucursal -->
                <div id="step-2" class="step">
                    <h5 class="mb-3">Paso 2: Administrador y Sucursal</h5>
                    <div class="mb-3"><label for="admin_user" class="form-label">Usuario Admin</label><input type="text" class="form-control" id="admin_user" name="admin_user" required></div>
                    <div class="mb-3"><label for="admin_pass" class="form-label">Contraseña Admin</label><input type="password" class="form-control" id="admin_pass" name="admin_pass" required></div>
                    <div class="mb-3"><label for="admin_email" class="form-label">Email Admin (para pruebas)</label><input type="email" class="form-control" id="admin_email" name="admin_email" required></div>
                    <div class="mb-3"><label for="admin_phone" class="form-label">Teléfono Admin (para pruebas, con código de país)</label><input type="tel" class="form-control" id="admin_phone" name="admin_phone" required></div>
                    <div class="mb-3"><label for="branch_name" class="form-label">Nombre de la Primera Sucursal</label><input type="text" class="form-control" id="branch_name" name="branch_name" required></div>
                    <button type="button" class="btn btn-secondary" onclick="prevStep(1)">Anterior</button>
                    <button type="button" class="btn btn-primary" onclick="nextStep(3)">Siguiente</button>
                </div>

                <!-- Paso 3: SMTP -->
                <div id="step-3" class="step">
                    <h5 class="mb-3">Paso 3: Configuración SMTP (PHPMailer)</h5>
                    <div class="mb-3"><label for="smtp_host" class="form-label">Host SMTP</label><input type="text" class="form-control" id="smtp_host" name="smtp_host" required></div>
                    <div class="mb-3"><label for="smtp_port" class="form-label">Puerto SMTP</label><input type="number" class="form-control" id="smtp_port" name="smtp_port" required></div>
                    <div class="mb-3"><label for="smtp_user" class="form-label">Usuario SMTP</label><input type="text" class="form-control" id="smtp_user" name="smtp_user" required></div>
                    <div class="mb-3"><label for="smtp_pass" class="form-label">Contraseña SMTP</label><input type="password" class="form-control" id="smtp_pass" name="smtp_pass" required></div>
                    <div class="mb-3"><label for="smtp_encryption" class="form-label">Cifrado</label><select class="form-select" id="smtp_encryption" name="smtp_encryption"><option value="tls">TLS</option><option value="ssl">SSL</option></select></div>
                    <button type="button" class="btn btn-info" onclick="testConnection('smtp')">Probar Conexión</button>
                    <div id="smtp-test-result" class="test-result"></div>
                    <button type="button" class="btn btn-secondary" onclick="prevStep(2)">Anterior</button>
                    <button type="button" class="btn btn-primary" id="btn-step3-next" onclick="nextStep(4)" disabled>Siguiente</button>
                </div>

                <!-- Paso 4: Twilio -->
                <div id="step-4" class="step">
                    <h5 class="mb-3">Paso 4: Configuración de WhatsApp (Twilio)</h5>
                    <div class="mb-3"><label for="twilio_sid" class="form-label">Twilio Account SID</label><input type="text" class="form-control" id="twilio_sid" name="twilio_sid" required></div>
                    <div class="mb-3"><label for="twilio_token" class="form-label">Twilio Auth Token</label><input type="password" class="form-control" id="twilio_token" name="twilio_token" required></div>
                    <div class="mb-3"><label for="twilio_whatsapp_from" class="form-label">Número de WhatsApp de Twilio</label><input type="text" class="form-control" id="twilio_whatsapp_from" name="twilio_whatsapp_from" required></div>
                    <button type="button" class="btn btn-info" onclick="testConnection('twilio')">Probar Conexión</button>
                    <div id="twilio-test-result" class="test-result"></div>
                    <button type="button" class="btn btn-secondary" onclick="prevStep(3)">Anterior</button>
                    <button type="submit" class="btn btn-success w-100 mt-3" id="btn-install" disabled>Instalar</button>
                </div>
            </form>
            <div id="progress-container" class="mt-4" style="display: none;">
                <div class="progress"><div id="progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%;"></div></div>
                <p id="progress-status" class="text-center mt-2"></p>
            </div>
            <div id="result-container" class="mt-4" style="display: none;"></div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        let currentStep = 1;
        function showStep(step) {
            $('.step').removeClass('active');
            $('#step-' + step).addClass('active');
            currentStep = step;
        }
        function nextStep(step) { showStep(step); }
        function prevStep(step) { showStep(step); }

        function testConnection(type) {
            let data = $('#install-form').serialize() + '&action=test_' + type;
            let resultDiv = '#' + type + '-test-result';
            let nextButton = '#btn-step' + currentStep + '-next';
            if (type === 'twilio') nextButton = '#btn-install';

            $(resultDiv).html('<div class="spinner-border spinner-border-sm" role="status"><span class="visually-hidden">Loading...</span></div>');

            $.ajax({
                url: 'installer_logic.php',
                type: 'GET',
                data: data,
                success: function(response) {
                    let res;
                    try {
                        res = (typeof response === 'object') ? response : JSON.parse(response);
                    } catch (e) {
                        $(resultDiv).html('<div class="alert alert-danger">Error: La respuesta del servidor no es válida.</div>');
                        return;
                    }

                    if (res.success) {
                        $(resultDiv).html('<div class="alert alert-success">' + res.message + '</div>');
                        $(nextButton).prop('disabled', false);
                    } else {
                        $(resultDiv).html('<div class="alert alert-danger">' + res.message + '</div>');
                        $(nextButton).prop('disabled', true);
                    }
                },
                error: function() {
                    $(resultDiv).html('<div class="alert alert-danger">Error de comunicación con el servidor.</div>');
                    $(nextButton).prop('disabled', true);
                }
            });
        }

        $('#install-form').on('submit', function(e) {
            e.preventDefault();
            $('#install-form').hide();
            $('#progress-container').show();

            let formData = $(this).serialize() + '&action=install';
            const eventSource = new EventSource('installer_logic.php?' + formData);

            eventSource.onmessage = function(event) {
                const data = JSON.parse(event.data);
                if (data.progress) {
                    $('#progress-bar').css('width', data.progress + '%').text(data.progress + '%');
                    $('#progress-status').html(data.message);
                }
                if (data.status) {
                    $('#progress-container').hide();
                    $('#result-container').html(data.message).show();
                    eventSource.close();
                }
            };

            eventSource.onerror = function() {
                $('#progress-container').hide();
                $('#result-container').html('<div class="alert alert-danger">Error de conexión con el servidor.</div>').show();
                eventSource.close();
            };
        });
    </script>
</body>
</html>