<?php

/**
 * Freemius SDK integration and licensing functions.
 *
 * This file handles the Freemius SDK initialization and provides helper
 * functions for premium feature checks. It also handles cleanup on uninstall.
 *
 * @package Carticy\CheckoutShield
 */
// Prevent direct file access.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( !function_exists( 'carticy_checkoutshield_fs' ) ) {
    /**
     * Create a helper function for easy SDK access.
     *
     * @return \Freemius The Freemius SDK instance.
     */
    function carticy_checkoutshield_fs() {
        global $carticy_checkoutshield_fs;
        if ( !isset( $carticy_checkoutshield_fs ) ) {
            // Freemius SDK is auto-loaded through Composer.
            $carticy_checkoutshield_fs = fs_dynamic_init( array(
                'id'               => '23066',
                'slug'             => 'carticy-checkout-shield-for-woocommerce',
                'premium_slug'     => 'carticy-checkout-shield-for-woocommerce-pro',
                'type'             => 'plugin',
                'public_key'       => 'pk_e76019e3e0cbff0c16de27e5ba37d',
                'is_premium'       => false,
                'premium_suffix'   => 'Pro',
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => true,
                'menu'             => array(
                    'first-path' => 'admin.php?page=wc-settings&tab=advanced&section=checkout_shield',
                ),
                'is_live'          => true,
            ) );
        }
        return $carticy_checkoutshield_fs;
    }

    // Init Freemius.
    carticy_checkoutshield_fs();
    // Signal that SDK was initiated.
    do_action( 'carticy_checkoutshield_fs_loaded' );
}
/**
 * Check if running the premium version code.
 *
 * IMPORTANT: For code stripping to work, use the Freemius SDK methods directly:
 * if ( carticy_checkoutshield_fs()->is__premium_only() ) { ... }
 *
 * This wrapper function is for runtime checks only and will NOT trigger
 * code stripping by the Freemius PHP Preprocessor.
 *
 * @return bool True if running premium version code.
 */
function carticy_checkout_shield_is_premium_only() : bool {
    return carticy_checkoutshield_fs()->is__premium_only();
}

/**
 * Check if the user can use premium features.
 *
 * IMPORTANT: For code stripping to work, use the Freemius SDK methods directly.
 *
 * Pattern for premium features (code will be stripped from free version):
 * if ( carticy_checkoutshield_fs()->is__premium_only() ) {
 *     if ( carticy_checkoutshield_fs()->can_use_premium_code() ) {
 *         // Premium feature code - will be REMOVED from free version
 *     }
 * }
 *
 * @return bool True if user has valid license or trial.
 */
function carticy_checkout_shield_can_use_premium() : bool {
    return carticy_checkoutshield_fs()->can_use_premium_code();
}

/**
 * Alias for carticy_checkout_shield_can_use_premium().
 *
 * @return bool True if premium features are available.
 */
function carticy_checkout_shield_is_pro() : bool {
    return carticy_checkout_shield_can_use_premium();
}

/**
 * Uninstall cleanup function.
 *
 * This function is called by Freemius when the plugin is uninstalled.
 * It respects the user's data deletion preference setting.
 */
function carticy_checkout_shield_uninstall_cleanup() {
    // Check if user wants data deleted on uninstall.
    // Default to 'no' to preserve data for potential reinstall.
    if ( get_option( 'carticy_checkout_shield_delete_data_on_uninstall', 'no' ) !== 'yes' ) {
        return;
    }
    // Delete all plugin options.
    $options = array(
        'carticy_checkout_shield_enabled',
        'carticy_checkout_shield_mode',
        'carticy_checkout_shield_proxy_support',
        'carticy_checkout_shield_whitelisted_ips',
        'carticy_checkout_shield_api_keys',
        'carticy_checkout_shield_activated',
        'carticy_checkout_shield_blocklist_enabled',
        'carticy_checkout_shield_db_version'
    );
    foreach ( $options as $option ) {
        delete_option( $option );
    }
    // Delete order meta.
    carticy_checkout_shield_delete_order_meta_on_uninstall();
    // Delete transients.
    carticy_checkout_shield_delete_transients_on_uninstall();
    // Drop custom database tables.
    carticy_checkout_shield_drop_tables_on_uninstall();
    // Finally delete the preference itself.
    delete_option( 'carticy_checkout_shield_delete_data_on_uninstall' );
}

/**
 * Delete all order meta created by the plugin.
 *
 * Note: This only deletes the meta, not the orders themselves.
 * This respects data retention - order history remains intact.
 */
function carticy_checkout_shield_delete_order_meta_on_uninstall() : void {
    global $wpdb;
    $meta_keys = array(
        '_carticy_checkout_shield_origin',
        '_carticy_checkout_shield_status',
        '_carticy_checkout_shield_signals',
        'carticy_ccs_status',
        'carticy_ccs_context'
    );
    // Handle HPOS (High-Performance Order Storage).
    if ( class_exists( '\\Automattic\\WooCommerce\\Utilities\\OrderUtil' ) && method_exists( '\\Automattic\\WooCommerce\\Utilities\\OrderUtil', 'custom_orders_table_usage_is_enabled' ) && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled() ) {
        // HPOS is enabled - delete from wc_orders_meta table.
        $meta_table = $wpdb->prefix . 'wc_orders_meta';
        foreach ( $meta_keys as $meta_key ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->delete( $meta_table, array(
                'meta_key' => $meta_key,
            ), array('%s') );
        }
        return;
    }
    // Legacy post-based orders - delete from postmeta table.
    foreach ( $meta_keys as $meta_key ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->delete( $wpdb->postmeta, array(
            'meta_key' => $meta_key,
        ), array('%s') );
    }
}

/**
 * Clear any transients or cached data.
 */
function carticy_checkout_shield_delete_transients_on_uninstall() : void {
    global $wpdb;
    // Delete any transients with our prefix.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", '_transient_carticy_checkout_shield_%', '_transient_timeout_carticy_checkout_shield_%' ) );
    // Also clear blocklist cache transients.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", '_transient_ccs_%', '_transient_timeout_ccs_%' ) );
}

/**
 * Drop custom database tables.
 */
function carticy_checkout_shield_drop_tables_on_uninstall() : void {
    global $wpdb;
    // Drop blocklist table.
    $blocklist_table = $wpdb->prefix . 'carticy_ccs_blocklist';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name is safe internal constant.
    $wpdb->query( "DROP TABLE IF EXISTS {$blocklist_table}" );
}

// Register uninstall hook with Freemius.
carticy_checkoutshield_fs()->add_action( 'after_uninstall', 'carticy_checkout_shield_uninstall_cleanup' );