<?php
namespace PageVICO\Cron;

defined('ABSPATH') || exit;

class DataRetention {
    /**
     * Initialize the data retention cron jobs
     */
    public static function init() {
        add_action('pagevico_prune_old_data', [__CLASS__, 'pruneOldData']);
        
        // Register deactivation hook to clean up schedules
        add_action('pagevico_plugin_deactivation', [__CLASS__, 'deactivate']);
        
        // Add admin notice when cleanup occurs
        add_action('admin_notices', [__CLASS__, 'maybeShowCleanupNotice']);
    }
    
    /**
     * Schedule the data retention cron job
     */
    public static function activate() {
        if (!wp_next_scheduled('pagevico_prune_old_data')) {
            // Schedule to run daily at midnight
            wp_schedule_event(strtotime('tomorrow midnight'), 'daily', 'pagevico_prune_old_data');
        }
    }
    
    /**
     * Clean up scheduled events on plugin deactivation
     */
    public static function deactivate() {
        $timestamp = wp_next_scheduled('pagevico_prune_old_data');
        if ($timestamp) {
            wp_unschedule_event($timestamp, 'pagevico_prune_old_data');
        }
    }
    
    /**
     * Show admin notice after cleanup
     */
    public static function maybeShowCleanupNotice() {
        // Only show on plugin pages
        $screen = get_current_screen();
        if (!$screen || strpos($screen->id, 'pagevico') === false) {
            return;
        }
        
        // Check if cleanup recently ran and we have a transient
        $cleanup_data = get_transient('pagevico_data_cleanup');
        if (!$cleanup_data) {
            return;
        }
        
        // Delete the transient so notice only shows once
        delete_transient('pagevico_data_cleanup');
        
        // Show the notice
        $message = sprintf(
            __('Data retention cleanup completed. Removed records older than %d days.', 'page-visit-counter-analytics'),
            $cleanup_data['days']
        );
        
        echo '<div class="notice notice-info is-dismissible"><p>' . esc_html($message) . '</p></div>';
    }
    
    /**
     * Delete data older than the retention period
     */
    public static function pruneOldData() {
        global $wpdb;
        
        // Get the retention period in days (default to 90 if not set)
        $retention_days = get_option('pagevico_views_retention', 90);
        
        // Make sure we have a valid number
        $retention_days = max(1, absint($retention_days));
        
        // Calculate the cutoff date in MySQL format
        $cutoff_date = date('Y-m-d', current_time('timestamp') - ($retention_days * 86400));
        
        // Delete old pageviews and get count
        $pageviews_deleted = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}pagevico_pageviews WHERE DATE(created_at) < %s",
            $cutoff_date
        ));
        
        // Delete old sessions that haven't been updated since the cutoff date
        $sessions_deleted = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$wpdb->prefix}pagevico_sessions WHERE DATE(last_seen) < %s",
            $cutoff_date
        ));
        
        // Store cleanup info for admin notice
        set_transient('pagevico_data_cleanup', [
            'days' => $retention_days,
            'pageviews' => $pageviews_deleted,
            'sessions' => $sessions_deleted,
            'time' => date('Y-m-d H:i:s', current_time('timestamp'))
        ], DAY_IN_SECONDS);
        
        // Log the cleanup for debugging purposes
        error_log(sprintf(
            'Page Visit Counter Analytics: Pruned data older than %s days. Removed %d pageviews, %d sessions.',
            $retention_days,
            $pageviews_deleted,
            $sessions_deleted
        ));
    }
} 