<?php
namespace IntentDeep\VirtualFiles\Traits;

/**
 * Trait PluginDataCleanup
 *
 * Handles cleanup of Virtual Files plugin data (posts, meta, options, transients)
 * Does NOT touch Freemius data.
 */
trait PluginDataCleanup {

    /**
     * Delete all plugin data
     *
     * @return array Summary of deleted data
     */
    public function deleteAllPluginData(): array {
        global $wpdb;

        $summary = [
            'posts' => 0,
            'post_meta' => 0,
            'options' => 0,
            'transients' => 0,
        ];

        // 1. Delete all virtual_file posts
        $posts = get_posts([
            'post_type' => 'idep_virtual_file',
            'posts_per_page' => -1,
            'post_status' => 'any',
            'fields' => 'ids',
        ]);

        foreach ($posts as $post_id) {
            wp_delete_post($post_id, true); // Force delete (bypass trash)
            $summary['posts']++;
        }

        // 2. Clean up orphaned post meta (vf_ prefix)
        $deleted_meta = $wpdb->query(
            "DELETE pm FROM {$wpdb->postmeta} pm
             LEFT JOIN {$wpdb->posts} p ON pm.post_id = p.ID
             WHERE p.ID IS NULL AND pm.meta_key LIKE 'vf_%'"
        );
        $summary['post_meta'] = $deleted_meta !== false ? $deleted_meta : 0;

        // 3. Delete plugin-specific options
        $plugin_options = [
            'intentdeep_vf_settings',
            'intentdeep_vf_flush_rewrite_scheduled',
            'intentdeep_vf_pro_upgrade_version',
        ];

        foreach ($plugin_options as $option) {
            if (delete_option($option)) {
                $summary['options']++;
            }
        }

        // 4. Delete plugin transients
        $transient_patterns = [
            'vf_%',
            'intentdeep_vf_%',
        ];

        foreach ($transient_patterns as $pattern) {
            // Delete transients
            $deleted = $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM {$wpdb->options}
                     WHERE option_name LIKE %s
                     OR option_name LIKE %s",
                    '_transient_' . $pattern,
                    '_transient_timeout_' . $pattern
                )
            );
            $summary['transients'] += $deleted !== false ? $deleted : 0;
        }

        // 5. Flush rewrite rules
        flush_rewrite_rules();

        return $summary;
    }

    /**
     * Check if plugin data exists
     *
     * @return array Count of existing data
     */
    public function getPluginDataCount(): array {
        global $wpdb;

        // Count posts
        $posts_count = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'idep_virtual_file'"
        );

        // Count post meta
        $meta_count = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key LIKE 'vf_%'"
        );

        // Count options
        $options_count = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->options}
             WHERE option_name IN ('intentdeep_vf_settings', 'intentdeep_vf_flush_rewrite_scheduled', 'intentdeep_vf_pro_upgrade_version')"
        );

        // Count transients
        $transients_count = $wpdb->get_var(
            "SELECT COUNT(*) FROM {$wpdb->options}
             WHERE option_name LIKE '_transient_vf_%'
             OR option_name LIKE '_transient_virtual_files_%'
             OR option_name LIKE '_transient_timeout_vf_%'
             OR option_name LIKE '_transient_timeout_virtual_files_%'"
        );

        return [
            'posts' => intval($posts_count),
            'post_meta' => intval($meta_count),
            'options' => intval($options_count),
            'transients' => intval($transients_count),
        ];
    }
}
