<%@ page import="java.sql.*" %>
<%@ page import="servlet.conexion_mysql" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<% request.setCharacterEncoding("UTF-8"); %>

<%
    String filtroRestaurante = request.getParameter("restaurante");
    String filtroTipoComida = request.getParameter("tipo_comida");
%>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Restaurantes - Guía Gastronómica</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #FF6699 0%, #FF0000 50%, #FF33CC 100%);
            min-height: 100vh;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
            color: white;
        }

        .header h1 {
            font-size: 3rem;
            font-weight: 700;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.2rem;
            opacity: 0.9;
            font-weight: 300;
        }

        .filters-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 40px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .filters-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .filter-row {
            display: grid;
            grid-template-columns: 1fr 1fr auto auto;
            gap: 20px;
            align-items: end;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
        }

        .filter-group label {
            font-weight: 600;
            color: #34495e;
            margin-bottom: 8px;
            font-size: 0.95rem;
        }

        .filter-group select {
            padding: 12px 15px;
            border: 2px solid #e1e8ed;
            border-radius: 10px;
            font-size: 1rem;
            background: white;
            transition: all 0.3s ease;
            outline: none;
        }

        .filter-group select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 10px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            height: fit-content;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: transparent;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .btn-secondary:hover {
            background: #667eea;
            color: white;
        }

        .restaurants-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 30px;
        }

        .restaurant-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .restaurant-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 30px 60px rgba(0,0,0,0.15);
        }

        .restaurant-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .restaurant-header {
            margin-bottom: 25px;
        }

        .restaurant-name {
            font-size: 1.8rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 15px;
        }

        .restaurant-info {
            display: grid;
            gap: 10px;
        }

        .info-item {
            display: flex;
            align-items: center;
            gap: 12px;
            color: #5a6c7d;
        }

        .info-item i {
            width: 20px;
            color: #667eea;
        }

        .section {
            margin-top: 30px;
        }

        .section-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .services-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .service-tag {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .menu-items {
            display: grid;
            gap: 15px;
        }

        .menu-item {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            border-left: 4px solid #667eea;
            transition: all 0.3s ease;
        }

        .menu-item:hover {
            background: #e3f2fd;
            transform: translateX(5px);
        }

        .dish-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 8px;
        }

        .dish-name {
            font-weight: 600;
            color: #2c3e50;
            font-size: 1.1rem;
        }

        .dish-price {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 4px 12px;
            border-radius: 15px;
            font-weight: 600;
            font-size: 0.9rem;
        }

        .dish-type {
            color: #667eea;
            font-size: 0.9rem;
            font-weight: 500;
            margin-bottom: 5px;
        }

        .dish-description {
            color: #5a6c7d;
            font-size: 0.95rem;
            line-height: 1.5;
        }

        .no-results {
            text-align: center;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 60px 30px;
            color: #5a6c7d;
        }

        .no-results i {
            font-size: 4rem;
            color: #bdc3c7;
            margin-bottom: 20px;
        }

        .no-results h3 {
            font-size: 1.5rem;
            margin-bottom: 10px;
            color: #2c3e50;
        }

        .error-message {
            background: #ff6b6b;
            color: white;
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
        }

        @media (max-width: 768px) {
            .header h1 {
                font-size: 2rem;
            }

            .filter-row {
                grid-template-columns: 1fr;
                gap: 15px;
            }

            .restaurants-grid {
                grid-template-columns: 1fr;
            }

            .dish-header {
                flex-direction: column;
                gap: 8px;
            }

            .container {
                padding: 15px;
            }
        }

        .fade-in {
            animation: fadeIn 0.6s ease-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header fade-in">
            <h1><i class="fas fa-utensils"></i> Guía Gastronómica</h1>
            <p>Descubre los mejores restaurantes y sus deliciosos platillos</p>
        </div>

        <!-- Filtros -->
        <div class="filters-container fade-in">
            <div class="filters-title">
                <i class="fas fa-filter"></i>
                Filtrar Restaurantes
            </div>
            <form method="get" action="vista_restaurantes.jsp">
                <div class="filter-row">
                    <div class="filter-group">
                        <label for="restaurante"><i class="fas fa-store"></i> Restaurante</label>
                        <select name="restaurante" id="restaurante">
                            <option value="">Todos los restaurantes</option>
                            <%
                                try (Connection con = conexion_mysql.getConnection();
                                     PreparedStatement ps = con.prepareStatement("SELECT id_restaurantes, nombre_restaurante FROM restaurantes ORDER BY nombre_restaurante");
                                     ResultSet rs = ps.executeQuery()) {
                                    while (rs.next()) {
                                        int id = rs.getInt("id_restaurantes");
                                        String nombre = rs.getString("nombre_restaurante");
                                        String selected = (String.valueOf(id).equals(filtroRestaurante)) ? "selected" : "";
                            %>
                                        <option value="<%= id %>" <%= selected %>><%= nombre %></option>
                            <%
                                    }
                                } catch (Exception e) {
                                    out.println("<option>Error al cargar restaurantes</option>");
                                }
                            %>
                        </select>
                    </div>

                    <div class="filter-group">
                        <label for="tipo_comida"><i class="fas fa-pizza-slice"></i> Tipo de Comida</label>
                        <select name="tipo_comida" id="tipo_comida">
                            <option value="">Todos los tipos</option>
                            <%
                                try (Connection con = conexion_mysql.getConnection();
                                     PreparedStatement ps = con.prepareStatement("SELECT DISTINCT tipo_comida FROM platos_restaurante WHERE tipo_comida IS NOT NULL AND tipo_comida != '' ORDER BY tipo_comida");
                                     ResultSet rs = ps.executeQuery()) {
                                    while (rs.next()) {
                                        String tipo = rs.getString("tipo_comida");
                                        String selected = tipo.equalsIgnoreCase(filtroTipoComida) ? "selected" : "";
                            %>
                                        <option value="<%= tipo %>" <%= selected %>><%= tipo %></option>
                            <%
                                    }
                                } catch (Exception e) {
                                    out.println("<option>Error al cargar tipos</option>");
                                }
                            %>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i>
                        Buscar
                    </button>
                    
                    <a href="vista_restaurantes.jsp" class="btn btn-secondary">
                        <i class="fas fa-times"></i>
                        Limpiar
                    </a>
                </div>
            </form>
        </div>

        <!-- Restaurantes -->
        <div class="restaurants-grid">
            <%
                try (Connection con = conexion_mysql.getConnection()) {

                    StringBuilder sql = new StringBuilder("SELECT * FROM restaurantes WHERE 1=1");
                    if (filtroRestaurante != null && !filtroRestaurante.isEmpty()) {
                        sql.append(" AND id_restaurantes = ?");
                    }
                    sql.append(" ORDER BY nombre_restaurante");

                    try (PreparedStatement psRest = con.prepareStatement(sql.toString())) {
                        if (filtroRestaurante != null && !filtroRestaurante.isEmpty()) {
                            psRest.setInt(1, Integer.parseInt(filtroRestaurante));
                        }

                        try (ResultSet rsRest = psRest.executeQuery()) {

                            boolean encontrado = false;
                            while (rsRest.next()) {
                                int idRest = rsRest.getInt("id_restaurantes");
                                String nombre = rsRest.getString("nombre_restaurante");
                                String direccion = rsRest.getString("direccion");
                                String telefono = rsRest.getString("telefono");
                                String email = rsRest.getString("email");

                                // Verificar filtro de tipo de comida
                                boolean mostrar = true;
                                if (filtroTipoComida != null && !filtroTipoComida.isEmpty()) {
                                    String tipoCheckSql = "SELECT COUNT(*) FROM platos_restaurante WHERE id_restaurante = ? AND tipo_comida = ?";
                                    try (PreparedStatement psTipo = con.prepareStatement(tipoCheckSql)) {
                                        psTipo.setInt(1, idRest);
                                        psTipo.setString(2, filtroTipoComida);
                                        try (ResultSet rsTipo = psTipo.executeQuery()) {
                                            rsTipo.next();
                                            mostrar = rsTipo.getInt(1) > 0;
                                        }
                                    }
                                }

                                if (!mostrar) continue;
                                encontrado = true;
            %>

            <div class="restaurant-card fade-in">
                <div class="restaurant-header">
                    <h2 class="restaurant-name"><%= nombre %></h2>
                    <div class="restaurant-info">
                        <div class="info-item">
                            <i class="fas fa-map-marker-alt"></i>
                            <span><%= direccion != null ? direccion : "Dirección no disponible" %></span>
                        </div>
                        <% if (telefono != null && !telefono.trim().isEmpty()) { %>
                        <div class="info-item">
                            <i class="fas fa-phone"></i>
                            <span><%= telefono %></span>
                        </div>
                        <% } %>
                        <% if (email != null && !email.trim().isEmpty()) { %>
                        <div class="info-item">
                            <i class="fas fa-envelope"></i>
                            <span><%= email %></span>
                        </div>
                        <% } %>
                    </div>
                </div>

                <!-- Servicios -->
                <div class="section">
                    <div class="section-title">
                        <i class="fas fa-concierge-bell"></i>
                        Servicios
                    </div>
                    <div class="services-list">
                        <%
                            String sqlServicios = "SELECT s.nombre_servicio FROM restaurante_servicio rs " +
                                                  "JOIN servicios s ON rs.id_servicio = s.id_servicio " +
                                                  "WHERE rs.id_restaurante = ? ORDER BY s.nombre_servicio";
                            try (PreparedStatement psServ = con.prepareStatement(sqlServicios)) {
                                psServ.setInt(1, idRest);
                                try (ResultSet rsServ = psServ.executeQuery()) {
                                    boolean hayServicios = false;
                                    while (rsServ.next()) {
                                        hayServicios = true;
                                        out.println("<span class='service-tag'>" + rsServ.getString("nombre_servicio") + "</span>");
                                    }
                                    if (!hayServicios) {
                                        out.println("<span class='service-tag' style='background: #bdc3c7;'>Sin servicios especificados</span>");
                                    }
                                }
                            }
                        %>
                    </div>
                </div>

                <!-- Menú -->
                <div class="section">
                    <div class="section-title">
                        <i class="fas fa-book-open"></i>
                        Menú
                    </div>
                    <div class="menu-items">
                        <%
                            String sqlPlatos = "SELECT tipo_comida, nombre_plato, descripcion, precio " +
                                               "FROM platos_restaurante WHERE id_restaurante = ?";
                            if (filtroTipoComida != null && !filtroTipoComida.isEmpty()) {
                                sqlPlatos += " AND tipo_comida = ?";
                            }
                            sqlPlatos += " ORDER BY tipo_comida, nombre_plato";

                            try (PreparedStatement psPlatos = con.prepareStatement(sqlPlatos)) {
                                psPlatos.setInt(1, idRest);
                                if (filtroTipoComida != null && !filtroTipoComida.isEmpty()) {
                                    psPlatos.setString(2, filtroTipoComida);
                                }

                                try (ResultSet rsPlatos = psPlatos.executeQuery()) {
                                    boolean hayPlatos = false;
                                    while (rsPlatos.next()) {
                                        hayPlatos = true;
                                        String nombrePlato = rsPlatos.getString("nombre_plato");
                                        String tipoComida = rsPlatos.getString("tipo_comida");
                                        String descripcion = rsPlatos.getString("descripcion");
                                        double precio = rsPlatos.getDouble("precio");
                        %>
                                        <div class="menu-item">
                                            <div class="dish-header">
                                                <div>
                                                    <div class="dish-name"><%= nombrePlato %></div>
                                                    <div class="dish-type"><i class="fas fa-tag"></i> <%= tipoComida %></div>
                                                </div>
                                                <div class="dish-price">$<%= String.format("%.2f", precio) %></div>
                                            </div>
                                            <div class="dish-description"><%= descripcion != null ? descripcion : "Sin descripción disponible" %></div>
                                        </div>
                        <%
                                    }
                                    if (!hayPlatos) {
                                        out.println("<div class='menu-item' style='text-align: center; color: #bdc3c7;'>");
                                        out.println("<i class='fas fa-utensils' style='font-size: 2rem; margin-bottom: 10px;'></i>");
                                        out.println("<div>No hay platos registrados</div>");
                                        out.println("</div>");
                                    }
                                }
                            }
                        %>
                    </div>
                </div>
            </div>

            <%
                            } // fin while
                            if (!encontrado) {
            %>
                                <div class="no-results">
                                    <i class="fas fa-search"></i>
                                    <h3>No se encontraron restaurantes</h3>
                                    <p>Intenta ajustar los filtros de búsqueda</p>
                                </div>
            <%
                            }
                        }
                    }

                } catch (Exception e) {
            %>
                    <div class="error-message">
                        <i class="fas fa-exclamation-triangle"></i>
                        Error al cargar los datos: <%= e.getMessage() %>
                    </div>
            <%
                }
            %>
        </div>
    </div>

    <script>
        // Animación de entrada para los elementos
        document.addEventListener('DOMContentLoaded', function() {
            const cards = document.querySelectorAll('.restaurant-card');
            cards.forEach((card, index) => {
                card.style.animationDelay = (index * 0.1) + 's';
            });
        });

        // Efecto hover mejorado para las cards
        document.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('mouseenter', function() {
                this.style.boxShadow = '0 8px 25px rgba(102, 126, 234, 0.15)';
            });
            
            item.addEventListener('mouseleave', function() {
                this.style.boxShadow = 'none';
            });
        });
    </script>
</body>
</html>