<?php

/**
 * AI Content Generator
 *
 * @package           AIContentGenerator
 * @author            RoidNet
 * @license           GPL-2.0-or-later
 *
 * @wordpress-plugin
 * Plugin Name: RoidNet AI Content Generator
 * Plugin URI:        https://roidnet.com/plugins/ai-content-generator
 * Description:       AI article writer & image generator using WordPress 7.0+ Native AI, OpenRouter (400+ models), Pexels, and auto-scheduling.
 * Version:           1.3.3
 * Requires at least: 6.0
 * Requires PHP:      7.4
 * Author:            RoidNet
 * Author URI:        https://roidnet.com
 * Text Domain:       roidnet-ai-content-generator
 * Domain Path:       /languages
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 */
// Prevent direct access
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Freemius SDK Integration
if ( function_exists( 'roidaico_fs' ) ) {
    roidaico_fs()->set_basename( false, __FILE__ );
} else {
    /**
     * DO NOT REMOVE THIS IF, IT IS ESSENTIAL FOR THE
     * `function_exists` CALL ABOVE TO PROPERLY WORK.
     */
    if ( !function_exists( 'roidaico_fs' ) ) {
        // Create a helper function for easy SDK access.
        function roidaico_fs() {
            global $roidaico_fs;
            if ( !isset( $roidaico_fs ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
                $roidaico_fs = fs_dynamic_init( array(
                    'id'               => '23018',
                    'slug'             => 'roidnet-ai-content-generator',
                    'type'             => 'plugin',
                    'public_key'       => 'pk_8614a4c24c2abce6406b38782f903',
                    'is_premium'       => false,
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'is_org_compliant' => false,
                    'trial'            => array(
                        'days'               => 7,
                        'is_require_payment' => true,
                    ),
                    'has_affiliation'  => 'selected',
                    'menu'             => array(
                        'slug'    => 'roidnet-ai-content-generator',
                        'contact' => false,
                        'support' => false,
                    ),
                    'is_live'          => true,
                ) );
            }
            return $roidaico_fs;
        }

        // Init Freemius.
        roidaico_fs();
        // Signal that SDK was initiated.
        do_action( 'roidaico_fs_loaded' );
    }
}
// Freemius Additional Hooks & Configuration (placed outside boilerplate to prevent deletion by Freemius compiler)
if ( function_exists( 'roidaico_fs' ) ) {
    // Show trial promotion notice immediately (0 seconds instead of 24 hours).
    roidaico_fs()->add_filter( 'show_first_trial_after_n_sec', '__return_zero' );
    // Force clear Freemius API cache and sync plans once on admin_init hook to prevent errors during early global inclusion.
    add_action( 'admin_init', function () {
        if ( !get_transient( 'roidaico_fs_clear_cache_once' ) ) {
            if ( class_exists( 'FS_Api' ) ) {
                FS_Api::clear_cache();
            }
            // Only sync plans if the site is registered/opted-in to prevent TypeErrors for unregistered users
            if ( roidaico_fs()->is_registered() ) {
                roidaico_fs()->_sync_plans();
            }
            set_transient( 'roidaico_fs_clear_cache_once', 'true', 300 );
        }
    } );
}
/**
 * Freemius Uninstall Cleanup
 *
 * This function handles all plugin data cleanup when the plugin is uninstalled.
 * It's hooked to Freemius's after_uninstall action to ensure uninstall tracking
 * and user feedback are captured before cleanup runs.
 */
if ( !function_exists( 'roidaico_fs_uninstall_cleanup' ) ) {
    /**
     * Freemius Uninstall Cleanup
     *
     * This function handles all plugin data cleanup when the plugin is uninstalled.
     * It's hooked to Freemius's after_uninstall action to ensure uninstall tracking
     * and user feedback are captured before cleanup runs.
     */
    function roidaico_fs_uninstall_cleanup() {
        global $wpdb;
        // Delete all plugin options
        $options = array(
            'roidaico_ai_provider',
            'roidaico_openrouter_api_key',
            'roidaico_openrouter_model',
            'roidaico_pexels_api_key',
            'roidaico_default_tone',
            'roidaico_default_length',
            'roidaico_default_language',
            'roidaico_max_ready_articles',
            'roidaico_min_interval_minutes',
            'roidaico_auto_generate_keywords',
            'roidaico_auto_generate_category',
            'roidaico_auto_generate_instructions',
            'roidaico_enable_internal_links',
            'roidaico_max_internal_links',
            'roidaico_custom_instructions',
            'roidaico_images_count',
            'roidaico_seo_plugin',
            'roidaico_image_source',
            'roidaico_ai_image_model',
            'roidaico_db_version'
        );
        foreach ( $options as $option ) {
            delete_option( $option );
        }
        // Delete all plugin database tables
        $tables = array(
            $wpdb->prefix . 'roidaico_keywords',
            $wpdb->prefix . 'roidaico_schedules',
            $wpdb->prefix . 'roidaico_used_images',
            $wpdb->prefix . 'roidaico_posts_log'
        );
        foreach ( $tables as $table ) {
            $wpdb->query( "DROP TABLE IF EXISTS {$table}" );
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        }
        // Delete all plugin post meta
        $meta_keys = array(
            '_roidaico_generated',
            '_roidaico_keyword',
            '_roidaico_generated_at',
            '_roidaico_meta_description',
            '_roidaico_focus_keyword'
        );
        foreach ( $meta_keys as $meta_key ) {
            $wpdb->delete( $wpdb->postmeta, array(
                'meta_key' => $meta_key,
            ), array('%s') );
        }
        // Clear scheduled cron events
        wp_clear_scheduled_hook( 'roidaico_scheduled_publish' );
        wp_clear_scheduled_hook( 'roidaico_keyword_check' );
        // Delete any transients
        delete_transient( 'roidaico_openrouter_models' );
    }

}
// Hook the uninstall cleanup to Freemius after_uninstall action
roidaico_fs()->add_action( 'after_uninstall', 'roidaico_fs_uninstall_cleanup' );
// Plugin constants
define( 'ROIDAICO_VERSION', '1.3.3' );
define( 'ROIDAICO_PLUGIN_FILE', __FILE__ );
define( 'ROIDAICO_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'ROIDAICO_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'ROIDAICO_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
// Override plugin icon to use local icon file
roidaico_fs()->add_filter( 'plugin_icon', function () {
    return ROIDAICO_PLUGIN_DIR . 'assets/img/icon.jpg';
} );
// Customize the "Upgrade" link in the plugins list to show "Start a Trial" if eligible.
$roidaico_custom_action_links_filter = function ( $links ) {
    if ( function_exists( 'roidaico_fs' ) ) {
        // Only if the user can't use premium features yet and is not already on a trial
        if ( !roidaico_fs()->can_use_premium_code() && !roidaico_fs()->is_trial() ) {
            if ( isset( $links['upgrade'] ) ) {
                $links['upgrade'] = sprintf( '<a href="%s" style="font-weight: bold; color: #0073aa;">%s</a>', esc_url( roidaico_fs()->get_trial_url() ), esc_html__( 'Start a Trial', 'roidnet-ai-content-generator' ) );
            }
        }
    }
    return $links;
};
add_filter( 'plugin_action_links_' . ROIDAICO_PLUGIN_BASENAME, $roidaico_custom_action_links_filter, 20 );
add_filter( 'network_admin_plugin_action_links_' . ROIDAICO_PLUGIN_BASENAME, $roidaico_custom_action_links_filter, 20 );
// Customize the "Visit plugin site" link in the plugins list to point to the Pro page when Pro version is active.
add_filter(
    'plugin_row_meta',
    function (
        $plugin_meta,
        $plugin_file,
        $plugin_data,
        $status
    ) {
        if ( $plugin_file === ROIDAICO_PLUGIN_BASENAME ) {
            if ( function_exists( 'roidaico_fs' ) && roidaico_fs()->can_use_premium_code() ) {
                if ( isset( $plugin_meta['plugin_uri'] ) ) {
                    $plugin_meta['plugin_uri'] = sprintf(
                        '<a href="%s" title="%s">%s</a>',
                        esc_url( 'https://roidnet.com/en/ai-content-generator-2/' ),
                        esc_attr__( 'Visit plugin site', 'roidnet-ai-content-generator' ),
                        esc_html__( 'Visit plugin site', 'roidnet-ai-content-generator' )
                    );
                }
            }
        }
        return $plugin_meta;
    },
    20,
    4
);
// Force the admin menu link to pricing page to include trial=true on client side to prevent Freemius PHP redirect loops.
add_action( 'admin_footer', function () {
    if ( function_exists( 'roidaico_fs' ) ) {
        if ( !roidaico_fs()->can_use_premium_code() && !roidaico_fs()->is_trial() ) {
            ?>
            <script type="text/javascript">
                jQuery(document).ready(function($) {
                    var $upgradeMenu = $('a[href*="page=roidnet-ai-content-generator-pricing"]');
                    $upgradeMenu.each(function() {
                        var href = $(this).attr('href');
                        if (href && href.indexOf('trial=true') === -1) {
                            $(this).attr('href', href + (href.indexOf('?') === -1 ? '?' : '&') + 'trial=true');
                        }
                    });
                });
            </script>
            <?php 
        }
    }
} );
/**
 * Autoloader for plugin classes
 */
spl_autoload_register( function ( $class ) {
    $prefix = 'AICG\\';
    $base_dir = ROIDAICO_PLUGIN_DIR . 'includes/';
    $len = strlen( $prefix );
    if ( strncmp( $prefix, $class, $len ) !== 0 ) {
        return;
    }
    $relative_class = substr( $class, $len );
    $file = $base_dir . 'class-' . strtolower( str_replace( '_', '-', $relative_class ) ) . '.php';
    if ( file_exists( $file ) ) {
        require $file;
    }
} );
if ( !function_exists( 'roidaico_activate' ) ) {
    /**
     * Plugin activation hook
     */
    function roidaico_activate() {
        require_once ROIDAICO_PLUGIN_DIR . 'includes/class-activator.php';
        AICG\Activator::activate();
    }

}
register_activation_hook( __FILE__, 'roidaico_activate' );
if ( !function_exists( 'roidaico_deactivate' ) ) {
    /**
     * Plugin deactivation hook
     */
    function roidaico_deactivate() {
        require_once ROIDAICO_PLUGIN_DIR . 'includes/class-deactivator.php';
        AICG\Deactivator::deactivate();
    }

}
register_deactivation_hook( __FILE__, 'roidaico_deactivate' );
if ( !function_exists( 'roidaico_init' ) ) {
    /**
     * Initialize the plugin
     */
    function roidaico_init() {
        static $already_run = false;
        if ( $already_run ) {
            return;
        }
        $already_run = true;
        // Load text domain
        // Load text domain - handled automatically by WordPress.org
        // load_plugin_textdomain( 'roidnet-ai-content-generator', false, dirname( ROIDAICO_PLUGIN_BASENAME ) . '/languages' );
        // Initialize core plugin
        require_once ROIDAICO_PLUGIN_DIR . 'includes/class-plugin-core.php';
        $plugin = new AICG\Plugin_Core();
        $plugin->init();
    }

}
add_action( 'plugins_loaded', 'roidaico_init' );