<?php

/**
 * Plugin Name: HD SofT AI Summary
 * Plugin URI: https://www.hdsoft.fi/hdsoft-ai-summary
 * Description: Automatically generates AI-powered summaries for posts using OpenRouter API integration.
 * Version: 1.0.0
 * Author: HD SofT
 * Author URI: https://hdsoft.fi/
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: hd-soft-ai-summary
 * Domain Path: /languages
 * Requires at least: 6.0
 * Tested up to: 6.7
 * Requires PHP: 8.0
 *
 * @package HDSofT\AISummary
 */
// Prevent direct access
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Define plugin constants
define( 'HDSOFT_AI_SUMMARY_VERSION', '1.0.0' );
define( 'HDSOFT_AI_SUMMARY_PLUGIN_FILE', __FILE__ );
define( 'HDSOFT_AI_SUMMARY_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'HDSOFT_AI_SUMMARY_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'HDSOFT_AI_SUMMARY_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
// Load Pro bootstrap if available (Pro build only)
if ( file_exists( __DIR__ . '/pro/bootstrap.php' ) ) {
    require_once __DIR__ . '/pro/bootstrap.php';
}
// Initialize Freemius SDK first
if ( !function_exists( 'hdsoft_ai_summary_fs' ) ) {
    // Create a helper function for easy SDK access.
    function hdsoft_ai_summary_fs() {
        global $hdsoft_ai_summary_fs;
        if ( !isset( $hdsoft_ai_summary_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
            // Dynamic configuration based on Pro build
            $is_pro_build = defined( 'HDSUM_PRO' ) && HDSUM_PRO;
            $hdsoft_ai_summary_fs = fs_dynamic_init( array(
                'id'               => '20479',
                'slug'             => 'hd-soft-ai-summary',
                'type'             => 'plugin',
                'public_key'       => 'pk_d6e9125a3ce5b161f359b4f658906',
                'is_premium'       => false,
                'has_paid_plans'   => true,
                'has_addons'       => false,
                'is_org_compliant' => true,
                'menu'             => array(
                    'slug'    => 'hd-soft-ai-summary',
                    'contact' => false,
                    'support' => false,
                    'parent'  => array(
                        'slug' => 'options-general.php',
                    ),
                ),
                'is_live'          => true,
            ) );
        }
        return $hdsoft_ai_summary_fs;
    }

    // Init Freemius.
    hdsoft_ai_summary_fs();
    // Signal that SDK was initiated.
    do_action( 'hdsoft_ai_summary_fs_loaded' );
    // Register Freemius uninstall cleanup hook
    hdsoft_ai_summary_fs()->add_action( 'after_uninstall', 'hdsoft_ai_summary_fs_uninstall_cleanup' );
}
/**
 * Freemius uninstall cleanup functions
 */
/**
 * Remove plugin options
 */
function hdsoft_ai_summary_remove_options() {
    // Remove plugin settings
    delete_option( 'hdsoft_ai_summary_settings' );
    // Remove API key (stored separately with autoload=false)
    delete_option( 'hdsoft_ai_summary_openrouter_api_key' );
    // Remove any other plugin-specific options
    delete_option( 'hdsoft_ai_summary_version' );
    delete_option( 'hdsoft_ai_summary_activation_time' );
}

/**
 * Remove post meta data
 */
function hdsoft_ai_summary_remove_post_meta() {
    // Remove all summary-related post meta using WordPress core function
    $meta_keys = array(
        '_hdsoft_ai_summary_title',
        '_hdsoft_ai_summary_text',
        '_hdsoft_ai_summary_hash',
        '_hdsoft_ai_summary_manual'
    );
    foreach ( $meta_keys as $meta_key ) {
        // WordPress core function removes all post meta with this key across all posts
        delete_post_meta_by_key( $meta_key );
    }
}

/**
 * Remove user meta data (if any)
 */
function hdsoft_ai_summary_remove_user_meta() {
    // Remove any user preferences or settings using WordPress core function
    $user_meta_keys = array('hdsoft_ai_summary_dismissed_notices', 'hdsoft_ai_summary_user_preferences');
    foreach ( $user_meta_keys as $meta_key ) {
        // WordPress core function removes all user meta with this key across all users
        delete_metadata(
            'user',
            0,
            $meta_key,
            '',
            true
        );
    }
}

/**
 * Remove transients
 */
function hdsoft_ai_summary_remove_transients() {
    global $wpdb;
    // Remove plugin-specific transients
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key
    $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", '_transient_hdsoft_ai_summary_%', '_transient_timeout_hdsoft_ai_summary_%' ) );
}

/**
 * Remove custom database tables (if any were created)
 */
function hdsoft_ai_summary_remove_custom_tables() {
    // This plugin doesn't create custom tables, but if it did in the future,
    // they would be removed here
}

/**
 * Remove directory and all its contents
 *
 * @param string $dir Directory path.
 */
function hdsoft_ai_summary_remove_directory(  $dir  ) {
    if ( !is_dir( $dir ) ) {
        return;
    }
    // Initialize WordPress file system
    require_once ABSPATH . 'wp-admin/includes/file.php';
    WP_Filesystem();
    global $wp_filesystem;
    if ( $wp_filesystem ) {
        $wp_filesystem->delete( $dir, true );
    }
}

/**
 * Clear any cached data
 */
function hdsoft_ai_summary_clear_cache() {
    // Clear object cache if using persistent caching
    if ( function_exists( 'wp_cache_flush' ) ) {
        wp_cache_flush();
    }
    // Clear any plugin-specific cache directories
    $upload_dir = wp_upload_dir();
    $cache_dir = trailingslashit( $upload_dir['basedir'] ) . 'hdsoft-ai-summary-cache/';
    if ( is_dir( $cache_dir ) ) {
        hdsoft_ai_summary_remove_directory( $cache_dir );
    }
}

/**
 * Main Freemius uninstall cleanup function
 */
function hdsoft_ai_summary_fs_uninstall_cleanup() {
    // Check if we should preserve data (could be a setting)
    $preserve_data = get_option( 'hdsoft_ai_summary_preserve_data_on_uninstall', false );
    if ( $preserve_data ) {
        // Only remove the preserve flag itself
        delete_option( 'hdsoft_ai_summary_preserve_data_on_uninstall' );
        return;
    }
    // Remove all plugin data
    hdsoft_ai_summary_remove_options();
    hdsoft_ai_summary_remove_post_meta();
    hdsoft_ai_summary_remove_user_meta();
    hdsoft_ai_summary_remove_transients();
    hdsoft_ai_summary_remove_custom_tables();
    hdsoft_ai_summary_clear_cache();
    // Flush rewrite rules
    flush_rewrite_rules();
}

/**
 * Check for Pro features
 *
 * @return bool
 */
function hdsoft_ai_summary_is_pro() {
    return hdsoft_ai_summary_fs()->is_plan( 'pro', true );
}

/**
 * Check if branding should be shown (always false now)
 *
 * @return bool
 */
function hdsoft_ai_summary_show_branding() {
    return false;
}

/**
 * Initialize the plugin
 */
function hdsoft_ai_summary_init() {
    // Include required files
    require_once HDSOFT_AI_SUMMARY_PLUGIN_DIR . 'includes/class-plugin.php';
    // Initialize main plugin class
    HDSofT\AISummary\Plugin::get_instance();
    // Trigger initialization action
    do_action( 'hdsoft_ai_summary_init' );
}

// Initialize plugin after all plugins are loaded
add_action( 'plugins_loaded', 'hdsoft_ai_summary_init' );
/**
 * Activation hook
 */
function hdsoft_ai_summary_activate() {
    $default_settings = array(
        'auto_generate'   => true,
        'append_position' => 'after',
        'model_name'      => 'anthropic/claude-3.5-sonnet',
        'max_tokens'      => 300,
        'prompt_style'    => 'narrative',
    );
    if ( !get_option( 'hdsoft_ai_summary_settings' ) ) {
        add_option( 'hdsoft_ai_summary_settings', $default_settings );
    }
    // Flush rewrite rules for REST API
    flush_rewrite_rules();
}

register_activation_hook( __FILE__, 'hdsoft_ai_summary_activate' );
/**
 * Deactivation hook
 */
function hdsoft_ai_summary_deactivate() {
    // Flush rewrite rules
    flush_rewrite_rules();
}

register_deactivation_hook( __FILE__, 'hdsoft_ai_summary_deactivate' );