<?php
/**
 * Uninstall Idesoftbcn AI Product Customizer for WooCommerce.
 *
 * @package Idesoftbcn_AI_Product_Customizer
 */

if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

/**
 * Removes plugin options, product meta, and optionally generated design files.
 */
function iapc_uninstall_plugin() {
    $iapc_options = array(
        'iapc_ai_license_key',
        'iapc_ai_license_status',
        'iapc_ai_license_token',
        'iapc_ai_license_expiry',
        'iapc_installation_uuid',
    );

    foreach ($iapc_options as $iapc_option) {
        delete_option($iapc_option);
    }

    global $wpdb;

    // Product customizer settings stored as post meta on products.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Bulk cleanup on uninstall.
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s",
            $wpdb->esc_like('_iapc_') . '%'
        )
    );

    // Per-user license admin notices.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Bulk cleanup on uninstall.
    $wpdb->query(
        "DELETE FROM {$wpdb->options}
        WHERE option_name LIKE '_transient_iapc_license_notice_%'
        OR option_name LIKE '_transient_timeout_iapc_license_notice_%'"
    );

    // Optional: remove generated design files from uploads.
    if (apply_filters('iapc_uninstall_delete_uploads', false)) {
        $iapc_upload_dir = wp_upload_dir();

        if (!empty($iapc_upload_dir['basedir'])) {
            $iapc_designs_dir = trailingslashit($iapc_upload_dir['basedir']) . 'iapc-designs';

            if (is_dir($iapc_designs_dir)) {
                $iapc_files = glob(trailingslashit($iapc_designs_dir) . '*');

                if (is_array($iapc_files)) {
                    foreach ($iapc_files as $iapc_file) {
                        if (is_file($iapc_file)) {
                            wp_delete_file($iapc_file);
                        }
                    }
                }

                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
                @rmdir($iapc_designs_dir);
            }
        }
    }
}

iapc_uninstall_plugin();
