<?php
/**
 * Plugin Name: AI App Onsite
 * Description: AIappOnsite - AI Web App Creator WP Plugin allows users to create their own AI-powered web app and launch it on their own site with no additional development needed. AI App Onsite web app creator is an AI web app builder for WordPress.
 * Version: 1.2.8
 * Author: By AIappOnsite
 * Author URI: https://aiapponsite.com/
 * Text Domain: ai-app-onsite
 * License: GPL-2.0-or-later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 */

define('AI_APP_ONSITE_VERSION', '1.2.8');
define('AI_APP_ONSITE_TOS_VERSION', '2025.08.01');

// Enqueue WordPress's jQuery
add_action('wp_enqueue_scripts', 'ai_app_onsite_enqueue_scripts');
function ai_app_onsite_enqueue_scripts()
{
    wp_enqueue_script('jquery');
}

if (version_compare(PHP_VERSION, '7.0', '<')) {
    add_action('admin_notices', function () {
        echo '<div class="notice notice-error"><p><strong>AI App Onsite Plugin:</strong> This plugin requires PHP 7.0 or higher. Your server is running PHP ' . PHP_VERSION . '.</p></div>';
    });
    return;
}

add_filter('cron_schedules', function ($schedules) {
    $schedules['validatelicense'] = [
        'interval' => 86400,
        'display' => __('Once Everyday'),
    ];
    $schedules['checkpluginversion'] = [
        'interval' => 43200, // 12 hours in seconds
        'display' => __('Twice Daily'),
    ];
    $schedules['userStats'] = [
        'interval' => 86400,
        'display' => __('Once Daily at Midnight'),
    ];
    return $schedules;
});


// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

define('AI_APP_ONSITE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('AI_APP_ONSITE_PLUGIN_URL', plugin_dir_url(__FILE__));


if ( ! function_exists( 'ai_app_onsite_get_version_meta' ) ) {
    function ai_app_onsite_get_version_meta() {
        $response = wp_remote_get( 'https://aiapponsite.com/prod/ai-app-onsite-version.php?nocache=' . time());

        if ( is_wp_error( $response ) ) {
            return [
                'error'   => 'Request failed',
                'message' => $response->get_error_message(),
            ];
        }

        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        if ( ! is_array( $data ) ) {
            error_log( 'Invalid JSON returned from version.php: ' . $body );
            return [
                'error'   => 'Invalid response',
                'message' => $body,
            ];
        }

        return $data;
    }
}

function ai_app_onsite_is_premium_active() {
	global $wpdb;
	$table = $wpdb->prefix . 'ai_app_onsite_license_settings';

	// Check if 'key_disable_status' column exists
	$column_exists = $wpdb->get_var(
		$wpdb->prepare(
			"SHOW COLUMNS FROM {$table} LIKE %s",
			'key_disable_status'
		)
	);

	$columns = 'key_status';
	if ( ! empty( $column_exists ) ) {
		$columns .= ', key_disable_status';
	}

	$row = $wpdb->get_row(
		"SELECT {$columns} FROM {$table} LIMIT 1",
		ARRAY_A
	);

	if ( empty( $row ) ) {
		return false;
	}

	if (
		isset( $row['key_disable_status'] ) && $row['key_disable_status'] === 'false' &&
		isset( $row['key_status'] ) && $row['key_status'] === 'ACTIVE' &&
		is_dir( AI_APP_ONSITE_PLUGIN_DIR . 'premium' )
	) {
		return true;
	}

	return false;
}

function ai_app_onsite_is_premium_disabled() {
	global $wpdb;
	$table = $wpdb->prefix . 'ai_app_onsite_license_settings';

	// Check if 'key_disable_status' column exists
	$column_exists = $wpdb->get_var(
		$wpdb->prepare(
			"SHOW COLUMNS FROM {$table} LIKE %s",
			'key_disable_status'
		)
	);

	$columns = 'key_status';
	if ( ! empty( $column_exists ) ) {
		$columns .= ', key_disable_status, license_key';
	}

	$row = $wpdb->get_row(
		"SELECT {$columns} FROM {$table} LIMIT 1",
		ARRAY_A
	);

	if ( empty( $row ) ) {
		return false;
	}

	if (
		isset( $row['key_disable_status'] ) && $row['key_disable_status'] === 'true' &&
		isset( $row['key_status'] ) && $row['key_status'] === 'ACTIVE' &&
		! empty( $row['license_key'] ) &&
		is_dir( AI_APP_ONSITE_PLUGIN_DIR . 'premium' )
	) {
		return true;
	}

	return false;
}

function ai_app_onsite_include_path(): string {
    return plugin_dir_path(__FILE__) . (ai_app_onsite_is_premium_active() ? 'premium/includes/' : 'includes/');
}

function ai_app_onsite_handler_path(): string {
    return plugin_dir_path(__FILE__) . (ai_app_onsite_is_premium_active() ? 'premium/handler/' : 'handler/');
}

function ai_app_onsite_assets_path(): string {
    return plugin_dir_url(__FILE__) . (ai_app_onsite_is_premium_active() ? 'premium/assets/' : 'assets/');
}

// Include necessary files
if (! function_exists('ai_app_onsite_init')) {
    function ai_app_onsite_init(): void {
        ai_app_onsite_config(); 

        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-admin.php';
        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-plugin-settings.php';
        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-app-properties.php';
        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-model-settings.php';
        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-field-selector.php';
        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-prompt-editor.php';
        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-app-preview.php';
        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-email-settings.php';
        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-db-handler.php';

        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-plugin-settings.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-app-properties.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-model-settings.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-field-selector.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-prompt-editor.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-app-preview.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-app-license.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-openAi-api.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-user-stats.php';
        require_once ai_app_onsite_handler_path() . 'ai-app-onsite-email-settings.php';

	    if(ai_app_onsite_is_premium_active()) {
		    require_once ai_app_onsite_handler_path() . 'ai-app-onsite-webhook-handler.php';
		    require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-rag-reference.php';
		    require_once ai_app_onsite_handler_path() . 'ai-app-onsite-rag-reference.php';
	    }

        $ai_app_onsite_admin = new AI_App_Onsite_Admin();
    }
}

if (!function_exists('ai_app_onsite_enqueue_admin_script')) {
    function ai_app_onsite_enqueue_admin_script($hook): void {
        // Only load on plugin settings page - adjust this to match your plugin's actual settings page slug
        if ($hook !== 'toplevel_page_ai-app-onsite-menu') {
            return;
        }

        // Enqueue CSS for admin
        wp_enqueue_style('ai-app-onsite-style', ai_app_onsite_assets_path() . 'css/ai-app-onsite-style.css', array(), time());
        wp_enqueue_style('ai-app-onsite-fafa-style', ai_app_onsite_assets_path() . 'css/fontawesome.min.css', array(), time());

        if(ai_app_onsite_is_premium_active()) {
            wp_enqueue_style('ai-app-onsite-rag-reference-style', ai_app_onsite_assets_path() . 'css/ai-app-onsite-rag-reference.css', array(), time());
        }

        wp_enqueue_style('ai-app-onsite-quill-style', ai_app_onsite_assets_path() . 'css/quill.snow.css', array(), time());
        wp_enqueue_style('ai-app-onsite-atom-one-dark-style', ai_app_onsite_assets_path() . 'css/atom-one-dark.min.css', array(), time());
        wp_enqueue_style('ai-app-onsite-katex-style', ai_app_onsite_assets_path() . 'css/katex.min.css', array(), time());


        // Check if Bootstrap is already loaded
	    global $wp_scripts, $wp_styles;
	    $is_bootstrap_loaded = false;

	    foreach ($wp_scripts->registered as $registered_script) {
		    if (str_contains($registered_script->src, 'bootstrap')) {
			    $is_bootstrap_loaded = true;
			    break;
		    }
	    }

	    if (!$is_bootstrap_loaded) {
		    foreach ($wp_styles->registered as $registered_style) {
			    if (str_contains($registered_style->src, 'bootstrap')) {
				    $is_bootstrap_loaded = true;
				    break;
			    }
		    }
	    }

        wp_enqueue_script('jquery-ui-sortable');

        // Enqueue Bootstrap if not already loaded
        if (!$is_bootstrap_loaded) {
            wp_register_script('bootstrape-poper-script', ai_app_onsite_assets_path() . 'js/popper.min.js', array('jquery'), time(), true);
            wp_enqueue_script('bootstrape-poper-script');

            wp_register_script('bootstrape-script-script', ai_app_onsite_assets_path() . 'js/bootstrap.min.js', array('jquery'), time(), true);
            wp_enqueue_script('bootstrape-script-script');

	        wp_register_style('ai_app_onsite_style_bootstrap',  ai_app_onsite_assets_path() . 'css/bootstrap.min.css', array(), time());
	        wp_enqueue_style('ai_app_onsite_style_bootstrap');
        }

        $shared_assets_url = plugin_dir_url(__FILE__) . 'assets/';
        wp_register_script(
            'ai-app-onsite-color-picker',
            $shared_assets_url . 'js/ai-app-onsite-color-picker.js',
            array('jquery'),
            time(),
            true
        );

        // All other scripts
        $scripts = [
            'admin-script' => [
                'file' => 'ai-app-onsite-admin.js',
                'deps' => ['jquery'],
            ],
            'ai-app-onsite-field-selector-script' => [
                'file' => 'ai-app-onsite-field-selector.js',
                'deps' => ['jquery'],
            ],
            'email-interation-script' => [
                'file' => 'ai-app-onsite-email-settings.js',
                'deps' => ['jquery'],
            ],
            'blockword-script-script' => [
                'file' => 'ai-app-onsite-blockword.js',
                'deps' => ['jquery'],
            ],
            'model_settings' => [
                'file' => 'ai-app-onsite-model-settings.js',
                'deps' => ['jquery'],
            ],
            'plugin_settings-script' => [
                'file' => 'ai-app-onsite-plugin-settings.js',
                'deps' => ['jquery'],
            ],
            'app_properties' => [
                'file' => 'ai-app-onsite-app-properties.js',
                'deps' => ['jquery'],
            ],
            'app-preview-script' => [
                'file' => 'ai-app-onsite-app-preview.js',
                'deps' => ['jquery', 'ai-app-onsite-color-picker'],
            ],
            'ai-app-onsite-jquery-sweetalert' => [
                'file' => 'sweetalert2.all.min.js',
                'deps' => ['jquery'],
            ],

            'ai-app-onsite-jquery-choice' => [
                'file' => 'choice.min.js',
                'deps' => ['jquery'],
            ],
            'terms-of-service-script' => [
                'file' => 'jspdf.umd.min.js',
                'deps' => ['jquery'],
            ],
            'ai-app-onsite-quill-script' => [
                'file' => 'quill.js',
                'deps' => ['jquery'],
            ],
            'ai-app-onsite-katex-script' => [
                'file' => 'katex.min.js',
                'deps' => ['jquery'],
            ],
            'ai-app-onsite-highlight-script' => [
                'file' => 'highlight.min.js',
                'deps' => ['jquery'],
            ],
            'ai-app-onsite-quill-init' => [
                'file' => 'quill-init.js',
                'deps' => ['ai-app-onsite-quill-script'],
            ],
            'prompt-editor-script' => [
                'file' => 'ai-app-onsite-prompt-editor.js',
                'deps' => ['ai-app-onsite-quill-init'],
            ],
        ];

		// only available in the premium version
		if(ai_app_onsite_is_premium_active()) {
			$scripts['ai-app-onsite-webhook-script'] = [
				'file' => 'ai-app-onsite-webhook-manager.js',
				'deps' => ['jquery'],
			];
			$scripts['ai-app-onsite-rag-reference-script'] = [
				'file' => 'ai-app-onsite-rag-reference.js',
				'deps' => ['jquery'],
			];
		}


        foreach ($scripts as $handle => $data) {
            $file = is_array($data) ? $data['file'] : $data;
            $deps = is_array($data) && isset($data['deps']) ? $data['deps'] : ['jquery'];

            wp_register_script($handle, ai_app_onsite_assets_path() . 'js/' . $file, $deps, time(), true);
            wp_enqueue_script($handle);
        }

        

        // Pass the fresh installation flag to JavaScript
        $is_fresh_install = get_option('ai_app_onsite_fresh_install', false);
        
        // Localize the main admin script
        wp_localize_script(
            'admin-script',
            'myPluginAjax',
            array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'deleteNonce' => wp_create_nonce('ai_app_onsite_delete_field_nonce'),
                'downloadUserStatsNonce' => wp_create_nonce('ai_app_onsite_download_user_stats_nonce'),
                'fieldSelectorOrder' => wp_create_nonce('ai_app_onsite_fields_selector_order_nonce'),
                'isFreshInstall' => $is_fresh_install,
            )
        );


        // Remove the flag after it's been used
        if ($is_fresh_install) {
            delete_option('ai_app_onsite_fresh_install');
        }

        wp_add_inline_script('admin-script', 'var AI_APP_ONSITE_PLUGIN_URL = "' . esc_url(AI_APP_ONSITE_PLUGIN_URL) . '";', 'before');
    }

    add_action('admin_enqueue_scripts', 'ai_app_onsite_enqueue_admin_script');
}

if (!function_exists('ai_app_onsite_enqueue_scripts_frontend')) {
    // Enqueue script for both frontend and admin
    function ai_app_onsite_enqueue_scripts_frontend()
    {
        // Enqueue your script with time() for cache-busting
	    if(ai_app_onsite_is_premium_active()){
		    wp_enqueue_script('ai-app-onsite-js-pdf-library', plugin_dir_url(__FILE__) .'premium/assets/js/jspdf.umd.min.js', array('jquery'), time(), true);

	    }
		wp_enqueue_script('ai-app-onsite-openai-api-script', ai_app_onsite_assets_path() . 'js/ai-app-onsite-openai-api.js', array('jquery'), time(), true);

        // Enqueue the session script
        wp_enqueue_script('ai-app-onsite-session-script', ai_app_onsite_assets_path() . 'js/ai-app-onsite-session.js', array('jquery'), time(), true);

        // Localize the script with the AJAX URL
        wp_localize_script('ai-app-onsite-openai-api-script', 'myPluginAjax', array(
            'ajaxurl' => admin_url('admin-ajax.php')
        ));
    }
    // Add action to enqueue scripts for both frontend and admin
    add_action('wp_enqueue_scripts', 'ai_app_onsite_enqueue_scripts_frontend');
}

function AI_APP_ONSITE_My_Form_Block_Assets()
{
    // Enqueue block editor script with file time for versioning (cache-busting)
    wp_enqueue_script(
        'ai-app-onsite-form-block-editor',
        plugins_url('assets/js/ai-app-onsite-form-block.js', __FILE__),
        array('wp-blocks', 'wp-element', 'wp-components', 'wp-editor'),
        filemtime(plugin_dir_path(__FILE__) . 'assets/js/ai-app-onsite-form-block.js')
    );
}

add_action('enqueue_block_editor_assets', 'AI_APP_ONSITE_My_Form_Block_Assets');

if (!function_exists('ai_app_onsite_enqueue_style')) {
	function ai_app_onsite_enqueue_style()
	{
		// Enqueue styles with time() for cache-busting
		// Register and enqueue stylesheets for the admin area
		wp_register_style('ai_app_onsite_form_style', ai_app_onsite_assets_path() . 'css/ai-app-onsite-form-style.css', array(), time());
		wp_enqueue_style('ai_app_onsite_form_style');

        wp_register_style('ai-app-onsite-fafa-style', ai_app_onsite_assets_path() . 'css/fontawesome.min.css', array(), time());
        wp_enqueue_style('ai-app-onsite-fafa-style');
		// Check if Bootstrap is already loaded
		global $wp_scripts, $wp_styles;
		$is_bootstrap_loaded = false;

		foreach ($wp_scripts->registered as $registered_script) {
			if (str_contains($registered_script->src, 'bootstrap')) {
				$is_bootstrap_loaded = true;
				break;
			}
		}

		if (!$is_bootstrap_loaded) {
			foreach ($wp_styles->registered as $registered_style) {
				if (str_contains($registered_style->src, 'bootstrap')) {
					$is_bootstrap_loaded = true;
					break;
				}
			}
		}

		// Enqueue Bootstrap if not already loaded
		if (!$is_bootstrap_loaded) {
			wp_register_style('ai_app_onsite_style_bootstrap', ai_app_onsite_assets_path() . 'css/bootstrap.min.css', array(), time());
			wp_enqueue_style('ai_app_onsite_style_bootstrap');
		}


	}

	// Enqueue styles for both admin and frontend
	add_action('admin_print_styles', 'ai_app_onsite_enqueue_style');
	add_action('wp_enqueue_scripts', 'ai_app_onsite_enqueue_style');
}

if (! function_exists('ai_app_onsite_activate')) {
    // Activation hook callback function
    function ai_app_onsite_activate()
    {
        global $wpdb; // Access the global $wpdb variable

        aiapp_set_option('ai_app_onsite_fresh_install', true);
        
        aiapp_register_client('https://aiapponsite.com/');
    }
}

if (! function_exists('ai_app_onsite_config')) {
    function ai_app_onsite_config() {
        global $wpdb;

        /**
         * To initializes and stores encryption keys and license-server URL to avoid hard-coding in WordPress options.
         * 
         * - The `ai_app_onsite_encryption_key` is a 256-bit encryption key generated using `random_bytes`.
         * - The `ai_app_onsite_encryption_iv` is a 16-byte initialization vector (IV) encoded in Base64.
         * - The `ai_app_onsite_api_key` is a Base64-encoded license server URL string.
         * 
         * These keys are securely generated and stored using WordPress's `aiapp_set_option` function.
         * 
         * Note: This is not obfuscated code. The Base64 encoding of the API key is used for safe storage
         * and transmission, and it is not intended to hide or obscure the key. This approach ensures
         * compatibility with systems that may require Base64-encoded strings.
         */
        if (!get_option('ai_app_onsite_encryption_key')) {
            aiapp_set_option('ai_app_onsite_encryption_key', bin2hex(random_bytes(32))); // 256-bit key
        }
        if (!get_option('ai_app_onsite_encryption_iv')) {
            aiapp_set_option('ai_app_onsite_encryption_iv', base64_encode(random_bytes(16)));
        }
        if (!get_option('ai_app_onsite_api_key')) {
            aiapp_set_option('ai_app_onsite_api_key', 'aHR0cHM6Ly9iZHl6OHJvM3BjLmV4ZWN1dGUtYXBpLnVzLWVhc3QtMS5hbWF6b25hd3MuY29tL1BST0QvdmFsaWRhdGVLZXk=');
        }
        if (!get_option('aiapp_server_base_url')) {
            aiapp_set_option('aiapp_server_base_url', 'https://aiapponsite.com/');
        }
        if (!get_option('ai_app_onsite_unique_id')) {
            aiapp_set_option('ai_app_onsite_unique_id', wp_generate_uuid4());
        }

        require_once ai_app_onsite_include_path() . '/class-ai-app-onsite-db-handler.php';
        // Create an instance of the database handler class and pass $wpdb
        $db_handler = new AI_App_Onsite_DB_Handler($wpdb);

        // Call the method to create the table
        $db_handler->ai_app_onsite_create_table();
    }
}

if (! function_exists('ai_app_onsite_deactivate')) {
    // Deactivation hook callback function
    function ai_app_onsite_deactivate()
    {
        ai_app_onsite_clear_user_stats_cron();
        // Enqueue a script to delete cookies on plugin deactivation
        add_action('admin_footer', function () {
            echo '<script>
                document.cookie = "ai_app_onsite_active_tab=; path=/; max-age=0";
            </script>';
        });
    }
}

add_action('admin_enqueue_scripts', function ($hook) {
    if ($hook !== 'plugins.php') {
        return;
    }

    wp_enqueue_script('plugin-deactivation-intercept', ai_app_onsite_assets_path() . 'js/ai-app-onsite-reset-localstorage.js', array('jquery'), '1.0', true);
});

if (! function_exists('ai_app_onsite_plugin_uninstall')) {
    function ai_app_onsite_plugin_uninstall()
    {
        global $wpdb;

        require_once ai_app_onsite_include_path() . 'class-ai-app-onsite-db-handler.php';

        // Create an instance of the database handler class and pass $wpdb
        $db_handler = new AI_App_Onsite_DB_Handler($wpdb);

        // Call the method to drop the table
        $result = $db_handler->ai_app_onsite_drop_table();

        $cron_hooks = [
            'ai_app_onsite_check_license_cron',
            'ai_app_onsite_check_version_cron',
            'ai_app_onsite_user_stats_cron'
        ];

        foreach ($cron_hooks as $hook) {
            if (wp_next_scheduled($hook)) {
                wp_clear_scheduled_hook($hook);
            }
        }

        // Delete all plugin-specific options from wp_options
        $option_keys = [
            'ai_app_onsite_fresh_install',
            'ai_app_onsite_encryption_key',
            'ai_app_onsite_encryption_iv',
            'ai_app_onsite_api_key',
            'ai_app_license_last_checked',
            'ai_app_onsite_uninstall_message',
        ];

        foreach ($option_keys as $option) {
            delete_option($option);
        }

        // Log the result
        if (is_wp_error($result)) {
            aiapp_set_option('ai_app_onsite_uninstall_message', 'Error during plugin uninstallation: ' . $result->get_error_message());
        } else {
            aiapp_set_option('ai_app_onsite_uninstall_message', 'Plugin uninstalled successfully! Tables were dropped.');
        }
    }
}

// Register activation and deactivation hooks
register_activation_hook(__FILE__, 'ai_app_onsite_activate');
register_deactivation_hook(__FILE__, 'ai_app_onsite_deactivate');

// Register uninstall hook to delete plugin data
register_uninstall_hook(__FILE__, 'ai_app_onsite_plugin_uninstall');

// Initialize the plugin
add_action('plugins_loaded', 'ai_app_onsite_init');

if ( ! function_exists( 'ai_app_onsite_clear_user_stats_cron' ) ) {
    function ai_app_onsite_clear_user_stats_cron() {
        // Clear the all crons
        $cron_hooks = [
            'ai_app_onsite_check_license_cron',
            'ai_app_onsite_check_version_cron',
            'ai_app_onsite_user_stats_cron'
        ];
        foreach ($cron_hooks as $hook) {
            $timestamp = wp_next_scheduled($hook);
            if ($timestamp) {
                wp_unschedule_event($timestamp, $hook);
            }
        }
    }
}

add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'ai_app_onsite_settings_and_upgrade_links');
function ai_app_onsite_settings_and_upgrade_links($links)
{
	$settings_link = '<a href="' . admin_url('admin.php?page=ai-app-onsite-menu') . '">Settings</a>';
	$upgrade_link = '<a href="https://aiapponsite.com/pricing" class="open-new-tab" target="_blank" style="color:#d35400;font-weight:600; text-decoration:none; outline:none; box-shadow:none;">UPGRADE  → <span style="background:#d35400;color:#fff;padding:2px 6px;border-radius:8px;font-size:10px;vertical-align:middle;">PLUS</span></a>';


	array_unshift($links, $settings_link);
	array_push($links, $upgrade_link);

	return $links;
}

add_action('admin_init', function () {
    $last_checked = (int) get_option('ai_app_license_last_checked');
    $now          = time();
    $was_updated  = get_transient('ai_app_onsite_plugin_was_updated');
    if ($was_updated || !$last_checked || ($now - $last_checked) > 3600) {
        // Run license check + restore premium folder
        (new AI_APP_ONSITE_App_License_Handler())->ai_app_onsite_app_check_license_cron_callback();
        
        // Reset hourly flag
        aiapp_set_option('ai_app_license_last_checked', $now);

        // Clear update flag if it was set
        if ($was_updated) {
            delete_transient('ai_app_onsite_plugin_was_updated');
        }
    }
});

add_action('init', 'ai_app_onsite_check_version_change', 5);
if (!function_exists('ai_app_onsite_check_version_change')) {
    function ai_app_onsite_check_version_change() {
        $option_name     = 'ai_app_onsite_version';
        $current_version = defined('AI_APP_ONSITE_VERSION') ? AI_APP_ONSITE_VERSION : 'unknown';
        $stored_version  = get_option($option_name);

        if ($stored_version !== $current_version) {
            $upload_dir = wp_upload_dir();
            $log_dir    = trailingslashit($upload_dir['basedir']) . 'ai-app-onsite';
            $log_file   = trailingslashit($log_dir) . 'version-change.log';

            if (!file_exists($log_dir)) {
                wp_mkdir_p($log_dir);
            }

            if (!is_writable($log_dir)) {
                error_log("AI App Onsite: Log directory not writable at $log_dir");
                return;
            }

            // Gather context info
            $wp_version     = get_bloginfo('version');
            $php_version    = PHP_VERSION;
            $site_url       = home_url();
            $current_user   = (function_exists('wp_get_current_user') && is_user_logged_in()) ? wp_get_current_user() : null;
            $user_email     = ($current_user && !empty($current_user->user_email)) ? $current_user->user_email : 'unknown';

            $plugin_dir      = plugin_dir_path(__FILE__);
            $premium_dir     = trailingslashit($plugin_dir) . 'premium';
            $is_premium      = is_dir($premium_dir) ? 'Yes' : 'No';
            
            // Compose log message
            $log_time = current_time('mysql');
            $unique_id = get_option('ai_app_onsite_unique_id', 'unknown');

            if (empty($stored_version)) {
                $log_message = sprintf(
                    "[%s] Plugin Installed   :: %s\n" .
                    "  - Previous Version    : N/A\n" .
                    "  - Current Version     : %s\n" .
                    "  - WordPress           : %s\n" .
                    "  - PHP                 : %s\n" .
                    "  - Site URL            : %s\n" .
                    "  - User                : %s\n" .
                    "  - Premium             : %s\n\n",
                    $log_time,
                    $unique_id,
                    $current_version,
                    $wp_version,
                    $php_version,
                    $site_url,
                    $user_email,
                    $is_premium
                );
            } else {
                // add unique identifier
                $log_message = sprintf(
                    "[%s] Plugin Updated     :: %s\n" .
                    "  - Previous Version    : %s\n" .
                    "  - Current Version     : %s\n" .
                    "  - WordPress           : %s\n" .
                    "  - PHP                 : %s\n" .
                    "  - Site URL            : %s\n" .
                    "  - User                : %s\n" .
                    "  - Premium             : %s\n\n",
                    $log_time,
                    $unique_id,
                    $stored_version,
                    $current_version,
                    $wp_version,
                    $php_version,
                    $site_url,
                    $user_email,
                    $is_premium
                );
            }

            $htaccess = $log_dir . '/.htaccess';
            if (!file_exists($htaccess)) {
                @file_put_contents($htaccess, "Options -Indexes\n<IfModule mod_authz_core.c>\nRequire all denied\n</IfModule>\n");
            }
            $index = $log_dir . '/index.html';
            if (!file_exists($index)) {
                @file_put_contents($index, "");
            }

            file_put_contents($log_file, $log_message, FILE_APPEND | LOCK_EX);
            aiapp_set_option($option_name, $current_version);
        }
    }
}

if ( ! function_exists( 'aiapp_set_option' ) ) {
    function aiapp_set_option( $key, $value ) {
        $exists = get_option( $key, null );

        if ( $exists === null ) {
            $result = add_option( $key, $value );
        } else {
            $result = update_option( $key, $value );
        }

        if ( $result ) {
            wp_cache_delete( $key, 'options' );
            wp_cache_delete( 'alloptions', 'options' );
            aiapp_clear_page_cache();
        } 

        return $result;
    }
}

if ( ! function_exists( 'aiapp_clear_page_cache' ) ) {
    function aiapp_clear_page_cache() {
        // LiteSpeed Cache
        if ( class_exists( 'LiteSpeed_Cache_API' ) ) {
            LiteSpeed_Cache_API::purge_all();
        }

        // SiteGround Optimizer
        if ( function_exists( 'sg_cachepress_purge_cache' ) ) {
            sg_cachepress_purge_cache();
        }

        // WP Super Cache
        if ( function_exists( 'wp_cache_clear_cache' ) ) {
            wp_cache_clear_cache();
        }

        // W3 Total Cache
        if ( function_exists( 'w3tc_pgcache_flush' ) ) {
            w3tc_pgcache_flush();
        }

        // WP Fastest Cache
        if ( class_exists( 'WpFastestCache' ) ) {
            $wfc = new WpFastestCache();
            if ( method_exists( $wfc, 'deleteCache' ) ) {
                $wfc->deleteCache();
            }
        }

        // Breeze (Cloudways)
        if ( function_exists( 'breeze_cache_clean' ) ) {
            breeze_cache_clean();
        }

        // Autoptimize
        if ( function_exists( 'autoptimize_clearall' ) ) {
            autoptimize_clearall();
        }

        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            error_log('[AI App Onsite] Page/UI cache cleared.');
        }
    }
}


add_action('upgrader_process_complete', 'ai_app_onsite_flag_plugin_updated', 10, 2);
function ai_app_onsite_flag_plugin_updated($upgrader, $hook_extra) {
    if (!isset($hook_extra['type']) || $hook_extra['type'] !== 'plugin') {
        return;
    }

    $plugin_files = [];

    // Case 1: Bulk/single updates (normal)
    if (!empty($hook_extra['plugins']) && is_array($hook_extra['plugins'])) {
        $plugin_files = $hook_extra['plugins'];
    }
    // Case 2: Single plugin (string key)
    elseif (!empty($hook_extra['plugin'])) {
        $plugin_files[] = $hook_extra['plugin'];
    }
    // Case 3: Fallback for zip uploads
    elseif (!empty($upgrader->new_plugin_data['TextDomain'])) {
        $slug = $upgrader->new_plugin_data['TextDomain'];
        $plugin_files[] = $slug . '/' . $slug . '.php';
    } 

    // Loop through collected plugins
    foreach ($plugin_files as $plugin_file) {
        if (strpos($plugin_file, 'ai-app-onsite') !== false) {
            set_transient('ai_app_onsite_plugin_was_updated', 1, MINUTE_IN_SECONDS * 10);
            break;
        }
    }
}




if (!function_exists('ai_app_onsite_get_app_selector')) {
    function ai_app_onsite_get_app_selector($app_id = 1) {
        global $wpdb;

        $plugin_settings_table = $wpdb->prefix . 'ai_app_onsite_plugin_settings';
        $app_properties_table = $wpdb->prefix . 'ai_app_onsite_app_properties';

        // Get the current app_selector value
        $app_selector = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT app_selector FROM $plugin_settings_table WHERE app_id = %d",
                $app_id
            )
        );

        // Check if app_selector matches app_name in the app_properties table
        if ($app_selector) {
            $app_id_from_properties = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT id FROM $app_properties_table WHERE app_name = %s OR app_name_show = %s",
                    $app_selector,
                    $app_selector
                )
            );

            // If a match is found, update app_selector to the id
            if ($app_id_from_properties) {
                $wpdb->update(
                    $plugin_settings_table,
                    ['app_selector' => $app_id_from_properties],
                    ['app_id' => $app_id],
                    ['%d'],
                    ['%d']
                );

                $app_selector = $app_id_from_properties;
            }
        }

        return $app_selector ?: null;
    }

	/**
	 * Get the app_name of the current app based on the app_selector.
	 */
	function ai_app_onsite_get_current_app_name():?string
	{
		global $wpdb;

		$app_id = ai_app_onsite_get_app_selector();

		if (!$app_id) {
			return null; // No app selector found
		}

		// Get the app_name from the app_properties table
		$app_name = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT `app_name`,`app_name_show` FROM {$wpdb->prefix}ai_app_onsite_app_properties WHERE app_id = %d",
				$app_id
			),
			ARRAY_A
		);

		//if app_name is null, then return app_show_name
		return $app_name['app_name'] ?: $app_name['app_name_show'] ?: null;
	}
}

/**
 * Register a client.
 * - Stores: aiapp_server_base_url, ai_app_onsite_unique_id, aiapp_client_credentials (autoload=false)
 */
if (!function_exists('aiapp_register_client')) {
    function aiapp_register_client( string $api_base ) {
        if (!function_exists('wp_remote_post')) {
            error_log('AI App Onsite: WordPress HTTP API is unavailable. Cannot register client.');
        }

        $api_base = rtrim($api_base, '/');

        // 1) If we already have creds, return them
        $creds = get_option('aiapp_client_credentials', []);
        if (!empty($creds['key']) && !empty($creds['secret'])) {
            // keep the server URL fresh (no autoload)
            if ($api_base !== '' && $api_base !== get_option('aiapp_server_base_url')) {
                aiapp_set_option('aiapp_server_base_url', $api_base, false);
            }
            error_log('AI App Onsite: Client already registered with key: ' . $creds['key']);
            return;
        }

        if ($api_base === '') {
            error_log('AI App Onsite: API base URL is missing. Cannot register client.');
        }

        // Ensure we have a local anonymous install/unique identifier UUID (no PII)
        $install_id = get_option('ai_app_onsite_unique_id');
        if (!$install_id) {
            if (!function_exists('wp_generate_uuid4')) {
                error_log('AI App Onsite: UUID generator is unavailable. Cannot generate install ID.');
            }
            $install_id = wp_generate_uuid4();
            aiapp_set_option('ai_app_onsite_unique_id', $install_id, false); // autoload=false
        }

        // 3) Call register-client (idempotent on your server)
        $endpoint = $api_base . '/wp-json/aiao/v1/register-client';
        $res = wp_remote_post($endpoint, [
            'method'    => 'POST',
            'timeout'   => 60,
            'headers'   => ['Content-Type' => 'application/json'],
            'body'      => wp_json_encode(['install_id' => $install_id]),
            'sslverify' => true,
        ]);

        if (is_wp_error($res)) {
            error_log('AI App Onsite: Error registering client: ' . $res->get_error_message());
        }

        $code = wp_remote_retrieve_response_code($res);
        $body = wp_remote_retrieve_body($res);
        $json = json_decode($body, true);

        if ($code !== 200 || !is_array($json) || empty($json['key']) || empty($json['secret'])) {
            error_log('AI App Onsite: Failed to register client. Response code: ' . $code . ', Body: ' . $body);
        }

        // 4) Persist creds + server URL (no autoload)
        aiapp_set_option('aiapp_server_base_url', $api_base, false);
        aiapp_set_option('aiapp_client_credentials', [
            'key'    => $json['key'],
            'secret' => $json['secret'],
        ], false);

        error_log('AI App Onsite: Client registered successfully with key: ' . $json['key']);
    }
}
