<?php

/*
* Plugin Name: IntentDeep Virtual Files for SEO
* Plugin URI: https://virtualfiles.intentdeep.com/
* Description: Create and manage virtual files that behave as if they physically exist in your website root directory
* Author: IntentDeep
* Version: 1.0.1
* Author URI: https://intentdeep.com/
* License: GPLv2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: intentdeep-virtual-files
* Requires PHP: 7.4
*/
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( !function_exists( 'intentdeep_vf_log' ) ) {
    /**
     * Custom logger for the plugin
     * Only logs when WP_DEBUG is true
     *
     * @param mixed $message The message to log (can be string, array, object)
     */
    function intentdeep_vf_log(  $message  ) {
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG === true ) {
            if ( is_array( $message ) || is_object( $message ) ) {
                error_log( print_r( $message, true ) );
            } else {
                error_log( $message );
            }
        }
    }

}
// Define plugin root directory
if ( !defined( 'INTENTDEEP_VF_PLUGIN_ROOT' ) ) {
    define( 'INTENTDEEP_VF_PLUGIN_ROOT', plugin_dir_path( __FILE__ ) );
}
// Load Composer autoloader FIRST (required for Freemius SDK)
require_once INTENTDEEP_VF_PLUGIN_ROOT . 'vendor/autoload.php';
// Freemius SDK initialization
if ( !function_exists( 'intentdeep_vf_fs' ) ) {
    // Create a helper function for easy SDK access.
    function intentdeep_vf_fs() {
        global $intentdeep_vf_fs;
        if ( !isset( $intentdeep_vf_fs ) ) {
            // Include Freemius SDK.
            // SDK is auto-loaded through Composer
            $intentdeep_vf_fs = fs_dynamic_init( array(
                'id'               => '21915',
                'slug'             => 'intentdeep-virtual-files',
                'premium_slug'     => 'intentdeep-virtual-files-pro',
                'type'             => 'plugin',
                'public_key'       => 'pk_1f2783c51d635a6b64ababced11be',
                'is_premium'       => false,
                'premium_suffix'   => 'Pro',
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => true,
                'trial'            => array(
                    'days'               => 7,
                    'is_require_payment' => true,
                ),
                'menu'             => array(
                    'slug'           => 'intentdeep_vf_settings',
                    'parent'         => array(
                        'slug' => 'edit.php?post_type=idep_virtual_file',
                    ),
                    'override_exact' => true,
                    'support'        => false,
                    'account'        => true,
                    'pricing'        => true,
                    'contact'        => true,
                    'affiliation'    => true,
                ),
                'is_live'          => true,
            ) );
        }
        return $intentdeep_vf_fs;
    }

    // Init Freemius.
    intentdeep_vf_fs();
    // Signal that SDK was initiated.
    do_action( 'intentdeep_vf_fs_loaded' );
    function intentdeep_vf_fs_settings_url() {
        return admin_url( 'edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings' );
    }

    function intentdeep_vf_fs_main_url() {
        return admin_url( 'edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings' );
    }

    intentdeep_vf_fs()->add_filter( 'connect_url', 'intentdeep_vf_fs_settings_url' );
    intentdeep_vf_fs()->add_filter( 'after_skip_url', 'intentdeep_vf_fs_main_url' );
    intentdeep_vf_fs()->add_filter( 'after_connect_url', 'intentdeep_vf_fs_main_url' );
    intentdeep_vf_fs()->add_filter( 'after_pending_connect_url', 'intentdeep_vf_fs_main_url' );
    intentdeep_vf_fs()->add_filter( 'after_activation_redirect', 'intentdeep_vf_fs_main_url' );
    intentdeep_vf_fs()->add_filter( 'plugin_page_url', 'intentdeep_vf_fs_main_url' );
    /**
     * Uninstall cleanup function
     * This will be called by Freemius after the uninstall event is tracked
     */
    function intentdeep_vf_fs_uninstall_cleanup() {
        // Get plugin settings to check if data should be removed
        $settings = get_option( 'intentdeep_vf_settings', [] );
        // Check if user wants to remove data on uninstall
        $remove_data = isset( $settings['remove_data_on_uninstall'] ) && $settings['remove_data_on_uninstall'] === true;
        // If user doesn't want to remove data, exit early
        if ( !$remove_data ) {
            return;
        }
        // Use the PluginDataCleanup trait through a temporary class
        $cleanup_class = new class {
            use \IntentDeep\VirtualFiles\Traits\PluginDataCleanup;
        }
;
        // Delete all plugin data
        try {
            $summary = $cleanup_class->deleteAllPluginData();
            // Log the cleanup for debugging (if WP_DEBUG is enabled)
            intentdeep_vf_log( sprintf(
                'Virtual Files Uninstall: Removed %d posts, %d post meta, %d options, %d transients',
                $summary['posts'],
                $summary['post_meta'],
                $summary['options'],
                $summary['transients']
            ) );
        } catch ( Exception $e ) {
            // Log error but don't prevent uninstall
            intentdeep_vf_log( 'Virtual Files Uninstall Error: ' . $e->getMessage() );
        }
    }

    // Hook the uninstall cleanup to Freemius's after_uninstall action
    intentdeep_vf_fs()->add_action( 'after_uninstall', 'intentdeep_vf_fs_uninstall_cleanup' );
}
// === PLUGIN ACTIVATION/DEACTIVATION HOOKS ===
function intentdeep_vf_activate() {
    $pluginManager = new \IntentDeep\VirtualFiles\Bootstrap\PluginManager('virtual-files');
    $pluginManager->activate();
    // Run migration for existing users (from old naming to new naming)
    intentdeep_vf_run_migration();
}

/**
 * Migration routine for upgrading from old naming convention
 */
function intentdeep_vf_run_migration() {
    // Check if migration has already run
    if ( get_option( 'intentdeep_vf_migration_completed' ) ) {
        return;
    }
    // Migrate main settings option from old name to new name
    $old_settings = get_option( 'virtual-files-settings' );
    if ( $old_settings !== false ) {
        // Copy to new option name
        update_option( 'intentdeep_vf_settings', $old_settings );
        // Keep old option for one version cycle (for rollback safety)
        // It will be cleaned up in a future version
        // Log migration if WP_DEBUG is enabled
        intentdeep_vf_log( 'IntentDeep Virtual Files: Migrated settings from "virtual-files-settings" to "intentdeep_vf_settings"' );
    }
    // Migrate other options
    $options_to_migrate = [
        'virtual_files_onboarding_status'       => 'intentdeep_vf_onboarding_status',
        'virtual_files_flush_rewrite_scheduled' => 'intentdeep_vf_flush_rewrite_scheduled',
        'virtual_files_pro_upgrade_version'     => 'intentdeep_vf_pro_upgrade_version',
    ];
    foreach ( $options_to_migrate as $old_name => $new_name ) {
        $old_value = get_option( $old_name );
        if ( $old_value !== false ) {
            update_option( $new_name, $old_value );
            intentdeep_vf_log( "IntentDeep Virtual Files: Migrated option from '{$old_name}' to '{$new_name}'" );
        }
    }
    // Mark migration as completed
    update_option( 'intentdeep_vf_migration_completed', true );
    // Add admin notice about successful migration
    set_transient( 'intentdeep_vf_migration_notice', true, 300 );
    // Show for 5 minutes
}

function intentdeep_vf_deactivate() {
    $pluginManager = new \IntentDeep\VirtualFiles\Bootstrap\PluginManager('virtual-files');
    $pluginManager->deactivate();
}

register_activation_hook( __FILE__, 'intentdeep_vf_activate' );
register_deactivation_hook( __FILE__, 'intentdeep_vf_deactivate' );
// === PLUGIN INITIALIZATION ===
add_action( 'plugins_loaded', function () {
    try {
        // Initialize the plugin using Bootstrap
        \IntentDeep\VirtualFiles\Bootstrap\Bootstrap::init();
    } catch ( \Exception $e ) {
        intentdeep_vf_log( 'Virtual Files Bootstrap Error: ' . $e->getMessage() );
        intentdeep_vf_log( 'Virtual Files Stack trace: ' . $e->getTraceAsString() );
        // Fallback to basic functionality in case of Bootstrap failure
        if ( is_admin() ) {
            add_action( 'admin_notices', function () use($e) {
                ?>
                <div class="notice notice-error">
                    <p>Virtual Files Error: <?php 
                echo esc_html( $e->getMessage() );
                ?></p>
                </div>
                <?php 
            } );
        }
    }
}, 0 );