<?php
/**
 * Cache Cleanup Service
 *
 * Manages daily cleanup of expired transients and lightweight caches.
 * Runs scheduled cleanup for analytics, discovery caches, and stats.
 *
 * @package FleekDash V2
 * @since 2.2.0
 */

namespace FleekDash\Core;

defined('ABSPATH') || exit;

// Load debug helpers
if (!function_exists('fleekdash_log_error')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

class CacheCleanup
{
    /**
     * Run daily cleanup of expired transients and lightweight caches
     *
     * @return void
     */
    public static function runDailyCleanup()
    {
        global $wpdb;

        // 1) Analytics cache service: cleanup expired entries
        try {
            $analyticsCache = new \FleekDash\Services\AnalyticsCacheService();
            $analyticsCache->cleanup_expired_cache();
        } catch (\Throwable $e) {
            fleekdash_log_error('FleekDash: Analytics cleanup error: ' . $e->getMessage());
        }

        // Helper to cleanup expired transients for a given key prefix
        $cleanup_prefix = function ($prefix) use ($wpdb) {
            $now = time();
            // Remove expired timeouts for this prefix
            $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM {$wpdb->options}
                     WHERE option_name LIKE %s
                     AND CAST(option_value AS UNSIGNED) < %d",
                    '_transient_timeout_' . $prefix . '%',
                    $now,
                ),
            );
            // Remove orphan values without matching timeout rows
            // Use derived table to avoid MySQL "can't specify target table for update in FROM clause" error
            $wpdb->query(
                $wpdb->prepare(
                    "DELETE o1 FROM {$wpdb->options} o1
                     LEFT JOIN (
                         SELECT CONCAT('_transient_', SUBSTRING(option_name, 19)) as valid_name
                         FROM {$wpdb->options} o2
                         WHERE o2.option_name LIKE %s
                     ) as valid ON o1.option_name = valid.valid_name
                     WHERE o1.option_name LIKE %s
                     AND valid.valid_name IS NULL",
                    '_transient_timeout_' . $prefix . '%',
                    '_transient_' . $prefix . '%'
                ),
            );
        };

        // 2) Cleanup expired discovery caches (integrations/modules)
        $cleanup_prefix('fleekdash_dirs_');
        $cleanup_prefix('fleekdash_cfg_');
        $cleanup_prefix('fleekdash_module_dirs_');
        $cleanup_prefix('fleekdash_module_cfg_');

        // 3) Cleanup expired API ETag cache
        $cleanup_prefix('fleekdash_etag_');

        // 4) Cleanup expired stats controller transients (read-heavy datasets)
        $cleanup_prefix('fleekdash_stats_');
        // Legacy key prefixes (pre StatsCache::TRANSIENT_KEY_PREFIX)
        $cleanup_prefix('posts_by_date_');
        $cleanup_prefix('posts_by_author_');
        $cleanup_prefix('posts_by_taxonomy_');
        $cleanup_prefix('comments_by_date_');
        $cleanup_prefix('user_registrations_');
        $cleanup_prefix('dashboard_stats');
        $cleanup_prefix('large_dataset_');
        $cleanup_prefix('chart_data_');

        // Optional: drop the top-level integrations discovery cache key if stale
        // (it has a short TTL; safe to remove proactively once per day)
        \delete_transient('fleekdash_integrations_cache_v3');
    }

    /**
     * Initialize cache cleanup hooks
     * Register WordPress actions for scheduled cleanup
     *
     * @return void
     */
    public static function init()
    {
        // Ensure daily cache cleanup is scheduled
        \add_action('plugins_loaded', function () {
            if (!wp_next_scheduled('fleekdash_daily_cache_cleanup')) {
                \wp_schedule_event(time() + 600, 'daily', 'fleekdash_daily_cache_cleanup');
            }
        });

        // Daily cache cleanup runner
        \add_action('fleekdash_daily_cache_cleanup', [self::class, 'runDailyCleanup']);
    }
}
