<!DOCTYPE html>
<html lang="en">
<script disable-devtool-auto src='https://cdn.jsdelivr.net/npm/disable-devtool@latest'></script>
<head>
    <link rel="stylesheet" href="https://unpkg.com/intro.js/minified/introjs.min.css">
<script src="https://unpkg.com/intro.js/minified/intro.min.js"></script>

<script>
   document.addEventListener('DOMContentLoaded', () => {
    const showGuide = localStorage.getItem('mapaClinicasGuideShown');
    if (!showGuide) {
        introJs()
            .setOptions({
                steps: [
                    {
                        intro: "Bem-vindo ao Mapa de Clínicas! Vamos ajudá-lo a entender como usar o site."
                    },
                    {
                        element: '.leaflet-marker-icon',
                        intro: "Esses números representam grupos de clínicas em uma região. Clique neles para ampliar e explorar mais clínicas."
                    },
                    {
                        element: '#map',
                        intro: "No mapa, você pode clicar nos pins individuais para acessar os detalhes de cada clínica."
                    },
                    {
                        element: '#filter-estado',
                        intro: "Use os filtros para selecionar um estado, cidade ou outros critérios para refinar sua busca."
                    },
                    {
                        element: '.btn-whatsapp',
                        intro: "Precisa de ajuda ou mais informações? Clique aqui para entrar em contato via WhatsApp."
                    }
                ],
                showProgress: true,
                showStepNumbers: false,
                nextLabel: "Próximo",
                prevLabel: "Voltar",
                doneLabel: "Entendi!"
            })
            .oncomplete(() => {
                localStorage.setItem('mapaClinicasGuideShown', true);

                // Destaca automaticamente o maior cluster
                const largestCluster = markers.getLayers().find(cluster => cluster._childCount > 1);
                if (largestCluster) {
                    largestCluster.openPopup();
                    setTimeout(() => largestCluster.closePopup(), 5000);
                }
            })
            .start();
    }
});

</script>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mapa de Clínicas</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.css" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css" />
    <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://unpkg.com/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        header {
            background-color: #007bff;
            color: white;
            padding: 15px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 18px;
        }

        #filter-panel {
            position: fixed;
            top: 0;
            left: 0;
            width: 300px;
            height: 100%;
            background: white;
            padding: 15px;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.2);
            border-radius: 0 10px 10px 0;
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            z-index: 1100;
        }

        #filter-panel.filter-panel-open {
            transform: translateX(0);
        }

        #map {
            flex: 1;
            height: calc(100vh - 50px);
        }

        #toggle-filter {
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1000;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 50px;
            width: 50px;
            border-radius: 50%;
            background: #28a745;
            color: white;.p
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
            cursor: pointer;
            border: none;
            font-size: 18px;
        }

        #close-filter {
            position: absolute;
            top: 10px;
            right: 10px;
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #007bff;
        }

        #results-button {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 50px;
            font-size: 16px;
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
            cursor: pointer;
            display: none;
        }

        .modal-body .clinic-item {
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 8px;
            background: #f8f9fa;
            box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
        }

        .clinic-buttons {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }

        .clinic-title {
            font-size: 16px;
            font-weight: bold;
        }

        .modal-body {
            max-height: 70vh;
            overflow-y: auto;
        }
        .filter-horizontal {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    margin: 20px 0;
}

.filter-horizontal select {
    width: 200px;
}

.filter-horizontal button {
    padding: 8px 20px;
}
@media (max-width: 768px) {
    .filter-horizontal {
        flex-wrap: wrap;
        gap: 10px;
    }

    .filter-horizontal select,
    .filter-horizontal button {
        width: 100%;
    }
}

.btn-whatsapp {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background-color: #25d366;
    color: white;
    font-size: 16px;
    font-weight: bold;
    padding: 12px 20px;
    border-radius: 50px;
    text-decoration: none;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    transition: background-color 0.3s ease;
}

.btn-whatsapp:hover {
    background-color: #1ebe5a;
    text-decoration: none;
    color: white;
}

@-webkit-keyframes marquee {
  100% {
    transform: translateX(-100%);
  }
}

@keyframes marquee {
  100% {
    transform: translateX(-100%);
  }
}

[data-marquee] {
  --loop-duration: 20s; /* Duração do loop */
  --separator: " | "; /* Separador entre mensagens */
  display: block;
  position: relative;
  width: 100%;
  background: linear-gradient(90deg, #007bff, #0056b3); /* Gradiente de fundo */
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

[data-marquee-overflow] {
  overflow: hidden;
  transform: translate3d(0, 0, 0);
}

[data-marquee-container] {
  display: flex;
  -webkit-animation: marquee var(--loop-duration) linear infinite;
  animation: marquee var(--loop-duration) linear infinite;
}

[data-marquee-style] {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;
  font-size: 1.2em;
  font-weight: bold;
  color: white; /* Cor do texto */
  text-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);
  white-space: nowrap;
}

[data-marquee-style]::after {
  content: var(--separator);
  color: #FF8B2A;
}

@media (max-width: 768px) {
  [data-marquee-container] {
    -webkit-animation-duration: 15s; /* Ajusta durao para telas menores */
    animation-duration: 15s;
  }

  [data-marquee-style] {
    font-size: 1em; /* Reduz o tamanho da fonte */
    padding: 0 10px;
  }
}

/* Acessibilidade - Parar animação para usuários com redução de movimento */
@media (prefers-reduced-motion: reduce) {
  [data-marquee-container] {
    animation: none;
  }
}

    </style>
</head>

<body>
    <header>
       <!-- Marquee -->
  <div data-marquee>
    <div data-marquee-overflow>
      <div data-marquee-container>
        <div data-marquee-style>Sua segurança em primeiro lugar! Aqui estão todas as clínicas do Brasil aprovadas e regularizadas pelos órgãos competentes.</div>
        <div data-marquee-style>Sua segurana em primeiro lugar! Aqui estão todas as clínicas do Brasil aprovadas e regularizadas pelos rgãos competentes.</div>
      </div>
    </div>
  </div>
  <script src="https://gestordesaude.com/marquee.js"></script>
  
    </header>
<div id="loading-message" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(0,0,0,0.8); color: white; padding: 20px; border-radius: 5px; z-index: 1000;">
    Carregando clínicas, por favor aguarde...
</div>


<div class="filter-horizontal" style="display: flex; justify-content: center; align-items: center; gap: 15px; margin: 20px;">
    <select id="filter-estado" class="form-select" style="width: 200px;">
        <option value="">Selecione um estado</option>
    </select>
    <select id="filter-cidade" class="form-select" style="width: 200px;">
        <option value="">Selecione uma cidade</option>
    </select>
    <select id="filter-tipo-clinica" class="form-select" style="width: 200px;">
        <option value="">Selecione o tipo</option>
    </select>
    <select id="filter-plano-saude" class="form-select" style="width: 200px;">
        <option value="">Selecione um plano</option>
    </select>
    <button id="apply-filters" class="btn btn-primary">Buscar</button>
</div>


    <!-- Mapa -->
    <div id="map"></div>

    <!-- Botão para exibir resultados -->
    <button id="results-button">Ver Resultados</button>

    <!-- Modal de Resultados -->
    <div class="modal fade" id="resultsModal" tabindex="-1" aria-labelledby="resultsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="resultsModalLabel">Resultados</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="results-list"></div>
                </div>
            </div>
        </div>
    </div>

<script>
// Inicializa o mapa
const map = L.map('map').setView([-14.235004, -51.92528], 4); // Centralizado no Brasil
const markers = L.markerClusterGroup();

// Adiciona camada de mapa
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

map.addLayer(markers);

// Funão para carregar estados, tipos e planos
async function loadFilters() {
    try {
        const estados = await fetch('https://gestordesaude.com/get_estados.php').then(res => res.json());
        const tipos = await fetch('https://gestordesaude.com/get_tipos_clinica.php').then(res => res.json());
        const planos = await fetch('https://gestordesaude.com/get_planos_saude.php').then(res => res.json());

        // Preenche os filtros no DOM
        populateSelect('filter-estado', estados);
        populateSelect('filter-tipo-clinica', tipos);
        populateSelect('filter-plano-saude', planos);
    } catch (error) {
        console.error('Erro ao carregar filtros:', error);
        showNotification('Erro ao carregar filtros. Tente novamente.', 'error');
    }
}

// Funço para carregar cidades com base no estado selecionado
document.getElementById('filter-estado').addEventListener('change', async function () {
    const estadoId = this.value;
    const cidadeSelect = document.getElementById('filter-cidade');
    cidadeSelect.innerHTML = '<option value="">Selecione uma cidade</option>';

    if (!estadoId) return;

    try {
        const cidades = await fetch(`https://gestordesaude.com/get_cidades2.php?estado=${estadoId}`).then(res => res.json());
        populateSelect('filter-cidade', cidades);
    } catch (error) {
        console.error('Erro ao carregar cidades:', error);
        showNotification('Erro ao carregar cidades. Tente novamente.', 'error');
    }
});

// Obtém o parâmetro 'ref' da URL
const urlParams = new URLSearchParams(window.location.search);
const ref = urlParams.get('ref') || '';

// Função para carregar clínicas no mapa
async function loadClinicas(filtros = {}) {
    const loadingMessage = document.getElementById('loading-message');
    loadingMessage.style.display = 'block'; // Exibe mensagem de carregamento

    try {
        const query = new URLSearchParams(filtros).toString();
        const clinicas = await fetch(`https://gestordesaude.com/get_clinicas.php?${query}`).then(res => res.json());

        markers.clearLayers();

        if (clinicas.length > 0) {
            // Adiciona as clínicas ao mapa
            clinicas.forEach(clinica => {
                if (!clinica.latitude || !clinica.longitude) return;

                // Adiciona o parâmetro ref ao link
                const clinicaLink = `https://gestordesaude.com/clinica/${clinica.slug}?ref=${ref}`;

                const marker = L.marker([clinica.latitude, clinica.longitude])
                    .bindPopup(`
                        <strong>${clinica.clinica_nome}</strong><br>
                        <a href="${clinicaLink}" target="_blank" style="color: #007bff; text-decoration: underline;">
                             Clique aqui para acessar a página da clínica 
                        </a>
                    `);
                markers.addLayer(marker);
            });

            const bounds = clinicas.map(c => [c.latitude, c.longitude]);
            map.fitBounds(bounds);
            showNotification(`${clinicas.length} clínicas encontradas! Clique nos pins para mais detalhes.`, 'info');
        } else {
            await findClosestOrCityClinics(filtros);
        }
    } catch (error) {
        console.error('Erro ao carregar clínicas:', error);
        showNotification('Erro ao carregar clínicas. Tente novamente.', 'error');
    } finally {
        loadingMessage.style.display = 'none'; // Esconde mensagem de carregamento
    }
}

// Função para calcular a distância Haversine entre dois pontos (em km)
function haversine(lat1, lon1, lat2, lon2) {
    const R = 6371; // Raio da Terra em km
    const toRad = (angle) => (angle * Math.PI) / 180;

    const dLat = toRad(lat2 - lat1);
    const dLon = toRad(lon2 - lon1);

    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
              Math.sin(dLon / 2) * Math.sin(dLon / 2);

    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c; // Retorna a distância em km
}

// Funço para encontrar clínicas na mesma cidade ou a mais próxima
async function findClosestOrCityClinics(filtros) {
    try {
        const cidadeId = filtros.cidade;

        // Obtém as coordenadas da cidade
        const cityData = await fetch(`https://gestordesaude.com/get_cidade_coords.php?cidade=${cidadeId}`).then(res => res.json());

        if (!cityData || !cityData.latitude || !cityData.longitude) {
            showNotification('Não foi possível determinar a localização desta cidade.', 'error');
            return;
        }

        const { latitude: cityLat, longitude: cityLon } = cityData;

        // Busca todas as clínicas
        const clinicas = await fetch('https://gestordesaude.com/get_clinicas.php').then(res => res.json());

        if (clinicas.length === 0) {
            showNotification('Nenhuma clínica disponível no sistema.', 'error');
            return;
        }

        // Calcula a distância para todas as clínicas
        clinicas.forEach(clinica => {
            if (!clinica.latitude || !clinica.longitude) return;

            clinica.distancia = haversine(
                parseFloat(cityLat),
                parseFloat(cityLon),
                parseFloat(clinica.latitude),
                parseFloat(clinica.longitude)
            );
        });

        // Ordena as clínicas pela distância
        const sortedClinics = clinicas.sort((a, b) => a.distancia - b.distancia);

        // Seleciona as 5 clínicas mais próximas
        const closestClinics = sortedClinics.slice(0, 5);

        if (closestClinics.length > 0) {
            // Exibe as clínicas mais próximas no mapa
            markers.clearLayers();
            closestClinics.forEach(clinica => {
                const marker = L.marker([clinica.latitude, clinica.longitude])
                    .bindPopup(`
                        <strong>${clinica.clinica_nome}</strong><br>
                        <a href="https://gestordesaude.com/clinica/${clinica.slug}" target="_blank" style="color: #007bff; text-decoration: underline;">
                            Clique aqui para acessar a página da clínica
                        </a>
                    `);
                markers.addLayer(marker);
            });

            const bounds = closestClinics.map(c => [c.latitude, c.longitude]);
            map.fitBounds(bounds);
            showNotification('Aqui estão as clínicas mais próximas de você.', 'info');
        } else {
            showNotification('Nenhuma clínica encontrada nas proximidades.', 'error');
        }
    } catch (error) {
        console.error('Erro ao buscar clínicas mais próximas:', error);
        showNotification('Erro ao buscar clínicas. Tente novamente.', 'error');
    }
}
// Função para exibir notificaçes
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.style.position = 'fixed';
    notification.style.bottom = '20px';
    notification.style.right = '20px';
    notification.style.backgroundColor = type === 'error' ? '#dc3545' : '#007bff';
    notification.style.color = '#fff';
    notification.style.padding = '15px';
    notification.style.borderRadius = '5px';
    notification.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)';
    notification.style.zIndex = '1000';
    notification.textContent = message;

    document.body.appendChild(notification);

    setTimeout(() => {
        document.body.removeChild(notification);
    }, 5000);
}

// Função para preencher selects
function populateSelect(id, data) {
    const select = document.getElementById(id);
    data.forEach(item => {
        const option = document.createElement('option');
        option.value = item.id;
        option.textContent = item.nome;
        select.appendChild(option);
    });
}

// Aplica os filtros ao clicar no botão
document.getElementById('apply-filters').addEventListener('click', () => {
    const filtros = {
        estado: document.getElementById('filter-estado').value,
        cidade: document.getElementById('filter-cidade').value,
        tipo_clinica: document.getElementById('filter-tipo-clinica').value,
        plano_saude: document.getElementById('filter-plano-saude').value,
    };

    loadClinicas(filtros);
});

// Carrega filtros e clínicas ao iniciar a pgina
document.addEventListener('DOMContentLoaded', () => {
    loadFilters();
    loadClinicas(); // Chama sem filtros para carregar todas as clínicas inicialmente
});



</script>


<a href="https://wa.me/<?php echo $whatsapp; ?>?text=Olá! Estou interessado em mais informações sobre as clínicas." 
    class="btn-whatsapp" 
    target="_blank">
    Fale com um atendente pelo WhatsApp
</a>


</body>

</html>