/* no se esta ordenado por la cantidad de like en el top semanal o mensual  

asi funciona los likes

function manejarLike() {
    if (!is_user_logged_in()) {
        echo 'not_logged_in';
        wp_die();
    }

    $userId = get_current_user_id();
    $postId = $_POST['post_id'] ?? '';
    $likeEstado = $_POST['like_state'] ?? false;


    if (empty($postId)) {
        echo 'error';
        wp_die();
    }

    $accion = $likeEstado ? 'like' : 'unlike';
    likeAccion($postId, $userId, $accion);
    $contadorLike = contarLike($postId);
    echo $contadorLike;
    wp_die();
}

add_action('wp_ajax_like', 'manejarLike');


function likeAccion($postId, $userId, $accion) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'post_likes';

    if ($accion === 'like') {
        if (chequearLike($postId, $userId)) {
            $accion = 'unlike';  
        } else {
            $insert_result = $wpdb->insert($table_name, ['user_id' => $userId, 'post_id' => $postId]);
            if ($insert_result === false) {
            } else {
                
                $autorId = get_post_field('post_author', $postId);
                
                if ($autorId != $userId) {
                    $usuario = get_userdata($userId);
                    
                }
            }
        }
    }

    if ($accion === 'unlike') {
        $delete_result = $wpdb->delete($table_name, ['user_id' => $userId, 'post_id' => $postId]);
        if ($delete_result === false) {
        } else {
        }
    }
}


*/

function construirQueryArgs($args, $paged, $current_user_id, $identifier, $is_admin, $posts, $filtroTiempo, $similar_to) {
    global $wpdb;
    $likes_table = $wpdb->prefix . 'post_likes';
    $query_args = [];

    // Configuración base
    $query_args = [
        'post_type' => $args['post_type'],
        'posts_per_page' => $posts,
        'paged' => $paged,
        'ignore_sticky_posts' => true,
    ];

    // Manejar diferentes tipos de ordenamiento
    if ($args['post_type'] === 'social_post') {
        switch ($filtroTiempo) {
            case 1: // Posts recientes
                $query_args['orderby'] = 'date';
                $query_args['order'] = 'DESC';
                break;

            case 2: // Top semanal
            case 3: // Top mensual
                $interval = ($filtroTiempo === 2) ? '1 WEEK' : '1 MONTH';
                
                // Obtener posts ordenados por likes en el período
                $posts_with_likes = $wpdb->get_results($wpdb->prepare("
                    SELECT p.ID, COUNT(pl.post_id) as like_count 
                    FROM {$wpdb->posts} p 
                    LEFT JOIN {$likes_table} pl ON p.ID = pl.post_id 
                    WHERE p.post_type = %s
                    AND p.post_status = 'publish'
                    AND pl.like_date >= DATE_SUB(NOW(), INTERVAL %s)
                    GROUP BY p.ID
                    ORDER BY like_count DESC, p.post_date DESC
                    LIMIT %d
            ", 'social_post', $interval, $posts * $paged), ARRAY_A);
            

                if (!empty($posts_with_likes)) {
                    $post_ids = wp_list_pluck($posts_with_likes, 'ID');
                    $query_args['post__in'] = $post_ids;
                    $query_args['orderby'] = 'post__in';
                }
                break;

            default:
                $personalized_feed = obtenerFeedPersonalizado($current_user_id, $identifier, $similar_to, $paged, $is_admin, $posts);
                if (!empty($personalized_feed['post_ids'])) {
                    $query_args['post__in'] = $personalized_feed['post_ids'];
                    $query_args['orderby'] = 'post__in';
                }
                if (!empty($personalized_feed['post_not_in'])) {
                    $query_args['post__not_in'] = array_unique($personalized_feed['post_not_in']);
                }
                break;
        }
    }

    return $query_args;
}