<?php
/**
 * Plugin Name:       ExertPro FAQ AI for WooCommerce
 * Plugin URI:        https://wordpress.org/plugins/search/exertpro-faq-ai/
 * Description:       AI FAQ Generator & FAQ Schema for WooCommerce Products. Supports OpenAI, Google Gemini, Anthropic Claude, xAI Grok, and Moonshot Kimi.
 * Version:           1.0.0
 * Author:            ExertPro
 * Author URI:        https://exertpro.com/
 * License:           GPL-2.0+
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       exertpro-faq-ai
 * Domain Path:       /languages
 * Requires at least: 6.0
 * Tested up to:      7.0
 * Requires PHP:      7.4
 * Requires Plugins:  woocommerce
 * WC requires at least: 8.0
 * WC tested up to:   10.0
 *
 * @package EPWF
 *
 * EXTERNAL SERVICE DISCLOSURE:
 * This plugin connects to third-party AI APIs to generate FAQ content.
 * Only product title and description are transmitted — no customer or order data.
 * Providers: OpenAI, Google Gemini, Anthropic Claude, xAI Grok, Moonshot Kimi.
 */

defined( 'ABSPATH' ) || exit;

// ── Constants ──────────────────────────────────────────────────────────────────
define( 'EPWF_VERSION',      '1.0.0' );
define( 'EPWF_FILE',         __FILE__ );
define( 'EPWF_PATH',         plugin_dir_path( __FILE__ ) );
define( 'EPWF_URL',          plugin_dir_url( __FILE__ ) );
define( 'EPWF_INCLUDES',     EPWF_PATH . 'includes/' );
define( 'EPWF_ADMIN_DIR',    EPWF_PATH . 'admin/' );
define( 'EPWF_PUBLIC_DIR',   EPWF_PATH . 'public/' );
define( 'EPWF_ASSETS_URL',   EPWF_URL  . 'assets/' );
define( 'EPWF_OPTION_KEY',   'epwf_settings' );
define( 'EPWF_META_FAQS',    '_epwf_generated_faqs' );
define( 'EPWF_META_OVERRIDE','_epwf_manual_override' );
define( 'EPWF_META_ENABLED', '_epwf_enabled' );
define( 'EPWF_META_HASH',    '_epwf_content_hash' );
define( 'EPWF_RATE_LIMIT',   20 );
// Max words sent to AI — controls API token cost (Fix #8)
define( 'EPWF_DESC_WORD_LIMIT', 300 );

// ── Explicit Autoloader ────────────────────────────────────────────────────────
spl_autoload_register( function ( $class ) {
    static $map = null;
    if ( null === $map ) {
        $map = array(
            'EPWF\\Includes\\Settings'     => EPWF_INCLUDES . 'class-settings.php',
            'EPWF\\Includes\\AI_Client'    => EPWF_INCLUDES . 'class-ai-client.php',
            'EPWF\\Includes\\FAQ_Manager'  => EPWF_INCLUDES . 'class-faq-manager.php',
            'EPWF\\Includes\\Hooks'        => EPWF_INCLUDES . 'class-hooks.php',
            'EPWF\\Includes\\Loader'       => EPWF_INCLUDES . 'class-loader.php',
            'EPWF\\Includes\\Init'         => EPWF_INCLUDES . 'class-init.php',
            'EPWF\\Admin\\Admin'           => EPWF_ADMIN_DIR  . 'class-admin.php',
            'EPWF\\PublicFacing\\Frontend' => EPWF_PUBLIC_DIR . 'class-frontend.php',
        );
    }
    if ( isset( $map[ $class ] ) && is_readable( $map[ $class ] ) ) {
        require_once $map[ $class ];
    }
} );

// ── Boot ───────────────────────────────────────────────────────────────────────
add_action( 'plugins_loaded', function () {

    // Fix #6: WooCommerce missing → show notice AND self-deactivate for clean UX
    if ( ! class_exists( 'WooCommerce' ) ) {
        add_action( 'admin_notices', function () {
            echo wp_kses_post(
                '<div class="notice notice-error is-dismissible"><p>'
                . sprintf(
                    /* translators: %s: WooCommerce link */
                    __( '<strong>ProductFAQ AI</strong> has been deactivated because %s is not installed or active.', 'exertpro-faq-ai' ),
                    '<a href="https://woocommerce.com" target="_blank" rel="noopener noreferrer">WooCommerce</a>'
                )
                . '</p></div>'
            );
        } );

        // Self-deactivate cleanly (Fix #6)
        deactivate_plugins( plugin_basename( EPWF_FILE ) );

        // Suppress the "Plugin activated" notice that would appear
        if ( isset( $_GET['activate'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
            unset( $_GET['activate'] );
        }
        return;
    }

    static $booted = false;
    if ( $booted ) return;
    $booted = true;

    ( new \EPWF\Includes\Init() )->run();

}, 20 );

// ── Activation ─────────────────────────────────────────────────────────────────
register_activation_hook( EPWF_FILE, function () {
    if ( ! current_user_can( 'activate_plugins' ) ) return;

    // Guard: if WooCommerce is not active, bail out immediately
    if ( ! class_exists( 'WooCommerce' ) ) {
        // translators: %s: WooCommerce link
        wp_die(
            wp_kses_post( sprintf(
                __( '<strong>ProductFAQ AI</strong> requires %s to be installed and active. Please activate WooCommerce first.', 'exertpro-faq-ai' ),
                '<a href="https://wordpress.org/plugins/woocommerce/" target="_blank">WooCommerce</a>'
            ) ),
            esc_html__( 'Plugin Activation Error', 'exertpro-faq-ai' ),
            array( 'back_link' => true )
        );
    }

    if ( false === get_option( EPWF_OPTION_KEY ) ) {
        add_option( EPWF_OPTION_KEY, epwf_defaults(), '', false );
    }
    update_option( 'epwf_db_version', EPWF_VERSION, false );
    flush_rewrite_rules();
} );

register_deactivation_hook( EPWF_FILE, function () {
    flush_rewrite_rules();
} );

// ── Defaults ───────────────────────────────────────────────────────────────────
function epwf_defaults() {
    return array(
        'enabled'            => true,
        'ai_model'           => 'gpt-4o',
        'openai_key'         => '',
        'gemini_key'         => '',
        'anthropic_key'      => '',
        'grok_key'           => '',
        'kimi_key'           => '',
        'faq_count'          => 5,
        'additive_mode'      => true,
        'hook'               => 'woocommerce_after_single_product_summary',
        'priority'           => 10,
        'accordion_style'    => 'modern',
        'auto_generate'      => true,
        'color_primary'      => '#7c3aed',
        'color_hover'        => '#6d28d9',
        'color_active'       => '#5b21b6',
        'color_text'         => '#1f2937',
        'color_answer_text'  => '#374151',
        'color_bg'           => '#ffffff',
        'color_border'       => '#e5e7eb',
        'color_answer_bg'    => '#f9fafb',
        'font_size'          => 15,
        'question_font_size' => 15,
        'answer_font_size'   => 14,
        'wrap_margin_top'    => 32,
        'wrap_margin_bottom' => 32,
        'item_padding_v'     => 14,
        'item_padding_h'     => 18,
        'answer_padding_v'   => 12,
        'answer_padding_h'   => 18,
        'item_margin_bottom' => 0,
        'enable_schema'      => 1,
        'section_title'      => 'Frequently Asked Questions',
    );
}

// ── Filterable API timeout ─────────────────────────────────────────────────────
function epwf_api_timeout() {
    return (int) apply_filters( 'epwf_api_timeout', 30 );
}

/**
 * Fix #8: Trim product description to max word count before sending to AI.
 * Keeps API costs predictable. Word limit is filterable.
 *
 * @param  string $desc Raw product description.
 * @return string       Trimmed plain-text description.
 */
function epwf_trim_description( $desc ) {
    // Strip HTML first, then trim to word limit
    $plain = wp_strip_all_tags( $desc );
    $limit = (int) apply_filters( 'epwf_desc_word_limit', EPWF_DESC_WORD_LIMIT );
    return wp_trim_words( $plain, $limit, '' );
}

// ── Privacy Policy disclosure ──────────────────────────────────────────────────
add_action( 'admin_init', function () {
    if ( ! function_exists( 'wp_add_privacy_policy_content' ) ) return;
    wp_add_privacy_policy_content(
        'ExertPro FAQ AI for WooCommerce',
        wp_kses_post(
            '<p>' . esc_html__( 'ProductFAQ AI connects to external AI APIs to generate product FAQ content. Only product title and description are transmitted. No customer, order, or personally identifiable data is ever sent.', 'exertpro-faq-ai' ) . '</p>'
        )
    );
} );

// ── HPOS compatibility ─────────────────────────────────────────────────────────
add_action( 'before_woocommerce_init', function () {
    if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
            'custom_order_tables', EPWF_FILE, true
        );
    }
} );