<?php
/**
 * Copyright (C) 2026 Plugixa (https://plugixa.com)
 * License: GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

namespace PlugixaRecipe;

// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.SlowDBQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom-table data layer: table identifiers are built with $wpdb->prefix and are never user input; all request values are bound via $wpdb->prepare(); ORDER BY / LIMIT fragments come out of internal allow-list maps; content reads go through PlugixaRecipe\Cache (the static sniff cannot trace caching through the wrapper); meta_key/meta_value are dedicated plugin columns, not WP_Query.

defined( 'ABSPATH' ) || exit;

/**
 * Plugin uninstall cleanup.
 *
 * Freemius ships its own uninstall.php and forbids the plugin from bundling
 * one, so this runs via the Freemius `after_uninstall` action (registered in
 * plugixarecipe.php) instead of a WordPress uninstall.php file.
 */
class Uninstaller {

    /**
     * Drop tables, options, and capabilities on plugin delete.
     *
     * Honors the `delete_data_on_uninstall` setting: when disabled, plugin
     * data (tables/attachments) is preserved and only options + capabilities
     * are removed.
     */
    public static function uninstall() {
        global $wpdb;

        // Check if user opted to delete all data on uninstall.
        $settings = get_option('plugixarecipe_settings', []);
        if (empty($settings['delete_data_on_uninstall'])) {
            // Preserve plugin data — only remove options and capabilities.
            delete_option('plugixarecipe_demo_image_ids');
            delete_option('plugixarecipe_demo_loaded');
            delete_option('plugixarecipe_settings');
            delete_option('plugixarecipe_ml_migrated');
            delete_option('plugixarecipe_ml_v2_migrated');

            $admin = get_role('administrator');
            if ($admin) {
                $admin->remove_cap('plugixa_recipe_manage');
                $admin->remove_cap('plugixa_recipe_edit');
                $admin->remove_cap('plugixa_recipe_delete');
                $admin->remove_cap('plugixa_recipe_publish');
                $admin->remove_cap('plugixa_recipe_settings');
            }
            return;
        }

        // Drop tables (order matters due to foreign key relationships).
        //
        // This list deliberately includes the three tables the premium overlay owns
        // (custom_fields, meta, seo_analysis). They are named here, not created here:
        // DROP TABLE IF EXISTS is a no-op when they are absent, and naming them means a
        // site that downgrades from premium to free can still clean them up on uninstall
        // instead of leaving them behind forever.
        $tables = [
            $wpdb->prefix . 'plugixarecipe_shopping_list_items',
            $wpdb->prefix . 'plugixarecipe_shopping_lists',
            $wpdb->prefix . 'plugixarecipe_collection_recipes',
            $wpdb->prefix . 'plugixarecipe_collections',
            $wpdb->prefix . 'plugixarecipe_favorites',
            $wpdb->prefix . 'plugixarecipe_seo_analysis',
            $wpdb->prefix . 'plugixarecipe_reviews',
            $wpdb->prefix . 'plugixarecipe_nutrition',
            $wpdb->prefix . 'plugixarecipe_instructions',
            $wpdb->prefix . 'plugixarecipe_ingredients',
            $wpdb->prefix . 'plugixarecipe_meta',
            $wpdb->prefix . 'plugixarecipe_custom_fields',
            $wpdb->prefix . 'plugixarecipe_recipe_courses',
            $wpdb->prefix . 'plugixarecipe_courses',
            $wpdb->prefix . 'plugixarecipe_recipe_cuisines',
            $wpdb->prefix . 'plugixarecipe_cuisines',
            $wpdb->prefix . 'plugixarecipe_recipe_categories',
            $wpdb->prefix . 'plugixarecipe_categories',
            $wpdb->prefix . 'plugixarecipe_recipes',
            $wpdb->prefix . 'plugixarecipe_views',
            $wpdb->prefix . 'plugixarecipe_shortcodes',
            $wpdb->prefix . 'plugixarecipe_units',
        ];

        foreach ($tables as $table) {
            $wpdb->query("DROP TABLE IF EXISTS {$table}");
        }

        // Delete demo attachments from media library
        $demo_image_ids = get_option('plugixarecipe_demo_image_ids', []);
        if (is_array($demo_image_ids)) {
            // Handle structured format (recipes/categories/cuisines sub-arrays)
            foreach (['recipes', 'categories', 'cuisines'] as $group) {
                if (isset($demo_image_ids[$group]) && is_array($demo_image_ids[$group])) {
                    foreach ($demo_image_ids[$group] as $id) {
                        wp_delete_attachment((int) $id, true);
                    }
                }
            }
            // Legacy flat format fallback
            if (!isset($demo_image_ids['recipes'])) {
                foreach ($demo_image_ids as $id) {
                    if (is_int($id)) {
                        wp_delete_attachment($id, true);
                    }
                }
            }
        }
        $remaining_demo = get_posts([
            'post_type'   => 'attachment',
            'meta_key'    => '_plugixarecipe_demo',
            'meta_value'  => '1',
            'numberposts' => -1,
            'fields'      => 'ids',
        ]);
        foreach ($remaining_demo as $id) {
            wp_delete_attachment((int) $id, true);
        }

        // Delete options
        delete_option('plugixarecipe_demo_image_ids');
        delete_option('plugixarecipe_demo_loaded');
        delete_option('plugixarecipe_settings');
        delete_option('plugixarecipe_ml_migrated');
        delete_option('plugixarecipe_ml_v2_migrated');

        // Remove capabilities
        $admin = get_role('administrator');
        if ($admin) {
            $admin->remove_cap('plugixa_recipe_manage');
            $admin->remove_cap('plugixa_recipe_edit');
            $admin->remove_cap('plugixa_recipe_delete');
            $admin->remove_cap('plugixa_recipe_publish');
            $admin->remove_cap('plugixa_recipe_settings');
        }
    }
}
