<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Clean up all OrderStock data for a specific site.
 *
 * @param int  $blog_id           The ID of the blog/site to clean up.
 * @param bool $full_cleanup      If true, deletes all data including Pro data if Pro is active.
 * @param bool $preserve_structure If true, preserves database table structures (e.g., wp_tulipwork_stocks).
 */
function tulipwork_orderstock_cleanup_site($blog_id, $full_cleanup = false, $preserve_structure = false) {
    global $wpdb;

    // En multisite, basculer vers le blog spécifié
    if (is_multisite()) {
        switch_to_blog($blog_id);
    }

    $delete_data = get_option('tulipwork_orderstock_delete_data_on_uninstall', 0);
    $is_pro_active = function_exists('is_plugin_active') && is_plugin_active('orderstock-pro/orderstock-pro.php');

    if ($delete_data || $full_cleanup) {
        // Suppression des options (plugin gratuit)
        $free_options = [
            'tulipwork_orderstock_admin_emails',
            'tulipwork_orderstock_company_name',
            'tulipwork_orderstock_company_address',
            'tulipwork_orderstock_company_phone',
            'tulipwork_orderstock_company_email',
            'tulipwork_orderstock_company_siret',
            'tulipwork_orderstock_tax_rate_1',
            'tulipwork_orderstock_tax_rate_2',
            'tulipwork_orderstock_tax_rate_3',
            'orderstock_order_mode',
            'tulipwork_orderstock_delete_data_on_uninstall',
            'tulipwork_orderstock_supplier_migration_done',
            'tulipwork_orderstock_pdf_tokens',
        ];
        foreach ($free_options as $option) {
            delete_option($option);
        }

        // Suppression des options spécifiques à OrderStock Pro si Pro est actif ou full_cleanup
        if ($is_pro_active || $full_cleanup) {
            $pro_options = [
                'orderstock_pro_central_kitchen_enabled',
                'orderstock_pro_central_kitchen',
                'orderstock_pro_supplier_migration_done',
                // Ne pas inclure 'orderstock_pro_license_key' et 'orderstock_pro_license_status' pour préserver la licence
            ];
            foreach ($pro_options as $option) {
                delete_option($option);
            }
        }

        // Suppression des fichiers PDF temporaires
        $upload_dir = wp_upload_dir()['basedir'] . '/tulipwork_orderstock/';
        if (file_exists($upload_dir)) {
            $files = glob($upload_dir . '*.pdf');
            foreach ($files as $file) {
                if (is_file($file)) {
                    wp_delete_file($file);
                }
            }
            @rmdir($upload_dir);
        }

        // Suppression des CPTs (plugin gratuit)
        $free_post_types = ['tulipwork_product', 'tulipwork_supplier', 'tulipwork_order'];
        foreach ($free_post_types as $post_type) {
            $posts = get_posts([
                'post_type' => $post_type,
                'posts_per_page' => -1,
                'post_status' => 'any',
                'suppress_filters' => true,
            ]);
            foreach ($posts as $post) {
                wp_delete_post($post->ID, true);
            }
        }

        // Suppression des CPTs spécifiques à OrderStock Pro si Pro est actif ou full_cleanup
        if ($is_pro_active || $full_cleanup) {
            $pro_post_types = ['tulipwork_store', 'tulipwork_inventory'];
            foreach ($pro_post_types as $post_type) {
                $posts = get_posts([
                    'post_type' => $post_type,
                    'posts_per_page' => -1,
                    'post_status' => 'any',
                    'suppress_filters' => true,
                ]);
                foreach ($posts as $post) {
                    wp_delete_post($post->ID, true);
                }
            }
        }

        // Suppression des termes de taxonomie
        $terms = get_terms([
            'taxonomy' => 'tulipwork_prod_cat',
            'hide_empty' => false,
            'fields' => 'ids',
        ]);
        if (!is_wp_error($terms)) {
            foreach ($terms as $term_id) {
                wp_delete_term($term_id, 'tulipwork_prod_cat');
            }
        }

        // Suppression explicite de la taxonomie
        unregister_taxonomy('tulipwork_prod_cat');

        // Nettoyage des métadonnées résiduelles pour tous les CPTs
        $all_post_types = array_merge($free_post_types, ['tulipwork_store', 'tulipwork_inventory']);
        foreach ($all_post_types as $post_type) {
            $result = $wpdb->query(
                $wpdb->prepare(
                    "DELETE pm FROM {$wpdb->postmeta} pm
                    LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
                    WHERE p.post_type = %s AND p.ID IS NULL",
                    $post_type
                )
            );
            if (false === $result) {
                error_log("OrderStock Cleanup: Failed to delete orphaned postmeta for post_type $post_type on blog $blog_id");
            }
        }

        // Gestion de la table personnalisée (OrderStock Pro) si Pro est actif ou full_cleanup
        if ($is_pro_active || $full_cleanup) {
            $table_name = $wpdb->prefix . 'tulipwork_stocks';
            if ($preserve_structure) {
                // Vider la table au lieu de la supprimer
                $result = $wpdb->query("TRUNCATE TABLE $table_name");
                if (false === $result) {
                    error_log("OrderStock Cleanup: Failed to truncate table $table_name on blog $blog_id: " . $wpdb->last_error);
                } else {
                    error_log("OrderStock Cleanup: Successfully truncated table $table_name on blog $blog_id");
                }
            } else {
                // Supprimer la table complètement
                $wpdb->query("DROP TABLE IF EXISTS $table_name");
                error_log("OrderStock Cleanup: Dropped table $table_name on blog $blog_id");
            }
        }

        // Suppression des métadonnées utilisateur spécifiques à OrderStock Pro (User Management)
        if ($is_pro_active || $full_cleanup) {
            $result = $wpdb->query(
                "DELETE FROM {$wpdb->usermeta} 
                WHERE meta_key = '_orderstock_assigned_stores'"
            );
            if (false === $result) {
                error_log("OrderStock Cleanup: Failed to delete _orderstock_assigned_stores usermeta on blog $blog_id");
            }
        }

        // Suppression des transients liés aux rapports (Reports)
        if ($is_pro_active || $full_cleanup) {
            $transients = $wpdb->get_col(
                "SELECT option_name 
                FROM {$wpdb->options} 
                WHERE option_name LIKE '_transient_orderstock_reports_%'"
            );
            foreach ($transients as $transient) {
                $transient_name = str_replace('_transient_', '', $transient);
                delete_transient($transient_name);
            }
        }

        // Suppression des capacités personnalisées (plugin gratuit)
        $capabilities = [
            'tulipwork_orderstock_access',
            'tulipwork_orderstock_access_stock',
            'tulipwork_orderstock_access_orders',
            'tulipwork_orderstock_access_products',
            'tulipwork_orderstock_access_suppliers',
            'tulipwork_orderstock_access_settings',
            'tulipwork_orderstock_access_inventories',
            'tulipwork_orderstock_access_history',
            'tulipwork_orderstock_access_reports',
            'tulipwork_orderstock_access_import_export',
            'tulipwork_orderstock_access_users',
        ];
        $roles = wp_roles();
        foreach ($roles->role_objects as $role) {
            foreach ($capabilities as $cap) {
                $role->remove_cap($cap);
            }
        }

        // Restaurer les capacités de base pour l'utilisateur actuel ou les administrateurs
        $current_user = wp_get_current_user();
        if ($current_user->ID) {
            $admin_role = get_role('administrator');
            if ($admin_role && in_array('administrator', $current_user->roles)) {
                // Restaurer les capacités de base pour les administrateurs
                $admin_role->add_cap('tulipwork_orderstock_access');
                $admin_role->add_cap('tulipwork_orderstock_access_stock');
                $admin_role->add_cap('tulipwork_orderstock_access_orders');
                $admin_role->add_cap('tulipwork_orderstock_access_products');
                $admin_role->add_cap('tulipwork_orderstock_access_suppliers');
                $admin_role->add_cap('tulipwork_orderstock_access_settings');
                error_log("OrderStock Cleanup: Restored base capabilities for administrator role on blog $blog_id");
            }
        }

        // Suppression des rôles personnalisés (OrderStock Pro) si Pro est actif ou full_cleanup
        if ($is_pro_active || $full_cleanup) {
            $pro_roles = [
                'orderstock_stock_manager',
                'orderstock_order_manager',
                'orderstock_kitchen_manager',
                'orderstock_full_manager',
                'tulipworkmember',
            ];
            foreach ($pro_roles as $role) {
                if (get_role($role)) {
                    remove_role($role);
                }
            }
        }
    }

    // Restaurer le blog courant en multisite
    if (is_multisite()) {
        restore_current_blog();
    }
}