<?php
/**
 * Plugin Name: SailWP AI Co-pilot
 * Plugin URI: https://sailwp.com
 * Description: AI co-pilot for WordPress. Persistent chat rail in every admin screen + front-end (logged-in editors). Works with any theme.
 * Version: 0.25.27
 * Author: Joost Boer
 * Author URI: https://sailwp.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: sailwp-ai-copilot
 * Requires at least: 6.0
 * Requires PHP: 7.4
 */

if (!defined('ABSPATH')) exit;

define('SAILWP_COPILOT_VERSION', '0.25.27');
define('SAILWP_COPILOT_FILE', __FILE__);
define('SAILWP_COPILOT_DIR', plugin_dir_path(__FILE__));
define('SAILWP_COPILOT_URL', plugin_dir_url(__FILE__));
define('SAILWP_COPILOT_AI_PROXY_DEFAULT', 'https://ai.sailwp.com');
define('SAILWP_COPILOT_CLOUD_DEFAULT', 'https://sailwp.com/app');
define('SAILWP_COPILOT_PLUGIN_LOADED', true);

require_once SAILWP_COPILOT_DIR . 'includes/class-plugin.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-settings.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-ai-client.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-rest.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-tools.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-rail.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-activation-notice.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-update-checker.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-fullpage-renderer.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-seo.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-edit-redirect.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-fatal-shield.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-dashboard-hero.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-dashboard-stats.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-versions.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-brand-profile.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-patterns.php';
require_once SAILWP_COPILOT_DIR . 'includes/class-iframe-bridge.php';
require_once SAILWP_COPILOT_DIR . 'includes/self-contained.php';
require_once SAILWP_COPILOT_DIR . 'includes/contact-form.php';

add_action('plugins_loaded', function () {
    SailWP_Copilot_Plugin::instance()->init();
});

register_activation_hook(__FILE__, function () {
    if (get_option('sailwp_copilot_installed_at') === false) {
        update_option('sailwp_copilot_installed_at', time());
    }
    // Auto-issue a free license on first activation. No email or signup
    // required — the plugin just registers the site and stores the key.
    if (!get_option('sailwp_copilot_license_key')) {
        $proxy = trim((string) get_option('sailwp_copilot_ai_proxy_url', SAILWP_COPILOT_AI_PROXY_DEFAULT));
        $theme = wp_get_theme();
        $resp  = wp_remote_post(rtrim($proxy, '/') . '/api/v1/free-license', [
            'timeout' => 15,
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => wp_json_encode([
                'site_url'        => home_url(),
                'wp_version'      => get_bloginfo('version'),
                'active_theme'    => $theme ? (string) $theme->get('Name') : '',
                'plugin_version'  => SAILWP_COPILOT_VERSION,
                'locale'          => get_locale(),
                'source'          => 'plugin',
            ]),
        ]);
        if (!is_wp_error($resp)) {
            $body = json_decode(wp_remote_retrieve_body($resp), true);
            if (is_array($body) && !empty($body['ok']) && !empty($body['license_key'])) {
                update_option('sailwp_copilot_license_key', sanitize_text_field($body['license_key']));
                if (!empty($body['site_id'])) {
                    update_option('sailwp_copilot_site_id', (int) $body['site_id']);
                }
                SailWP_Copilot_Plugin::cache_quota_from_response($body);
            }
        }
    }
});

/**
 * Defensive: if a license never got fetched (e.g. plugin was auto-updated
 * rather than freshly activated), fetch one on the first admin page load.
 * Runs at most once per install.
 */
add_action('admin_init', function () {
    if (get_option('sailwp_copilot_license_key')) return;
    if (get_transient('swcp_license_fetch_lock')) return;
    set_transient('swcp_license_fetch_lock', 1, 5 * MINUTE_IN_SECONDS);
    $proxy = trim((string) get_option('sailwp_copilot_ai_proxy_url', SAILWP_COPILOT_AI_PROXY_DEFAULT));
    $theme = wp_get_theme();
    $resp  = wp_remote_post(rtrim($proxy, '/') . '/api/v1/free-license', [
        'timeout' => 15,
        'headers' => ['Content-Type' => 'application/json'],
        'body'    => wp_json_encode([
            'site_url'        => home_url(),
            'wp_version'      => get_bloginfo('version'),
            'active_theme'    => $theme ? (string) $theme->get('Name') : '',
            'plugin_version'  => SAILWP_COPILOT_VERSION,
            'locale'          => get_locale(),
            'source'          => 'plugin',
        ]),
    ]);
    if (!is_wp_error($resp)) {
        $body = json_decode(wp_remote_retrieve_body($resp), true);
        if (is_array($body) && !empty($body['ok']) && !empty($body['license_key'])) {
            update_option('sailwp_copilot_license_key', sanitize_text_field($body['license_key']));
            if (!empty($body['site_id'])) {
                update_option('sailwp_copilot_site_id', (int) $body['site_id']);
            }
            SailWP_Copilot_Plugin::cache_quota_from_response($body);
            delete_transient('swcp_license_fetch_lock');
        }
    }
});

/**
 * Fire-and-forget event log to the proxy. Used by tools that want to
 * report behavioural signals (preview applied / discarded).
 *
 * Guarded so the plugin and the theme-bundled copy of the Co-pilot can
 * coexist on the same install — whichever defines the function first
 * wins, and the other yields. (The theme bundle's bootstrap also
 * declares this with a function_exists guard.)
 */
if (!function_exists('swcp_log_remote_event')) {
    function swcp_log_remote_event($event_name, $details = null) {
        $license = SailWP_Copilot_Plugin::get_license_key();
        if (!$license) return;
        $proxy = SailWP_Copilot_Plugin::get_ai_proxy_url();
        wp_remote_post($proxy . '/api/v1/event', [
            'timeout'  => 5,
            'blocking' => false, // fire and forget
            'headers'  => [
                'Content-Type'  => 'application/json',
                'X-License-Key' => $license,
            ],
            'body' => wp_json_encode([
                'event_name' => $event_name,
                'details'    => is_array($details) ? $details : null,
            ]),
        ]);
    }
}
