<?php
/**
 * Plugin Name: BoostBot - AI Chatbot
 * Plugin URI: https://boostmedia.co.il/boostbot
 * Description: AI-powered chatbot for WordPress websites with lead generation, knowledge base, and analytics.
 * Version: 2.2.18
 * Author: BoostMedia
 * Author URI: https://boostmedia.co.il
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: boostbot
 * Domain Path: /languages
 * Requires at least: 6.2
 * Tested up to: 6.9
 * Requires PHP: 8.0
 *
 * @package BoostBot
 */

// Prevent direct file access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Early PHP version check.
 *
 * This runs BEFORE any PHP 8.0+ syntax is loaded.
 * Written in PHP 7.0-compatible code so it can display a friendly
 * Hebrew error message instead of a cryptic parse error.
 */
if ( version_compare( PHP_VERSION, '8.0', '<' ) ) {

    /**
     * Show a custom admin notice in Hebrew guiding the user to upgrade PHP.
     */
    function boostbot_php_version_notice() {
        $current  = PHP_VERSION;
        $required = '8.0';
        ?>
        <div class="notice notice-error" style="direction: rtl; text-align: right; border-right: 4px solid #E32774; border-left: none; padding: 16px 20px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            <div style="display: flex; align-items: flex-start; gap: 12px;">
                <span style="font-size: 32px; line-height: 1;">🤖</span>
                <div>
                    <h3 style="margin: 0 0 8px 0; color: #1d2327; font-size: 16px;">
                        BoostBot — נדרש שדרוג גרסת PHP
                    </h3>
                    <p style="margin: 0 0 12px 0; color: #50575e; font-size: 14px; line-height: 1.6;">
                        תוסף <strong>BoostBot</strong> דורש גרסת <strong>PHP <?php echo esc_html( $required ); ?></strong> ומעלה כדי לפעול.
                        <br>
                        השרת שלך מריץ כרגע גרסה <strong style="color: #E32774;"><?php echo esc_html( $current ); ?></strong>, שאינה נתמכת.
                    </p>
                    <div style="background: #f0f6fc; border: 1px solid #c3c4c7; border-radius: 6px; padding: 12px 16px; margin-bottom: 8px;">
                        <p style="margin: 0 0 6px 0; font-weight: 600; color: #1d2327; font-size: 14px;">
                            🔧 מה צריך לעשות?
                        </p>
                        <ol style="margin: 0; padding: 0 20px 0 0; color: #50575e; font-size: 13px; line-height: 1.8;">
                            <li>פנה לספק האחסון שלך (חברת ה-Hosting) ובקש <strong>שדרוג ל-PHP <?php echo esc_html( $required ); ?> ומעלה</strong>.</li>
                            <li>אם יש לך גישה ל-cPanel, חפש את האפשרות <strong>"Select PHP Version"</strong> או <strong>"PHP Manager"</strong>.</li>
                            <li>לאחר השדרוג, הפעל מחדש את התוסף — והוא יעבוד מיד! ✨</li>
                        </ol>
                    </div>
                    <p style="margin: 0; color: #787c82; font-size: 12px;">
                        💡 <em>טיפ: מומלץ לעבור ל-PHP 8.1 או 8.2 לביצועים הטובים ביותר ולאבטחה מעודכנת.</em>
                    </p>
                </div>
            </div>
        </div>
        <?php
    }
    add_action( 'admin_notices', 'boostbot_php_version_notice' );

    /**
     * Prevent plugin activation on PHP < 8.0 with a friendly message.
     */
    function boostbot_php_version_activation_check() {
        deactivate_plugins( plugin_basename( __FILE__ ) );
        wp_die(
            '<div dir="rtl" style="text-align: right; font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;">'
            . '<h2 style="color: #E32774;">🤖 BoostBot — לא ניתן להפעיל את התוסף</h2>'
            . '<p style="font-size: 15px; line-height: 1.7; color: #333;">'
            . 'תוסף <strong>BoostBot</strong> דורש גרסת <strong>PHP 8.0</strong> ומעלה.'
            . '<br>השרת שלך מריץ כרגע גרסה <strong style="color: #E32774;">' . esc_html( PHP_VERSION ) . '</strong>.'
            . '</p>'
            . '<h3>🔧 מה צריך לעשות?</h3>'
            . '<ol style="font-size: 14px; line-height: 1.8; color: #555;">'
            . '<li>פנה לספק האחסון שלך (חברת ה-Hosting) ובקש <strong>שדרוג ל-PHP 8.0 ומעלה</strong>.</li>'
            . '<li>אם יש לך גישה ל-cPanel, חפש את האפשרות <strong>"Select PHP Version"</strong> או <strong>"PHP Manager"</strong>.</li>'
            . '<li>לאחר השדרוג, חזור לכאן והפעל מחדש את התוסף ✨</li>'
            . '</ol>'
            . '<p style="color: #888; font-size: 13px;">💡 <em>טיפ: מומלץ לעבור ל-PHP 8.1 או 8.2 לביצועים הטובים ביותר ולאבטחה מעודכנת.</em></p>'
            . '</div>',
            'BoostBot — PHP Version Error',
            array( 'back_link' => true )
        );
    }
    register_activation_hook( __FILE__, 'boostbot_php_version_activation_check' );

    // Stop loading the plugin entirely — do not proceed to PHP 8.0+ code.
    return;
}

/**
 * Plugin version.
 */
define( 'BOOSTBOT_VERSION', '2.2.18' );

/**
 * Plugin directory path.
 */
define( 'BOOSTBOT_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );

/**
 * Plugin directory URL.
 */
define( 'BOOSTBOT_PLUGIN_URL', plugin_dir_url( __FILE__ ) );

/**
 * Plugin basename.
 */
define( 'BOOSTBOT_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );

/**
 * Minimum PHP version.
 */
define( 'BOOSTBOT_MIN_PHP_VERSION', '8.0' );

/**
 * Minimum WordPress version.
 */
define( 'BOOSTBOT_MIN_WP_VERSION', '6.2' );

/**
 * Database version for schema updates.
 */
// Multilingual: language column on entity tables.
// 1.1.3: WooCommerce tables and bundles language column.
// Bump DB version to trigger BoostBot_Activator::upgrade_db() on existing installs.
define( 'BOOSTBOT_DB_VERSION', '1.2.0' );

/**
 * Self-hosted flag.
 *
 * When true, the plugin uses its own update server (boostbot.boostmedia.co.il).
 * When false (default), updates come from WordPress.org.
 * The release script sets this to true in self-hosted ZIP builds.
 */
if ( ! defined( 'BOOSTBOT_SELF_HOSTED' ) ) {
    define( 'BOOSTBOT_SELF_HOSTED', true );
}

/**
 * Debug mode - set to false in production.
 */
if ( ! defined( 'BOOSTBOT_DEBUG' ) ) {
    define( 'BOOSTBOT_DEBUG', false );
}

/**
 * Check system requirements before loading.
 *
 * @return bool
 */
function boostbot_check_requirements() {
    $errors = array();

    // Check PHP version.
    if ( version_compare( PHP_VERSION, BOOSTBOT_MIN_PHP_VERSION, '<' ) ) {
        $errors[] = sprintf(
            /* translators: 1: Required PHP version, 2: Current PHP version */
            __( 'BoostBot requires PHP version %1$s or higher. You are running version %2$s.', 'boostbot' ),
            BOOSTBOT_MIN_PHP_VERSION,
            PHP_VERSION
        );
    }

    // Check WordPress version.
    global $wp_version;
    if ( version_compare( $wp_version, BOOSTBOT_MIN_WP_VERSION, '<' ) ) {
        $errors[] = sprintf(
            /* translators: 1: Required WordPress version, 2: Current WordPress version */
            __( 'BoostBot requires WordPress version %1$s or higher. You are running version %2$s.', 'boostbot' ),
            BOOSTBOT_MIN_WP_VERSION,
            $wp_version
        );
    }

    // Display errors if any.
    if ( ! empty( $errors ) ) {
        add_action( 'admin_notices', function() use ( $errors ) {
            foreach ( $errors as $error ) {
                printf( '<div class="notice notice-error"><p>%s</p></div>', esc_html( $error ) );
            }
        } );
        return false;
    }

    return true;
}

/**
 * Load the autoloader.
 */
require_once BOOSTBOT_PLUGIN_DIR . 'includes/class-autoloader.php';

if ( defined( 'BOOSTBOT_SELF_HOSTED' ) && BOOSTBOT_SELF_HOSTED ) {
    if ( file_exists( BOOSTBOT_PLUGIN_DIR . 'boostaffiliate.php' ) ) {
        require_once BOOSTBOT_PLUGIN_DIR . 'boostaffiliate.php';
        BoostAffiliate::init( __FILE__, BOOSTBOT_VERSION );
    }
}

/**
 * Begin plugin execution.
 *
 * @since 1.0.0
 */
function boostbot_run() {
    // Check requirements first.
    if ( ! boostbot_check_requirements() ) {
        return;
    }

    // Initialize autoloader.
    BoostBot_Autoloader::init();

    // Load utilities first (needed by other classes).
    require_once BOOSTBOT_PLUGIN_DIR . 'includes/utilities/functions.php';

    // DB upgrades (safe): run schema updates on version bump without requiring de/activation.
    // Wrapped in try/catch so a migration failure NEVER crashes the site.
    if ( class_exists( 'BoostBot_Activator' ) && BoostBot_Activator::needs_db_upgrade() ) {
        try {
            BoostBot_Activator::upgrade_db();
        } catch ( \Throwable $e ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- boot-path catch block; Logger may not be loaded yet.
            error_log( '[BoostBot][DB Upgrade] Fatal during upgrade: ' . $e->getMessage() );
        }
    }

    // JWT secret sync: runs once per plugin version upgrade (non-blocking).
    // Wrapped in try/catch so a sync failure NEVER crashes the site.
    $jwt_sync_version = get_option( 'boostbot_jwt_sync_version', '' );
    if ( $jwt_sync_version !== BOOSTBOT_VERSION && class_exists( 'BoostBot_Activator' ) ) {
        try {
            BoostBot_Activator::sync_jwt_secret();
        } catch ( \Throwable $e ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- boot-path catch block; Logger may not be loaded yet.
            error_log( '[BoostBot][JWT Sync] Fatal during sync: ' . $e->getMessage() );
        }
        update_option( 'boostbot_jwt_sync_version', BOOSTBOT_VERSION );
    }

    // Get the main plugin instance.
    $plugin = new BoostBot();
    $plugin->run();
}

/**
 * Plugin activation hook.
 */
function boostbot_activate() {
    // Load autoloader for activation.
    require_once BOOSTBOT_PLUGIN_DIR . 'includes/class-autoloader.php';
    BoostBot_Autoloader::init();

    // Load utilities.
    require_once BOOSTBOT_PLUGIN_DIR . 'includes/utilities/functions.php';

    // Run activation. Wrapped in try/catch so activation failures don't crash the site.
    try {
        BoostBot_Activator::activate();
    } catch ( \Throwable $e ) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- boot-path catch block; Logger may not be loaded yet.
        error_log( '[BoostBot][Activation] Fatal during activation: ' . $e->getMessage() );
    }

    // Sync JWT secret from backend (non-fatal if it fails).
    // For WP.org builds, only sync if user has opted in to cloud service.
    if ( BoostBot_Activator::is_cloud_service_allowed() ) {
        try {
            BoostBot_Activator::sync_jwt_secret();
        } catch ( \Throwable $e ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- boot-path catch block; Logger may not be loaded yet.
            error_log( '[BoostBot][JWT Sync] Fatal during activation sync: ' . $e->getMessage() );
        }
        update_option( 'boostbot_jwt_sync_version', BOOSTBOT_VERSION );
    }
}
register_activation_hook( __FILE__, 'boostbot_activate' );

/**
 * Plugin deactivation hook.
 */
function boostbot_deactivate() {
    // Load autoloader for deactivation.
    require_once BOOSTBOT_PLUGIN_DIR . 'includes/class-autoloader.php';
    BoostBot_Autoloader::init();

    // Run deactivation.
    BoostBot_Deactivator::deactivate();
}
register_deactivation_hook( __FILE__, 'boostbot_deactivate' );

// Initialize the plugin after WordPress has loaded.
add_action( 'plugins_loaded', 'boostbot_run' );

/**
 * Debug logging for development.
 * Outputs to browser console when BOOSTBOT_DEBUG is true.
 */
if ( BOOSTBOT_DEBUG ) {
    add_action( 'admin_footer', 'boostbot_debug_output' );
    add_action( 'wp_footer', 'boostbot_debug_output' );
}

/**
 * Output debug information to console.
 */
function boostbot_debug_output() {
    if ( ! BOOSTBOT_DEBUG ) {
        return;
    }

    // Only show to administrators.
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    // License check debug
    $license_manager = class_exists( 'BoostBot_License_Manager' ) ? new BoostBot_License_Manager() : null;
    
    $debug_data = array(
        'hooks_registered' => has_action( 'rest_api_init' ),
        'version'          => BOOSTBOT_VERSION,
        'file_version'     => 'v6.0-fix-license-check', // Change this to verify file is updated
    );

    $widget_debug = array(
        'is_admin'       => is_admin(),
        'is_front_page'  => is_front_page(),
        'is_home'        => is_home(),
        'page_id'        => get_the_ID(),
        'is_pro'         => $license_manager ? $license_manager->is_pro() : 'NO_MANAGER',
        'dev_mode'       => $license_manager ? $license_manager->is_dev_mode() : 'NO_MANAGER',
        'license_status' => $license_manager ? $license_manager->get_license_status() : 'NO_MANAGER',
    );

    $js_parts = array();
    $js_parts[] = 'console.log("%c\\ud83e\\udd16 BoostBot Debug Logs","background:#3BC2D0;color:white;padding:4px 8px;border-radius:4px;font-weight:bold;");';
    if ( class_exists( 'BoostBot_Logger' ) && method_exists( 'BoostBot_Logger', 'get_console_logs' ) ) {
        foreach ( BoostBot_Logger::get_console_logs() as $log ) {
            $js_parts[] = sprintf(
                'console.log("[%s] %s",%s);',
                esc_js( $log['time'] ),
                esc_js( $log['message'] ),
                wp_json_encode( $log['context'] )
            );
        }
    }
    $js_parts[] = sprintf( 'console.log("[%s] BoostBot plugin running",%s);', esc_js( gmdate( 'Y-m-d H:i:s' ) ), wp_json_encode( $debug_data ) );
    $js_parts[] = sprintf( 'console.log("\\ud83d\\udd0d Widget Debug:",%s);', wp_json_encode( $widget_debug ) );

    $handle = is_admin() ? 'boostbot-admin' : 'boostbot-widget';
    wp_add_inline_script( $handle, implode( "\n", $js_parts ) );
}

