<?php

/**
 * Plugin Name: AI Featured Image Generator
 * Description: One-click AI Featured Image Generator using OpenAI - Pro adds Google Gemini support and an AI Image Generator block.
 * Version: 1.8.1
 * Author: WPRaptor
 * Author URI: https://www.linkedin.com/in/amr-issa/
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: ai-featured-image-generator
 * Domain Path: /languages
 * Requires at least: 5.8
 * Requires PHP: 7.4
 *
 * @package AIFI
 */
$autoload = dirname( __FILE__ ) . '/vendor/autoload.php';
if ( file_exists( $autoload ) ) {
    require_once $autoload;
}
if ( !function_exists( 'afig_fs' ) ) {
    // Create a helper function for easy SDK access.
    function afig_fs() {
        global $afig_fs;
        if ( !isset( $afig_fs ) ) {
            // Include Freemius SDK.
            // SDK is auto-loaded through Composer
            $afig_fs = fs_dynamic_init( array(
                'id'               => '22299',
                'slug'             => 'ai-featured-image-generator',
                'type'             => 'plugin',
                'public_key'       => 'pk_8ee5817c3f9bac01d4aa681869233',
                'is_premium'       => false,
                'premium_suffix'   => 'Pro',
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'menu'             => array(
                    'slug'    => 'ai-featured-image-generator',
                    'parent'  => array(
                        'slug' => 'ai-featured-image-generator',
                    ),
                    'support' => false,
                ),
                'is_live'          => true,
                'is_org_compliant' => true,
            ) );
        }
        return $afig_fs;
    }

    // Init Freemius.
    afig_fs();
    // Hide Account page for free users
    afig_fs()->add_filter(
        'is_submenu_visible',
        function ( $is_visible, $submenu_id ) {
            if ( 'account' === $submenu_id && !afig_fs()->can_use_premium_code() ) {
                return false;
            }
            return $is_visible;
        },
        10,
        2
    );
    // Signal that SDK was initiated.
    do_action( 'afig_fs_loaded' );
}
if ( function_exists( 'afig_fs' ) ) {
    afig_fs()->set_basename( false, __FILE__ );
    // Filter plugin name to ensure correct display: remove "Pro" for free users, add for premium
    add_filter( 'all_plugins', function ( $plugins ) {
        $plugin_file = plugin_basename( __FILE__ );
        if ( isset( $plugins[$plugin_file] ) ) {
            $original_name = $plugins[$plugin_file]['Name'] ?? '';
            $can_use_premium = ( function_exists( 'afig_fs' ) ? afig_fs()->can_use_premium_code() : false );
            // Ensure correct name based on license: remove "Pro" for free users, add for premium
            $base_name = str_replace( ' Pro', '', $original_name );
            if ( $can_use_premium ) {
                // Premium users should see "Pro" suffix
                if ( strpos( $base_name, ' Pro' ) === false ) {
                    $plugins[$plugin_file]['Name'] = $base_name . ' Pro';
                }
            } else {
                // Free users should NOT see "Pro" suffix
                $plugins[$plugin_file]['Name'] = $base_name;
            }
        }
        return $plugins;
    }, 999 );
}
// If this file is called directly, abort.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Plugin version
define( 'AIFI_VERSION', '1.8.1' );
define( 'AIFI_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'AIFI_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
// Autoloader
spl_autoload_register( function ( $class ) {
    $prefix = 'AIFI\\';
    $base_dir = AIFI_PLUGIN_DIR . 'inc/';
    $len = strlen( $prefix );
    if ( strncmp( $prefix, $class, $len ) !== 0 ) {
        return;
    }
    $relative_class = substr( $class, $len );
    $file = $base_dir . 'class-' . str_replace( '\\', '/', strtolower( str_replace( '_', '-', $relative_class ) ) ) . '.php';
    if ( file_exists( $file ) ) {
        require $file;
    }
} );
// Initialize the plugin
function aifi_init() {
    $plugin = new AIFI\Plugin();
    $plugin->init();
}

add_action( 'plugins_loaded', 'aifi_init' );
// Activation hook
register_activation_hook( __FILE__, function () {
    // Get existing options to preserve settings during upgrade
    $existing = ( is_multisite() ? get_network_option( null, 'aifi_settings' ) : get_option( 'aifi_settings' ) );
    // Check if user can use premium features (Freemius may not be fully initialized during activation)
    $can_use_premium = function_exists( 'afig_fs' ) && afig_fs()->can_use_premium_code();
    // Set default options - Gemini settings only included for context but will be gated at runtime
    $defaults = array(
        'ai_provider'            => 'openai',
        'openai_api_key'         => '',
        'default_size'           => '1536x1024',
        'default_style'          => 'realistic',
        'output_format'          => 'webp',
        'image_quality'          => 90,
        'ai_model'               => 'gpt-image-1.5',
        'max_attempts'           => 3,
        'auto_generate'          => false,
        'auto_alt_text'          => 1,
        'alt_text_source'        => 'post_title',
        'alt_text_custom_format' => '{title}',
    );
    // Only set Gemini and Pro defaults for premium users
    if ( $can_use_premium ) {
        $defaults['gemini_api_key'] = '';
        $defaults['gemini_aspect_ratio'] = '16:9';
        $defaults['gemini_image_size'] = '2K';
        $defaults['enabled_post_types'] = array('post', 'page');
        // Pro users can customize this
    }
    // Migrate legacy 'api_key' to 'openai_api_key' if it exists
    if ( is_array( $existing ) && isset( $existing['api_key'] ) && !empty( $existing['api_key'] ) ) {
        $defaults['openai_api_key'] = $existing['api_key'];
    }
    // Merge with existing settings to preserve user configuration
    $settings = ( is_array( $existing ) ? array_merge( $defaults, $existing ) : $defaults );
    // Ensure new fields are present
    if ( !isset( $settings['ai_provider'] ) ) {
        $settings['ai_provider'] = 'openai';
    }
    // Force OpenAI for non-premium users who somehow have Gemini selected
    if ( !$can_use_premium && isset( $settings['ai_provider'] ) && $settings['ai_provider'] === 'gemini' ) {
        $settings['ai_provider'] = 'openai';
        $settings['ai_model'] = 'gpt-image-1.5';
    }
    if ( !isset( $settings['openai_api_key'] ) && isset( $settings['api_key'] ) ) {
        $settings['openai_api_key'] = $settings['api_key'];
    }
    // Only set Gemini defaults if premium (or preserve existing for upgrade scenarios)
    if ( $can_use_premium ) {
        if ( !isset( $settings['gemini_api_key'] ) ) {
            $settings['gemini_api_key'] = '';
        }
        if ( !isset( $settings['gemini_aspect_ratio'] ) ) {
            $settings['gemini_aspect_ratio'] = '16:9';
        }
        if ( !isset( $settings['gemini_image_size'] ) ) {
            $settings['gemini_image_size'] = '2K';
        }
    }
    if ( is_multisite() ) {
        update_network_option( null, 'aifi_settings', $settings );
    } else {
        update_option( 'aifi_settings', $settings );
    }
} );
// Deactivation hook
register_deactivation_hook( __FILE__, function () {
    // Clean up transients
    $all_options = wp_load_alloptions();
    foreach ( $all_options as $option_name => $value ) {
        if ( strpos( $option_name, '_transient_aifi_lock_' ) === 0 ) {
            $transient = str_replace( '_transient_', '', $option_name );
            delete_transient( $transient );
        }
    }
} );