<?php

namespace PageVICO\Cleanup;

defined( 'ABSPATH' ) || exit;
class DataCleanup {
    public static function init() {
        // Schedule daily cleanup if not already scheduled
        if ( !wp_next_scheduled( 'pagevico_daily_cleanup' ) ) {
            wp_schedule_event( time(), 'daily', 'pagevico_daily_cleanup' );
        }
        // Add cleanup action
        add_action( 'pagevico_daily_cleanup', array(__CLASS__, 'cleanup_old_data') );
        // Register deactivation hook
        register_deactivation_hook( PageVICO_PLUGIN_FILE, array(__CLASS__, 'plugin_deactivation') );
    }

    /**
     * Clean up scheduled events on plugin deactivation
     */
    public static function plugin_deactivation() {
        wp_clear_scheduled_hook( 'pagevico_daily_cleanup' );
    }

    /**
     * Clean up old data based on retention settings
     */
    public static function cleanup_old_data() {
        global $wpdb;
        // Get retention periods
        $analytics_retention = get_option( 'PageVICO_analytics_retention', 90 );
        $heatmap_retention = get_option( 'PageVICO_heatmap_retention', 30 );
        // Clean up sessions data - uses first_seen column
        $sessions_table = PageVICO_TABLE_SESSIONS;
        $wpdb->query( $wpdb->prepare( "DELETE FROM {$sessions_table} WHERE first_seen < DATE_SUB(NOW(), INTERVAL %d DAY)", $analytics_retention ) );
        // Clean up pageviews data - uses created_at column
        $pageviews_table = PageVICO_TABLE_PAGEVIEWS;
        $wpdb->query( $wpdb->prepare( "DELETE FROM {$pageviews_table} WHERE created_at < DATE_SUB(NOW(), INTERVAL %d DAY)", $analytics_retention ) );
    }

}
