<?php
global $wpdb; // Глобальная переменная для работы с базой данных


// Получаем все подрубрики рубрики 740
$excluded_category_ids = array(740); // Начально включаем саму рубрику 740
$child_categories = get_term_children(740, 'category');
if (!empty($child_categories)) {
    $excluded_category_ids = array_merge($excluded_category_ids, $child_categories);
}

// Формируем часть запроса для NOT IN оператора
$excluded_category_ids_in = implode(',', array_map('intval', $excluded_category_ids));


/**
$query = $wpdb->prepare("
    SELECT DISTINCT p.ID, p.post_title, p.post_content, m.meta_value AS position
    FROM $wpdb->posts p
    INNER JOIN $wpdb->postmeta m ON p.ID = m.post_id
    LEFT JOIN $wpdb->term_relationships tr ON p.ID = tr.object_id
    LEFT JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
    WHERE p.post_type = 'post'
    AND m.meta_key = 'top_participation_position'
    AND m.meta_value != ''
    AND tt.term_id NOT IN ($excluded_category_ids_in)
    ORDER BY CAST(m.meta_value AS UNSIGNED) ASC
");
*/



/**
$query = $wpdb->prepare("
    SELECT p.ID, p.post_title, p.post_content, m.meta_value AS position
    FROM $wpdb->posts p
    INNER JOIN $wpdb->postmeta m ON p.ID = m.post_id
    WHERE p.post_type = 'post'
        AND m.meta_key = 'top_participation_position'
        AND m.meta_value != ''
    ORDER BY CAST(m.meta_value AS UNSIGNED) ASC
");*/

$excluded_category_id = 740;

// Запрос для получения всех постов с непустым метаполем 'top_participation_position'
$query = "
    SELECT DISTINCT p.ID, p.post_title, p.post_content, m.meta_value AS position
    FROM $wpdb->posts p
    INNER JOIN $wpdb->postmeta m ON p.ID = m.post_id
    WHERE p.post_type = 'post'
    AND m.meta_key = 'top_participation_position'
    AND m.meta_value != ''
    ORDER BY CAST(m.meta_value AS UNSIGNED) ASC
";

$top_posts = $wpdb->get_results($query);

if (!empty($top_posts)) {
    
    foreach ($top_posts as $post) {
        // Проверка наличия категории или подкатегории с ID 740
        $terms = wp_get_post_terms($post->ID, 'category');
        $exclude = false;
        foreach ($terms as $term) {
            if ($term->term_id == $excluded_category_id || $term->parent == $excluded_category_id) {
                $exclude = true;
                break;
            }
        }

        if (!$exclude) {
        
            $permalink = get_permalink($post->ID);
            $title = get_the_title($post->ID);?>

            <div class="most-read__link">
                <a href="<?php echo esc_url($permalink); ?>" class="most-read__link-inner text-13 link-icon-after">
                    <?php echo esc_html($title); ?>
                </a>
            </div>
    
        <?} 
    
    }?>  

    <div class="allnews-container">
        <a href="https://agroexpert.press/all-events/" class="allnews">
            Все новости
        </a>
    </div>

<?}?>        
