<?php

namespace FleekDash\Core\Search;

/**
 * Incremental search indexing
 *
 * Handles background/cron-based incremental indexing for recently
 * modified content without rebuilding entire index.
 *
 * @package FleekDash\Core\Search
 * @since 2.2.0
 */
class SearchIncrementalIndexer
{
    /**
     * Index recently modified posts
     *
     * @param object $manager        SearchIndexManager instance for single indexing
     * @param int    $since_timestamp Unix timestamp to index from
     * @return int Number of posts indexed
     */
    public static function indexRecentPosts($manager, $since_timestamp)
    {
        global $wpdb;

        $posts = $wpdb->get_results($wpdb->prepare("
            SELECT ID FROM {$wpdb->posts}
            WHERE post_status = 'publish'
            AND post_modified_gmt > %s
            ORDER BY post_modified_gmt DESC
            LIMIT 100
        ", gmdate('Y-m-d H:i:s', $since_timestamp)));

        $count = 0;
        foreach ($posts as $post) {
            $manager->indexSinglePost($post->ID);
            $count++;
        }

        return $count;
    }

    /**
     * Index recently registered users
     *
     * @param object $manager        SearchIndexManager instance for single indexing
     * @param int    $since_timestamp Unix timestamp to index from
     * @return int Number of users indexed
     */
    public static function indexRecentUsers($manager, $since_timestamp)
    {
        global $wpdb;

        $users = $wpdb->get_results($wpdb->prepare("
            SELECT ID FROM {$wpdb->users}
            WHERE user_registered > %s
            ORDER BY user_registered DESC
            LIMIT 50
        ", gmdate('Y-m-d H:i:s', $since_timestamp)));

        $count = 0;
        foreach ($users as $user) {
            $manager->indexSingleUser($user->ID);
            $count++;
        }

        return $count;
    }

    /**
     * Index recent menus
     *
     * Legacy method kept for backward compatibility.
     * Menus don't have timestamps, so this rebuilds the entire menu index.
     *
     * @param object $manager SearchIndexManager instance
     * @return int Number of menu items indexed
     */
    public static function indexRecentMenus()
    {
        // Legacy method kept for backward compatibility. Use rebuild_menu_index instead.
        return SearchIndexBuilder::rebuildMenuIndex();
    }
}

