<?php
/**
* Plugin Name: SearchShifter AI Visibility
* Plugin URI: https://searchshifter.ai
* Description: Generates structured configuration files and metadata to support AI crawler access and content interpretation.
* Version: 1.0.0
* Author: Thrivx.ai
* Author URI: https://searchshifter.ai
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: searchshifter
* Requires at least: 6.0
* Requires PHP: 8.1
* Tested up to: 7.0
*/

/**
 * SearchShifter AI Visibility is free software. You can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License or any later version.
 *
 * SearchShifter AI Visibility is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SearchShifter AI Visibility. If not, see https://www.gnu.org/licenses/gpl-2.0.html.
 */

if ( ! defined( 'ABSPATH' ) ) { exit; }
    require_once __DIR__ . '/includes/Core/constants.php';
    require_once __DIR__ . '/includes/Core/helpers.php';
    require_once __DIR__ . '/includes/Core/autoload.php';
    require_once __DIR__ . '/includes/Core/activation.php';
    require_once __DIR__ . '/includes/Core/database.php';
    require_once __DIR__ . '/includes/Core/schema.php';
    require_once __DIR__ . '/includes/glossary/class-glossary.php';
    require_once __DIR__ . '/includes/glossary/class-glossary-setup.php';
    require_once __DIR__ . '/includes/glossary/class-glossary-admin.php';
    require_once __DIR__ . '/includes/glossary/class-glossary-frontend.php';
    require_once __DIR__ . '/includes/faq/class-faq-frontend.php';
    require_once __DIR__ . '/admin/class-schema-preview.php';
    require_once __DIR__ . '/includes/class-schema-governor.php';
    require_once __DIR__ . '/admin/admin-actions.php';
    require_once __DIR__ . '/admin/class-ss-meta-boxes.php';
    require_once __DIR__ . '/admin/class-ss-admin-ui.php';
    require_once __DIR__ . '/admin/class-upgrade-popup.php';
    add_action('plugins_loaded', function() {
        SS_Setup::init();
        SS_Schema::init();
        SS_Meta_Boxes::init();
        SS_Admin_UI::init();
        SS_Glossary::init();
        SS_Glossary_Setup::init();
        SS_Glossary_Admin::init();
        SS_Glossary_Frontend::init();
        SS_FAQ_Frontend::init();
        SS_Upgrade_Popup::init();
        SS_Schema_Preview::init();
        SS_Schema_Governor::init();
        SS_Shortcodes::init();
        SS_Free_Features::init();
        if (class_exists('SS_Telemetry_Diagnostics')) {
            SS_Telemetry_Diagnostics::init();
        }
        if (class_exists('SS_QA_Admin_UI')) {
            SS_QA_Admin_UI::init();
        }
        if (is_admin()) {
            if (class_exists('SS_AdminAssets')) SS_AdminAssets::init();
            if (class_exists('SS_Ajax')) SS_Ajax::init();
        }
    });
    define('SEARCHSHIFTER_MIN_PHP', '8.1');
        if (version_compare(PHP_VERSION, '8.1', '<')) {
            add_action('admin_notices', function () {
                ?>
                <div class="notice notice-error">
                    <p><strong>SearchShifter was not activated.</strong></p>
                    <p>
                        This plugin requires <strong>PHP 8.1 or higher</strong>.<br>
                        Your site is currently running <strong><?php echo esc_html(PHP_VERSION); ?></strong>.
                    </p>
                    <p>No changes were made to your site.</p>
                </div>
                <?php
            });
            register_activation_hook(__FILE__, function () {
                deactivate_plugins(plugin_basename(__FILE__));
            });
            return; 
        }
        require_once __DIR__ . '/includes/class-ss-api.php';
        if ( searchshifter_has_plan('pro') && file_exists(__DIR__ . '/vendor/autoload.php') ) {
            require_once __DIR__ . '/vendor/autoload.php';
        }

        add_action('muplugins_loaded', function() {
            if ( ! is_multisite() || ! is_network_admin() ) {
                return;
            }
            require_once plugin_dir_path(__FILE__) . 'includes/licensing.php';
            if ( ! class_exists('SS_Licensing') ) {
                return;
            }
            $license = SS_Licensing::get_cached_status();
            $plan    = strtolower($license['plan'] ?? 'free');
            if ( in_array($plan, ['pro', 'authority', 'elite'], true) ) {
                return; // Allowed
            }
            deactivate_plugins( plugin_basename(__FILE__), true );
            wp_die(
                '<h2>🔒 SearchShifter Multisite is a Pro Feature</h2>
                <p>This plugin cannot be network-activated on a Free plan.</p>
                <p>Please activate it individually per site or upgrade to <strong>Pro</strong>.</p>',
                'Network Activation Blocked',
                ['back_link' => true]
            );
        }, 5);

        add_filter('query', function($query) {
            global $wpdb;
            if (
                stripos( $query, 'SHOW FULL COLUMNS FROM' ) !== false &&
                stripos( $query, $wpdb->prefix . 'ss_jobs' ) !== false
            ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                if ( ! $wpdb->get_var(
                    "SHOW TABLES LIKE '{$wpdb->prefix}ss_jobs'"
                ) ) {
                    return ''; // prevent the query entirely
                }
            }
            return $query;
        });
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/class-ss-export.php';
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/schema-glossary.php';
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/schema-faq.php';
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/class-ss-free-features.php';
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/glossary-admin.php';
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/glossary-runs.php';
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/auto-link.php';
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/rebuild-glossary.php';
        require_once SEARCHSHIFTER_PLUGIN_DIR . 'includes/class-orphan-engine.php';

        add_action('shutdown', function () {
            if (class_exists('SearchShifter\\Core\\Telemetry')) {
                SearchShifter\Core\Telemetry::onShutdown();
            }
        });

        add_action(
            'admin_init',
            function () {
                if ( ! current_user_can( 'manage_options' ) ) {
                    return;
                }
                if (
                    ! isset( $_GET['ss_force_create_tables'], $_GET['_wpnonce'] ) ||
                    '1' !== $_GET['ss_force_create_tables'] ||
                    ! wp_verify_nonce(
                        sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
                        'ss_force_create_tables'
                    )
                ) {
                    return;
                }
                ss_ensure_core_tables();
                wp_safe_redirect(
                    remove_query_arg(
                        [ 'ss_force_create_tables', '_wpnonce' ]
                    )
                );
                exit;
            }
        );
        if (class_exists('SearchShifter\\Core\\SyncEngine')) {
            SearchShifter\Core\SyncEngine::init();
        }
        add_action('admin_head', function() {
            echo '<style>
                .ss-modal-open { overflow: hidden !important; }
                .ss-modal { z-index: 9999999 !important; position: fixed !important; }
                .ss-modal-content { animation: fadeIn 0.2s ease-in-out; }
            </style>';
        });

        add_action('save_post_ss_qa', function($post_id) {

            if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
            if (wp_is_post_revision($post_id)) return;

            if (!current_user_can('edit_post', $post_id)) return;
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification handled elsewhere.
            if (isset($_POST['ss_qa_answer'])) {
                update_post_meta(
                    $post_id,
                    '_ss_qa_answer',
                    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification handled elsewhere.
                    sanitize_textarea_field($_POST['ss_qa_answer'])
                );
            } else {
                delete_post_meta($post_id, '_ss_qa_answer');
            }

        });
