<?php
// Configurações de conexão ao banco de dados
$host = 'localhost';
$db = 'digupdog_FEED';
$user = 'digupdog_FEEDadmin';
$pass = 'Raimundinho1';
$charset = 'utf8mb4';

// DSN para PDO
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Erro ao conectar com o banco de dados: " . $e->getMessage());
}

// Função otimizada para verificar feeds com melhor controle de redirecionamento e códigos HTTP
function check_feed($website) {
    $feed_urls = [
        "/rss", "/rss/", "/feed", "/feed/", "/atom", "/atom/",
        "/feeds/posts/default", "/feeds/posts/default/",
        "/index.rss", "/index.rss/", "/index.atom", "/index.atom/",
        "/rss.xml", "/rss.xml/", "/feed.xml", "/feed.xml/",
        "/feed/atom", "/feed/atom/", "/feed/rss", "/feed/rss/",
        "/blog/rss", "/blog/feed", "/news/rss", "/news/feed",
        "/podcast/rss", "/podcast/feed",
        "/rss/wikis/feed", "/rss/v2/videos/feed", "/rss/v2/articles/feed",
        "/rss/v1/articles", "/rss/v1/news", "/rss/v1/blogs", "/rss/v2/blogs/feed",
        "/api/rss", "/api/v1/rss", "/api/v2/rss", "/rss/v3/feed", "/rss/latest",
        "/articles/rss", "/articles/feed", "/news/rss", "/news/feed", "/updates/rss", "/updates/feed",
        "/index.php?title=Special:RecentChanges&feed=atom",  // Padrão MediaWiki
        "/feeds/posts/default?alt=rss",  // Padrão Blogger com parâmetro
        "/feeds/posts/default?alt=atom", // Variação com Atom
        "/?feed=rss", "/?feed=atom", "/?feed=rss2", "/?alt=rss", "/?alt=atom"
    ];

    $userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";

    // Inicializar cURL multi para requisições paralelas
    $multiHandle = curl_multi_init();
    $curlHandles = [];
    $feedResults = [];

    foreach ($feed_urls as $feed_url) {
        $url = rtrim($website, '/') . $feed_url;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  // Seguir redirecionamentos
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
        curl_multi_add_handle($multiHandle, $ch);
        $curlHandles[$url] = $ch; // Associar URL ao handle
    }

    // Executar todas as requisições cURL ao mesmo tempo
    do {
        $status = curl_multi_exec($multiHandle, $active);
        curl_multi_select($multiHandle);
    } while ($active && $status == CURLM_OK);

    // Processar as respostas
    foreach ($curlHandles as $url => $ch) {
        $response = curl_multi_getcontent($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // Verificar códigos de redirecionamento e seguir a nova URL
        if ($http_code == 301 || $http_code == 302) {
            $new_url = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
            if ($new_url) {
                curl_setopt($ch, CURLOPT_URL, $new_url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                $response = curl_exec($ch);
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            }
        }

        // Verificar se o feed foi encontrado
        if ($http_code == 200 && $response) {
            if (strpos($response, '<rss') !== false || strpos($response, '<feed') !== false || strpos($response, '<channel') !== false) {
                $feedResults[] = ['status' => 1, 'feed' => $url]; // Feed encontrado
            }
        }
        curl_multi_remove_handle($multiHandle, $ch);
        curl_close($ch);
    }

    curl_multi_close($multiHandle);

    // Se algum feed foi encontrado, retornar o primeiro encontrado
    if (!empty($feedResults)) {
        return $feedResults[0];
    }

    // Se nenhum feed foi encontrado
    return ['status' => 2, 'feed' => 'Non existent'];
}


// Função auxiliar para gerar URLs customizados com variações HTTP e HTTPS
function add_http_https_variations($website, $feed_urls) {
    $parsedUrl = parse_url($website);

    // Gerar variações com http e https
    $http_variations = [
        "http://", 
        "https://"
    ];

    foreach ($http_variations as $protocol) {
        foreach ($feed_urls as $feed) {
            $feed_urls[] = $protocol . ltrim($parsedUrl['host'], '/') . $feed;
        }
    }

    return $feed_urls;
}

// Função para verificar se o feed foi armazenado em cache
function check_cache($website) {
    // Verificar cache temporário ou banco de dados
    // Exemplo fictício: arquivo ou tabela de cache
    $cache_file = '/path/to/cache/' . md5($website) . '.cache';
    if (file_exists($cache_file)) {
        return json_decode(file_get_contents($cache_file), true);
    }
    return null;
}

// Função para salvar no cache
function save_to_cache($website, $feed_url) {
    // Exemplo fictício de cache usando arquivo
    $cache_file = '/path/to/cache/' . md5($website) . '.cache';
    file_put_contents($cache_file, json_encode(['status' => 1, 'feed' => $feed_url]));
}

// Função auxiliar para extrair feeds de <link rel="alternate" type="application/rss+xml"> no HTML
function extract_feed_from_html($html) {
    preg_match_all('/<link[^>]+rel="alternate"[^>]+type="application\/rss\+xml"[^>]+href="([^"]+)"/i', $html, $matches);
    return $matches[1][0] ?? null;
}


// Função auxiliar para gerar URLs de feeds customizados (mais abrangente)
function generate_custom_feed_urls($website) {
    $parsedUrl = parse_url($website);
    $customUrls = [];

    // Gerar subdomínios comuns para feeds
    $subdomains = ['www', 'blog', 'news', 'podcast', 'media', 'content'];
    foreach ($subdomains as $subdomain) {
        $customUrls[] = "https://$subdomain." . $parsedUrl['host'] . "/feed";
        $customUrls[] = "https://$subdomain." . $parsedUrl['host'] . "/rss";
    }

    // Adicionar feeds customizados com diferentes versões e estruturas de APIs
    $paths = ["/rss/v1/", "/rss/v2/", "/rss/v3/", "/api/rss/", "/feeds/rss/", "/feeds/atom/"];
    foreach ($paths as $path) {
        $customUrls[] = "https://" . $parsedUrl['host'] . $path;
        $customUrls[] = "https://" . $parsedUrl['host'] . $path . "feed";
    }

    return $customUrls;
}



function save_to_temp_file($config, $links, $batch_size = 5) {
    $temp_dir = '/path/to/temp/';  // Diretório onde serão armazenados os arquivos temporários
    $filename = $temp_dir . md5(serialize($config)) . '.tmp';

    // Abrir o arquivo temporário e gravar a configuração e os links a serem processados
    $file_content = json_encode([
        'config' => $config,
        'links' => $links,
        'batch_size' => $batch_size,
        'current_batch' => 0,  // Indica o primeiro lote a ser processado
    ]);

    file_put_contents($filename, $file_content);
    return $filename;
}


function load_and_process_batch($temp_file) {
    // Carregar o arquivo temporário
    if (!file_exists($temp_file)) {
        die('Arquivo temporário não encontrado.');
    }

    $data = json_decode(file_get_contents($temp_file), true);
    $links = $data['links'];
    $batch_size = $data['batch_size'];
    $current_batch = $data['current_batch'];

    // Definir o lote atual a ser processado
    $batch_links = array_slice($links, $current_batch * $batch_size, $batch_size);

    // Processar os links do lote atual
    foreach ($batch_links as $link) {
        // Aqui vai sua lógica de processamento
        echo "Processando: " . $link . "\n";
    }

    // Atualizar o progresso do lote
    $data['current_batch'] += 1;
    file_put_contents($temp_file, json_encode($data));

    // Verificar se ainda há mais lotes para processar
    if (($current_batch + 1) * $batch_size < count($links)) {
        return "Ainda há mais lotes para processar.";
    } else {
        unlink($temp_file);  // Deletar o arquivo temporário quando todos os lotes forem processados
        return "Processamento completo.";
    }
}


// Função para validar entradas de formulário
function sanitize_input($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// Se o formulário de verificação de feeds foi enviado
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $selected_websites = $_POST['websites'] ?? []; // Websites selecionados
    $process_limit = sanitize_input($_POST['process_limit'] ?? 'all'); // Limite de websites a serem processados ('all' ou número)

    // Se "all" for selecionado, processa todos os websites selecionados
    if ($process_limit === 'all') {
        $websites_to_check = $selected_websites;
    } else {
        $websites_to_check = array_slice($selected_websites, 0, (int)$process_limit);
    }

    foreach ($websites_to_check as $website_id) {
        $stmt = $pdo->prepare("SELECT website_base, feeds_rss_atom FROM feed_data WHERE id = ?");
        $stmt->execute([$website_id]);
        $row = $stmt->fetch();

        if ($row) {
            // Verifica se o feed já foi checado
            if ($row["feeds_rss_atom"] === null || $row["feeds_rss_atom"] == "Not checked") {
                $feed_result = check_feed($row["website_base"]);
                $status = $feed_result['status'];
                $feed_url = $feed_result['feed'];

                // Atualizar a tabela com o resultado da verificação na coluna feeds_rss_atom
                $stmt_update = $pdo->prepare("UPDATE feed_data SET status_feed = ?, feeds_rss_atom = ?, check_date = NOW() WHERE id = ?");
                $stmt_update->execute([$status, $feed_url, $website_id]);

                // Adicionar ao array de resultados para exibição
                $results[] = [
                    'id' => $website_id,
                    'website' => $row["website_base"],
                    'feed' => $feed_url
                ];
            } else {
                // Se o feed já foi checado antes, usar o valor existente
                $results[] = [
                    'id' => $website_id,
                    'website' => $row["website_base"],
                    'feed' => $row["feeds_rss_atom"] ? $row["feeds_rss_atom"] : "Not checked"
                ];
            }
        }
    }
}

// Variáveis de busca, limite e paginação
$search = sanitize_input($_GET['search'] ?? ''); // Valor de busca
$limit = (int)(sanitize_input($_GET['limit'] ?? 10)); // Quantidade de resultados por página
$page = (int)(sanitize_input($_GET['page'] ?? 1)); // Página atual
$status_filter = sanitize_input($_GET['status'] ?? 'all'); // Filtro de status selecionado
$order_by = sanitize_input($_GET['order'] ?? 'latest'); // Ordem de exibição
$offset = ($page - 1) * $limit; // Cálculo do offset

// Lógica de contagem otimizada para mostrar status atual do progresso
$count_query = "SELECT 
    COUNT(*) AS total, 
    SUM(CASE WHEN status_feed IN (1, 2) THEN 1 ELSE 0 END) AS checked,
    SUM(CASE WHEN status_feed = 1 THEN 1 ELSE 0 END) AS existent,
    SUM(CASE WHEN status_feed = 2 THEN 1 ELSE 0 END) AS non_existent,
    SUM(CASE WHEN status_feed = 3 THEN 1 ELSE 0 END) AS not_checked
FROM feed_data";

$count_data = $pdo->query($count_query)->fetch();

$count_all = $count_data['total'];
$count_checked = $count_data['checked'];
$count_existent = $count_data['existent'];
$count_non_existent = $count_data['non_existent'];
$count_not_checked = $count_data['not_checked'];

// Calcular o percentual de progresso
$total_checked = $count_existent + $count_non_existent; // Contando apenas os feeds verificados (existentes ou não)
$progress_percentage = ($total_checked / $count_all) * 100; // Correção no cálculo do progresso

// Condições de filtro de status
$status_condition = '';
if ($status_filter === 'checked') {
    $status_condition = " AND status_feed IN (1, 2)"; // Feeds já checados
} elseif ($status_filter === 'not_checked') {
    $status_condition = " AND status_feed = 3"; // Feeds não checados
} elseif ($status_filter === 'existent') {
    $status_condition = " AND status_feed = 1"; // Feeds existentes
} elseif ($status_filter === 'non_existent') {
    $status_condition = " AND status_feed = 2"; // Feeds não existentes
}

// Ordenação por data ou ID
if ($order_by == 'oldest') {
    $order_clause = 'ORDER BY check_date ASC';
} elseif ($order_by == 'latest') {
    $order_clause = 'ORDER BY check_date DESC';
} elseif ($order_by == 'id_asc') {
    $order_clause = 'ORDER BY id ASC'; // Ordenar por IDs menores primeiro
} elseif ($order_by == 'id_desc') {
    $order_clause = 'ORDER BY id DESC'; // Ordenar por IDs maiores primeiro
}

// Consulta SQL para buscar os websites com base na pesquisa e filtro
$query = "SELECT COUNT(*) FROM feed_data WHERE is_active = 1 AND website_base LIKE ?" . $status_condition;
$stmt = $pdo->prepare($query);
$stmt->execute(['%' . $search . '%']);
$total_results = $stmt->fetchColumn();

// Consulta SQL para buscar os websites, com limite e paginação
$query = "SELECT id, website_base, status_feed, check_date FROM feed_data WHERE is_active = 1 AND website_base LIKE ?" . $status_condition . " $order_clause LIMIT ? OFFSET ?";
$stmt = $pdo->prepare($query);
$stmt->execute(['%' . $search . '%', $limit, $offset]);
$websites = $stmt->fetchAll();

// Calcular o número total de páginas
$total_pages = ceil($total_results / $limit);

// Função para renderizar a paginação com limites de exibição
function render_pagination($page, $total_pages, $search, $limit, $status_filter, $order_by) {
    $range = 1; // Número de páginas visíveis ao redor da página atual

    $html = '<nav aria-label="Pagination" class="d-flex justify-content-center">';
    $html .= '<ul class="pagination pagination-modern">';

    // Botão anterior com ícone
    if ($page > 1) {
        $html .= '<li class="page-item"><a class="page-link" href="?search=' . $search . '&limit=' . $limit . '&status=' . $status_filter . '&order=' . $order_by . '&page=' . ($page - 1) . '">&laquo;</a></li>';
    } else {
        $html .= '<li class="page-item disabled"><span class="page-link">&laquo;</span></li>';
    }

    // Mostrar sempre a primeira página
    if ($page > $range + 1) {
        $html .= '<li class="page-item"><a class="page-link" href="?search=' . $search . '&limit=' . $limit . '&status=' . $status_filter . '&order=' . $order_by . '&page=1">1</a></li>';
        $html .= '<li class="page-item disabled"><span class="page-link">...</span></li>'; // Mostrar elipses se houver mais páginas
    }

    // Definir intervalo de páginas visíveis ao redor da página atual
    $start = max(1, $page - $range);
    $end = min($total_pages, $page + $range);

    // Renderizar os números de página visíveis
    for ($i = $start; $i <= $end; $i++) {
        $active = $i == $page ? 'active' : '';
        $html .= '<li class="page-item ' . $active . '"><a class="page-link" href="?search=' . $search . '&limit=' . $limit . '&status=' . $status_filter . '&order=' . $order_by . '&page=' . $i . '">' . $i . '</a></li>';
    }

    // Mostrar sempre a última página
    if ($end < $total_pages) {
        $html .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        $html .= '<li class="page-item"><a class="page-link" href="?search=' . $search . '&limit=' . $limit . '&status=' . $status_filter . '&order=' . $order_by . '&page=' . $total_pages . '">' . $total_pages . '</a></li>';
    }

    // Botão próximo com ícone
    if ($page < $total_pages) {
        $html .= '<li class="page-item"><a class="page-link" href="?search=' . $search . '&limit=' . $limit . '&status=' . $status_filter . '&order=' . $order_by . '&page=' . ($page + 1) . '">&raquo;</a></li>';
    } else {
        $html .= '<li class="page-item disabled"><span class="page-link">&raquo;</span></li>';
    }

    $html .= '</ul></nav>';
    return $html;
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RSS/Atom Feed Verification</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        /* General styles */
        body {
            font-family: Arial, sans-serif;
        }

        .container-card {
            margin-top: 20px;
        }

        /* Card styles */
        .card {
            border: 1px solid #e1e1e1;
            border-radius: 8px;
            margin-bottom: 10px;
            padding: 5px;
            background-color: #f9f9f9;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
            width: 100%;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
        }

        /* Responsive layout for cards */
        .cards-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            justify-content: space-around;
        }

        .card-body {
            padding: 5px;
        }

        .card-title {
            font-size: 1.25rem;
            margin-bottom: 15px;
            color: #007bff;
        }

        .progress-bar {
            margin-top: 10px;
            background-color: #007bff;
        }

        /* Color-coded feed statuses */
        .result-found {
            border-left: 5px solid #28a745;
            background-color: #d4edda;
        }

        .result-not-found {
            border-left: 5px solid #dc3545;
            background-color: #f8d7da;
        }

        /* Responsive layout adjustments */
        @media (max-width: 1200px) {
            .card {
                flex: 1 1 30%;
            }
        }

        @media (max-width: 768px) {
            .card {
                flex: 1 1 45%;
            }
        }

        @media (max-width: 576px) {
            .card {
                flex: 1 1 100%;
            }
        }

        /* Loading spinner styles */
        .loading {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            z-index: 9999;
        }

        .loading .spinner-border {
            width: 4rem;
            height: 4rem;
            border-width: 6px;
            color: #007bff;
        }
        
        
        
/* Suavizando as transições */
.progress-bar-smooth {
    transition: width 0.8s ease-in-out, background-color 0.6s ease-in-out, box-shadow 0.6s ease;
}

/* Listras suaves, menos intensas */
.progress-bar-striped {
    background-size: 1rem 1rem;
    animation: progress-bar-stripes 2s linear infinite;
}

/* Melhorias gerais da progress bar */
.progress {
    background-color: #f0f0f0 !important; /* Cor de fundo mais clara e moderna */
    border-radius: 12px;
    height: 35px;
    padding: 0; /* Remover o padding interno */
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1); /* Sombra interna sutil */
    overflow: hidden; /* Garantir que o conteúdo não extrapole a barra */
}

/* Melhorias nas barras de progresso */
.progress-bar {
    border-radius: 12px;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    text-shadow: none; /* Remover sombra no texto */
    color: black; /* Cor preta no texto */
    height: 100%; /* Assegura que o preenchimento cubra toda a altura */
    margin: 0; /* Remover possíveis margens */
    padding: 0; /* Remover padding */
    white-space: nowrap; /* Evitar quebra de linha dentro da barra */
    text-overflow: ellipsis; /* Adicionar reticências se o texto for muito longo */
    overflow: hidden; /* Prevenir que o texto ultrapasse a barra */
    font-size: 0.9rem; /* Reduzir o tamanho da fonte para caber melhor */
}

/* Estilizando transições suaves */
.progress-bar-animated {
    animation: progress-bar-stripes 2s linear infinite;
}

/* Gradiente e sombras modernas */
.progress-bar.bg-primary {
    background: linear-gradient(90deg, #007bff, #0056b3);
    box-shadow: 0 4px 10px rgba(0, 123, 255, 0.3);
}

.progress-bar.bg-success {
    background: linear-gradient(90deg, #28a745, #1e7e34);
    box-shadow: 0 4px 10px rgba(40, 167, 69, 0.3);
}

.progress-bar.bg-danger {
    background: linear-gradient(90deg, #dc3545, #bd2130);
    box-shadow: 0 4px 10px rgba(220, 53, 69, 0.3);
}

.progress-bar.bg-warning {
    background: linear-gradient(90deg, #ffc107, #e0a800);
    box-shadow: 0 4px 10px rgba(255, 193, 7, 0.3);
}

/* Melhora na animação das listras */
@keyframes progress-bar-stripes {
    0% {
        background-position: 1rem 0;
    }
    100% {
        background-position: 0 0;
    }
}

/* Efeitos de sombra */
.progress-bar {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}


.pagination-modern {
    padding: 0;
    margin: 0;
    display: flex;
    justify-content: center;
    list-style: none;
    gap: 0.5rem;
}

.pagination-modern .page-item {
    border-radius: 5px;
}

.pagination-modern .page-link {
    display: block;
    padding: 0.5rem 0.75rem;
    border: 1px solid #ddd;
    color: #007bff;
    text-decoration: none;
    font-size: 1rem;
    transition: background-color 0.3s ease;
}

.pagination-modern .page-link:hover {
    background-color: #f0f0f0;
    border-color: #ccc;
}

.pagination-modern .page-item.active .page-link {
    background-color: #007bff;
    color: white;
    border-color: #007bff;
}

.pagination-modern .page-item.disabled .page-link {
    color: #6c757d;
    pointer-events: none;
    background-color: #e9ecef;
    border-color: #dee2e6;
}

/* Responsividade: estilo compacto para dispositivos móveis */
@media (max-width: 768px) {
    .pagination-modern .page-link {
        padding: 0.4rem 0.6rem;
        font-size: 0.875rem;
    }

    .pagination-modern {
        gap: 0.3rem;
    }
}

        /* Iframe style */
        .iframe-container {
            margin-top: 20px;
            width: 100%;
            height: 500px;
            border: 1px solid #ccc;
            border-radius: 8px;
        }
    </style>
</head>
<body>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-lg-10 col-md-12">
            <div class="card container-card">
                <div class="card-header text-center bg-primary text-white">
                    <h1>RSS/Atom Feed Verification</h1>
                </div>
                <div class="card-body">

                <!-- Adicionando o iframe monitor -->
                <div class="iframe-container">
                    <iframe id="monitorFrame" src="about:blank" width="100%" height="100%"></iframe>
                </div>

<!-- Barra de Progresso Geral -->
<h5>Progresso Geral</h5>
<div class="progress mb-4" style="height: 40px; background-color: #f0f0f0; border-radius: 8px; position: relative;">
    <div class="progress-bar bg-primary progress-bar-smooth" role="progressbar"
         style="width: <?php echo $progress_percentage; ?>%; height: 100%; transition: width 0.8s ease;">
    </div>
    <span style="position: absolute; width: 100%; text-align: center; line-height: 40px; font-size: 1.5rem; font-weight: bold; color: <?php echo $progress_percentage > 20 ? '#ffffff' : '#000000'; ?>;">
        <?php echo round($progress_percentage); ?>% (<?php echo $total_checked; ?> / <?php echo $count_all; ?> feeds verificados)
    </span>
</div>

<!-- Feeds Existentes -->
<div class="progress mb-2" style="height: 40px; background-color: #f0f0f0; border-radius: 8px; position: relative;">
    <div class="progress-bar bg-success progress-bar-smooth" role="progressbar"
         style="width: <?php echo ($count_existent / $count_all) * 100; ?>%; height: 100%; transition: width 0.8s ease;">
    </div>
    <span style="position: absolute; width: 100%; text-align: center; line-height: 40px; font-size: 1.5rem; font-weight: bold; color: <?php echo ($count_existent / $count_all) * 100 > 20 ? '#ffffff' : '#000000'; ?>;">
        Feeds Existentes: <?php echo $count_existent; ?> (<?php echo round(($count_existent / $count_all) * 100); ?>%)
    </span>
</div>

<!-- Feeds Não Existentes -->
<div class="progress mb-2" style="height: 40px; background-color: #f0f0f0; border-radius: 8px; position: relative;">
    <div class="progress-bar bg-danger progress-bar-smooth" role="progressbar"
         style="width: <?php echo ($count_non_existent / $count_all) * 100; ?>%; height: 100%; transition: width 0.8s ease;">
    </div>
    <span style="position: absolute; width: 100%; text-align: center; line-height: 40px; font-size: 1.5rem; font-weight: bold; color: <?php echo ($count_non_existent / $count_all) * 100 > 20 ? '#ffffff' : '#000000'; ?>;">
        Feeds Não Existentes: <?php echo $count_non_existent; ?> (<?php echo round(($count_non_existent / $count_all) * 100); ?>%)
    </span>
</div>

<!-- Feeds Não Verificados -->
<div class="progress mb-4" style="height: 40px; background-color: #f0f0f0; border-radius: 8px; position: relative;">
    <div class="progress-bar bg-warning progress-bar-smooth" role="progressbar"
         style="width: <?php echo ($count_not_checked / $count_all) * 100; ?>%; height: 100%; transition: width 0.8s ease;">
    </div>
    <span style="position: absolute; width: 100%; text-align: center; line-height: 40px; font-size: 1.5rem; font-weight: bold; color: <?php echo ($count_not_checked / $count_all) * 100 > 20 ? '#ffffff' : '#000000'; ?>;">
        Feeds Não Verificados: <?php echo $count_not_checked; ?> (<?php echo round(($count_not_checked / $count_all) * 100); ?>%)
    </span>
</div>

                    <!-- Search and filter form -->
                    <form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="mb-4">
                        <div class="row g-3">
                            <div class="col-md-3">
                                <input type="text" name="search" class="form-control" placeholder="Search by website" value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                            <div class="col-md-3">
                                <select name="status" class="form-select">
                                    <option value="all" <?php if ($status_filter == 'all') echo 'selected'; ?>>All (<?php echo $count_all; ?>)</option>
                                    <option value="checked" <?php if ($status_filter == 'checked') echo 'selected'; ?>>Checked (<?php echo $count_checked; ?>)</option>
                                    <option value="not_checked" <?php if ($status_filter == 'not_checked') echo 'selected'; ?>>Not Checked (<?php echo $count_not_checked; ?>)</option>
                                    <option value="existent" <?php if ($status_filter == 'existent') echo 'selected'; ?>>Existent (<?php echo $count_existent; ?>)</option>
                                    <option value="non_existent" <?php if ($status_filter == 'non_existent') echo 'selected'; ?>>Non-existent (<?php echo $count_non_existent; ?>)</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <select name="order" class="form-select">
                                    <option value="latest" <?php if ($order_by == 'latest') echo 'selected'; ?>>Latest</option>
                                    <option value="oldest" <?php if ($order_by == 'oldest') echo 'selected'; ?>>Oldest</option>
                                    <option value="id_asc" <?php if ($order_by == 'id_asc') echo 'selected'; ?>>Smallest ID</option>
                                    <option value="id_desc" <?php if ($order_by == 'id_desc') echo 'selected'; ?>>Largest ID</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <input type="number" name="limit" class="form-control" value="<?php echo $limit; ?>" min="1" max="100">
                            </div>
                            <div class="col-md-1">
                                <button type="submit" class="btn btn-primary w-100">Filter</button>
                            </div>
                        </div>
                    </form>

                    <!-- Selection form -->
                    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="showLoading()">
                        <h5>Select websites for verification</h5>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="selectAll" onclick="toggleSelectAll(this)">
                            <label class="form-check-label" for="selectAll">Select All</label>
                        </div>

                        <div class="cards-container">
                            <?php foreach ($websites as $row): ?>
                                <div class="card <?php echo ($row['status_feed'] == 1) ? 'result-found' : (($row['status_feed'] == 2) ? 'result-not-found' : ''); ?>">
                                    <div class="card-body">
                                        <h5 class="card-title">
                                            <input type="checkbox" class="form-check-input website-checkbox" name="websites[]" value="<?php echo $row['id']; ?>"> Website ID: <?php echo $row['id']; ?>
                                        </h5>
                                        <p class="card-text">
                                            Website: <a href="<?php echo $row['website_base']; ?>" target="_blank"><?php echo $row['website_base']; ?></a><br>
                                            Status: <?php 
                                                if ($row['status_feed'] == 1) {
                                                    echo "Existent";
                                                } elseif ($row['status_feed'] == 2) {
                                                    echo "Non-existent";
                                                } else {
                                                    echo "Not Checked";
                                                }
                                            ?><br>
                                            Last Checked: <?php echo $row['check_date'] ? date('d/m/Y H:i', strtotime($row['check_date'])) : "Not Verified"; ?>
                                        </p>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Compact pagination -->
                        <?php echo render_pagination($page, $total_pages, $search, $limit, $status_filter, $order_by); ?>

                        <button type="submit" class="btn btn-primary mt-3 w-100">Check Feeds</button>
                    </form>

                    <!-- Loading indicator -->
                    <div id="loading" class="loading">
                        <div class="spinner-border" role="status"></div>
                    </div>

                    <!-- Verification results -->
                    <?php if (!empty($results)): ?>
                        <h5 class="mt-5">Verification Results</h5>
                        <div class="cards-container">
                            <?php foreach ($results as $result): ?>
                                <div class="card <?php echo $result['feed'] !== 'Non existent' ? 'result-found' : 'result-not-found'; ?>">
                                    <div class="card-body">
                                        <h5 class="card-title">Website ID: <?php echo $result['id']; ?></h5>
                                        <p class="card-text">
                                            Website: <a href="<?php echo $result['website']; ?>" target="_blank"><?php echo $result['website']; ?></a><br>
                                            Feed: <?php echo $result['feed'] !== 'Non existent' ? "<a href='{$result['feed']}' target='_blank'>{$result['feed']}</a>" : "No feed found"; ?>
                                        </p>
                                        <!-- Adicionando botão para exibir o site no iframe -->
                                        <button class="btn btn-info" onclick="showInIframe('<?php echo $result['website']; ?>')">Ver no iframe</button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Show loading indicator
    function showLoading() {
        document.getElementById("loading").style.display = "block";
    }

    // Toggle select all checkboxes
    function toggleSelectAll(source) {
        let checkboxes = document.querySelectorAll('.website-checkbox');
        checkboxes.forEach(checkbox => checkbox.checked = source.checked);
    }

    // Select a predefined number of checkboxes
    function selectQuantity(quantity) {
        let checkboxes = document.querySelectorAll('.website-checkbox');
        checkboxes.forEach((checkbox, index) => checkbox.checked = index < quantity);
    }

    // Mostrar o site no iframe
    function showInIframe(url) {
        document.getElementById("monitorFrame").src = url;
    }
</script>
</body>
</html>