<?php

/**
 * Plugin Name: Inqyra
 * Plugin URI: https://inqyra.com
 * Description: AI-powered chatbot with RAG (Retrieval-Augmented Generation) for your WordPress site. Uses your own AI API key.
 * Version: 1.1.5
 * Author: Ipportunities B.V.
 * Author URI: https://ippo.nl
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain: inqyra
 * Requires at least: 6.2
 * Requires PHP: 8.1
 *
 */
// If this file is called directly, abort.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Freemius SDK initialization.
if ( !function_exists( 'inqyra_fs' ) ) {
    // Create a helper function for easy SDK access.
    function inqyra_fs() {
        global $inqyra_fs;
        if ( !isset( $inqyra_fs ) ) {
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/vendor/freemius/wordpress-sdk/start.php';
            $inqyra_fs = fs_dynamic_init( array(
                'id'               => '24535',
                'slug'             => 'inqyra',
                'type'             => 'plugin',
                'public_key'       => 'pk_36aaafc33fce47cf5164b44a5e7a8',
                'is_premium'       => false,
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => true,
                'menu'             => array(
                    'slug'       => 'inqyra',
                    'first-path' => 'admin.php?page=inqyra-wizard',
                    'support'    => false,
                ),
                'is_live'          => true,
            ) );
        }
        return $inqyra_fs;
    }

    // Init Freemius.
    inqyra_fs();
    // Signal that SDK was initiated.
    do_action( 'inqyra_fs_loaded' );
    // When a license is activated, flag that a re-crawl is needed so the
    // user can index all content without the free-tier 10-page limit.
    inqyra_fs()->add_action( 'after_license_activation', function () {
        update_option( 'inqyra_upgrade_recrawl_needed', true );
    } );
    // Point Freemius to the plugin's own icon instead of the SDK cached copy.
    inqyra_fs()->add_filter( 'plugin_icon', function () {
        return dirname( __FILE__ ) . '/assets/img/inqyra.png';
    } );
    // Uninstall cleanup — hooked into Freemius so uninstall feedback is sent first.
    inqyra_fs()->add_action( 'after_uninstall', 'inqyra_fs_uninstall_cleanup' );
}
/**
 * Check if the current site has a premium (paid) license.
 *
 * Accepts both 'inqyrapro' and 'inqyrabusiness' Freemius plan slugs
 * for backwards compatibility with existing licenses.
 *
 * @return bool True if premium.
 */
function inqyra_is_premium() : bool {
    return false;
}

/**
 * Clean up all plugin data on uninstall.
 *
 * Called by Freemius after the uninstall event is reported.
 */
function inqyra_fs_uninstall_cleanup() {
    global $wpdb, $wp_filesystem;
    WP_Filesystem();
    // Delete all plugin tables.
    $tables = array(
        $wpdb->prefix . 'inqyra_agents',
        $wpdb->prefix . 'inqyra_knowledge_chunks',
        $wpdb->prefix . 'inqyra_chunk_links',
        $wpdb->prefix . 'inqyra_documents',
        $wpdb->prefix . 'inqyra_synonyms',
        $wpdb->prefix . 'inqyra_webhooks',
        $wpdb->prefix . 'inqyra_webhook_logs',
        $wpdb->prefix . 'inqyra_conversations',
        $wpdb->prefix . 'inqyra_messages',
        $wpdb->prefix . 'inqyra_crawl_runs'
    );
    foreach ( $tables as $table ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is built from $wpdb->prefix + hardcoded strings.
        $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $table ) );
    }
    // Delete plugin options.
    delete_option( 'inqyra_settings' );
    delete_option( 'inqyra_db_version' );
    delete_option( 'inqyra_wizard_completed' );
    // Delete all transients.
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table query.
    $wpdb->query( $wpdb->prepare(
        'DELETE FROM %i
             WHERE option_name LIKE %s
             OR option_name LIKE %s',
        $wpdb->options,
        $wpdb->esc_like( '_transient_inqyra_' ) . '%',
        $wpdb->esc_like( '_transient_timeout_inqyra_' ) . '%'
    ) );
    // Clear scheduled cron events.
    wp_clear_scheduled_hook( 'inqyra_process_embeddings' );
    wp_clear_scheduled_hook( 'inqyra_archive_conversations' );
    // Delete uploaded files.
    $upload_dir = wp_upload_dir();
    $inqyra_dir = $upload_dir['basedir'] . '/inqyra';
    if ( is_dir( $inqyra_dir ) ) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($inqyra_dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
        $real_inqyra_dir = realpath( $inqyra_dir );
        foreach ( $files as $file ) {
            $real_path = $file->getRealPath();
            if ( strpos( $real_path, $real_inqyra_dir ) !== 0 ) {
                continue;
            }
            if ( $file->isDir() ) {
                $wp_filesystem->rmdir( $real_path );
            } else {
                wp_delete_file( $real_path );
            }
        }
        $wp_filesystem->rmdir( $inqyra_dir );
    }
    // Delete transformer cache.
    $cache_dir = WP_CONTENT_DIR . '/cache/transformers';
    if ( is_dir( $cache_dir ) ) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($cache_dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
        $real_cache_dir = realpath( $cache_dir );
        foreach ( $files as $file ) {
            $real_path = $file->getRealPath();
            if ( strpos( $real_path, $real_cache_dir ) !== 0 ) {
                continue;
            }
            if ( $file->isDir() ) {
                $wp_filesystem->rmdir( $real_path );
            } else {
                wp_delete_file( $real_path );
            }
        }
        $wp_filesystem->rmdir( $cache_dir );
    }
}

/**
 * Plugin version.
 */
define( 'INQYRA_VERSION', '1.1.5' );
/**
 * Plugin directory path.
 */
define( 'INQYRA_PATH', plugin_dir_path( __FILE__ ) );
/**
 * Plugin directory URL.
 */
define( 'INQYRA_URL', plugin_dir_url( __FILE__ ) );
/**
 * Plugin basename.
 */
define( 'INQYRA_BASENAME', plugin_basename( __FILE__ ) );
/**
 * Minimum PHP version required.
 */
define( 'INQYRA_MIN_PHP_VERSION', '8.1' );
/**
 * Minimum WordPress version required.
 */
define( 'INQYRA_MIN_WP_VERSION', '6.0' );
/**
 * Check PHP version compatibility.
 */
if ( version_compare( PHP_VERSION, INQYRA_MIN_PHP_VERSION, '<' ) ) {
    add_action( 'admin_notices', function () {
        $message = sprintf( 
            /* translators: 1: Required PHP version, 2: Current PHP version */
            __( 'Inqyra requires PHP version %1$s or higher. You are running version %2$s. Please upgrade PHP to use this plugin.', 'inqyra' ),
            INQYRA_MIN_PHP_VERSION,
            PHP_VERSION
         );
        echo '<div class="notice notice-error"><p>' . esc_html( $message ) . '</p></div>';
    } );
    return;
}
/**
 * Check WordPress version compatibility.
 */
if ( version_compare( $GLOBALS['wp_version'], INQYRA_MIN_WP_VERSION, '<' ) ) {
    add_action( 'admin_notices', function () {
        $message = sprintf( 
            /* translators: 1: Required WordPress version, 2: Current WordPress version */
            __( 'Inqyra requires WordPress version %1$s or higher. You are running version %2$s. Please upgrade WordPress to use this plugin.', 'inqyra' ),
            INQYRA_MIN_WP_VERSION,
            $GLOBALS['wp_version']
         );
        echo '<div class="notice notice-error"><p>' . esc_html( $message ) . '</p></div>';
    } );
    return;
}
/**
 * Autoloader for plugin classes.
 */
spl_autoload_register( function ( $class ) {
    // Plugin namespace prefix
    $prefix = 'Inqyra\\';
    // Check if the class uses our namespace
    if ( strpos( $class, $prefix ) !== 0 ) {
        return;
    }
    // Get the relative class name
    $relative_class = substr( $class, strlen( $prefix ) );
    // Convert namespace separators to directory separators
    $relative_path = str_replace( '\\', '/', $relative_class );
    // Map class name to file name (e.g., Inqyra\Admin\Admin -> admin/class-inqyra-admin.php)
    $parts = explode( '/', $relative_path );
    $class_name = array_pop( $parts );
    $file_name = 'class-inqyra-' . strtolower( preg_replace( '/([a-z])([A-Z])/', '$1-$2', $class_name ) ) . '.php';
    // Build the file path
    if ( !empty( $parts ) ) {
        $directory = strtolower( implode( '/', $parts ) );
        $file = INQYRA_PATH . $directory . '/' . $file_name;
    } else {
        $file = INQYRA_PATH . 'includes/' . $file_name;
    }
    // Load the file if it exists
    if ( file_exists( $file ) ) {
        require_once $file;
    }
} );
/**
 * Load Composer autoloader for runtime dependencies.
 *
 * In production: premium/vendor/ has runtime deps (pdfparser, phpword).
 * In development: vendor/ has all deps (runtime + dev) from composer install.
 */
if ( inqyra_fs()->is__premium_only() && file_exists( INQYRA_PATH . 'premium/vendor/autoload.php' ) ) {
    require_once INQYRA_PATH . 'premium/vendor/autoload.php';
}
if ( file_exists( INQYRA_PATH . 'vendor/autoload.php' ) ) {
    require_once INQYRA_PATH . 'vendor/autoload.php';
}
/**
 * Code that runs during plugin activation.
 */
function inqyra_activate() {
    require_once INQYRA_PATH . 'includes/class-inqyra-activator.php';
    Inqyra_Activator::activate();
}

/**
 * Code that runs during plugin deactivation.
 */
function inqyra_deactivate() {
    require_once INQYRA_PATH . 'includes/class-inqyra-deactivator.php';
    Inqyra_Deactivator::deactivate();
}

register_activation_hook( __FILE__, 'inqyra_activate' );
register_deactivation_hook( __FILE__, 'inqyra_deactivate' );
/**
 * Begins execution of the plugin.
 */
function inqyra_run() {
    require_once INQYRA_PATH . 'includes/class-inqyra.php';
    $plugin = new Inqyra();
    $plugin->run();
}

inqyra_run();