<?php
// index_sin_recaptcha.php - Formulario sin reCAPTCHA
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Mostrar mensajes
$mensaje = $_SESSION['flash_message'] ?? '';
$tipo_mensaje = $_SESSION['flash_type'] ?? '';
unset($_SESSION['flash_message'], $_SESSION['flash_type']);

// Conexión BD
try {
    $pdo = new PDO("mysql:host=localhost;dbname=kxewkurkho_encuestabd;charset=utf8", "kxewkurkho_encuestados", "3ncu3st@spy");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $campos = $pdo->query("SELECT * FROM campos_encuesta WHERE activo = 1 ORDER BY orden")->fetchAll();
    $logos = $pdo->query("SELECT * FROM logos WHERE activo = 1 ORDER BY orden")->fetchAll();
} catch (Exception $e) {
    $campos = [];
    $logos = [];
    $error_bd = "Error cargando datos: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Encuesta MIPYMES - Sin reCAPTCHA</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)), 
                        url('https://images.unsplash.com/photo-1556761175-5973dc0f32e7?ixlib=rb-1.2.1&auto=format&fit=crop&w=1950&q=80');
            background-size: cover;
            background-position: center;
            color: #333;
            min-height: 100vh;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 40px;
            background: rgba(255,255,255,0.95);
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 2.5em;
        }
        
        .header p {
            color: #7f8c8d;
            font-size: 1.2em;
        }
        
        .form-container {
            background: rgba(255,255,255,0.95);
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 25px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #bdc3c7;
            border-radius: 6px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }
        
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #3498db;
        }
        
        .required::after {
            content: " *";
            color: #e74c3c;
        }
        
        .btn-submit {
            background: #27ae60;
            color: white;
            padding: 15px 40px;
            border: none;
            border-radius: 6px;
            font-size: 18px;
            cursor: pointer;
            transition: background 0.3s ease;
            display: block;
            margin: 30px auto 0;
        }
        
        .btn-submit:hover {
            background: #219a52;
        }
        
        .alert {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .logos-section {
            background: rgba(255,255,255,0.95);
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            text-align: center;
        }
        
        .logos-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
        }
        
        .logo-item {
            width: 120px;
            height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: white;
            border-radius: 8px;
            padding: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .logo-item img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        
        .gps-status {
            font-size: 14px;
            color: #7f8c8d;
            margin-top: 5px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 Encuesta MIPYMES</h1>
            <p>Tu opinión es importante para el crecimiento de las micro, pequeñas y medianas empresas</p>
            <p style="color: #27ae60; font-weight: bold; margin-top: 10px;">✅ Modo sin reCAPTCHA - Envíos directos</p>
        </div>
        
        <?php if(isset($error_bd)): ?>
            <div class="alert alert-error">
                <?php echo $error_bd; ?>
            </div>
        <?php endif; ?>
        
        <?php if($mensaje): ?>
            <div class="alert alert-<?php echo $tipo_mensaje; ?>">
                <?php echo $mensaje; ?>
            </div>
        <?php endif; ?>
        
        <?php if(!empty($logos)): ?>
        <div class="logos-section">
            <h3>🏢 Empresas y Organizaciones Participantes</h3>
            <div class="logos-container">
                <?php foreach($logos as $logo): ?>
                <div class="logo-item">
                    <?php if(!empty($logo['url'])): ?>
                        <a href="<?php echo htmlspecialchars($logo['url']); ?>" target="_blank">
                            <img src="uploads/<?php echo htmlspecialchars($logo['imagen']); ?>" alt="<?php echo htmlspecialchars($logo['nombre']); ?>">
                        </a>
                    <?php else: ?>
                        <img src="uploads/<?php echo htmlspecialchars($logo['imagen']); ?>" alt="<?php echo htmlspecialchars($logo['nombre']); ?>">
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="form-container">
            <?php if(empty($campos)): ?>
                <div style="text-align: center; padding: 40px; color: #7f8c8d;">
                    <h3>📝 Encuesta en Preparación</h3>
                    <p>Actualmente no hay campos de encuesta disponibles.</p>
                </div>
            <?php else: ?>
            
            <form method="POST" action="procesar_sin_recaptcha.php" id="encuestaForm">
                <?php foreach($campos as $campo): ?>
                <div class="form-group">
                    <label class="<?php echo $campo['obligatorio'] ? 'required' : ''; ?>">
                        <?php echo htmlspecialchars($campo['nombre']); ?>
                    </label>
                    
                    <?php if($campo['tipo'] == 'select' && !empty($campo['opciones'])): ?>
                        <select name="campo_<?php echo $campo['id']; ?>" <?php echo $campo['obligatorio'] ? 'required' : ''; ?>>
                            <option value="">-- Seleccione una opción --</option>
                            <?php 
                            $opciones = explode(',', $campo['opciones']);
                            foreach($opciones as $opcion): 
                                $opcion_trim = trim($opcion);
                                if(!empty($opcion_trim)):
                            ?>
                                <option value="<?php echo htmlspecialchars($opcion_trim); ?>">
                                    <?php echo htmlspecialchars($opcion_trim); ?>
                                </option>
                            <?php 
                                endif;
                            endforeach; 
                            ?>
                        </select>
                    <?php elseif($campo['tipo'] == 'texto'): ?>
                        <textarea name="campo_<?php echo $campo['id']; ?>" 
                                  rows="4" 
                                  placeholder="Escriba su respuesta aquí..."
                                  <?php echo $campo['obligatorio'] ? 'required' : ''; ?>></textarea>
                    <?php else: ?>
                        <input type="<?php echo $campo['tipo']; ?>" 
                               name="campo_<?php echo $campo['id']; ?>" 
                               placeholder="Ingrese <?php echo strtolower($campo['nombre']); ?>..."
                               <?php echo $campo['obligatorio'] ? 'required' : ''; ?>>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
                
                <input type="hidden" name="latitud" id="latitud" value="">
                <input type="hidden" name="longitud" id="longitud" value="">
                
                <div class="gps-status" id="gpsStatus">
                    📍 Obteniendo ubicación GPS...
                </div>
                
                <button type="submit" class="btn-submit" id="submitBtn">
                    ✅ Enviar Encuesta (Sin reCAPTCHA)
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // GPS simple
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        document.getElementById('latitud').value = position.coords.latitude;
                        document.getElementById('longitud').value = position.coords.longitude;
                        document.getElementById('gpsStatus').textContent = '📍 Ubicación obtenida correctamente';
                        document.getElementById('gpsStatus').style.color = '#27ae60';
                    },
                    function(error) {
                        console.log('Error GPS:', error);
                        document.getElementById('gpsStatus').textContent = '❌ No se pudo obtener la ubicación GPS';
                        document.getElementById('gpsStatus').style.color = '#e74c3c';
                    }
                );
            } else {
                document.getElementById('gpsStatus').textContent = '❌ GPS no soportado';
                document.getElementById('gpsStatus').style.color = '#e74c3c';
            }
        }

        // Envío directo sin reCAPTCHA
        document.getElementById('encuestaForm').addEventListener('submit', function(e) {
            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.innerHTML;
            
            // Mostrar loading
            submitBtn.innerHTML = '⏳ Enviando...';
            submitBtn.disabled = true;
            
            // El formulario se envía directamente
            // No hay validación de reCAPTCHA que lo bloquee
        });

        // Inicializar
        document.addEventListener('DOMContentLoaded', function() {
            getLocation();
        });
    </script>
</body>
</html>