<?php
/**
 * Plugin Name: Word.Chat Pro
 * Plugin URI: https://www.word.chat/
 * Description: Chat with your WordPress content using AI. Pro version with unlimited content sync, AI Content Writer, and advanced analytics.
 * Version: 0.2.0
 * Author: Word.Chat
 * Author URI: https://www.word.chat/
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: wordchat-pro
 * Domain Path: /languages
 * Requires at least: 5.5
 * Tested up to: 6.5
 * Requires PHP: 7.4
 */

define('WORDCHAT_API_URL', 'https://chat.word.chat');
define('WORDCHAT_VERSION', '0.2.0');
define('WORDCHAT_PLUGIN_SLUG', 'wordchat-pro');
define('WORDCHAT_IS_PRO', true);

// --- CONFLICT DETECTION ---
// If free plugin is active, deactivate it (Pro takes priority)
function wordchat_pro_conflict_check() {
    if (is_plugin_active('wordchat/wordchat.php')) {
        deactivate_plugins('wordchat/wordchat.php');
        add_action('admin_notices', 'wordchat_pro_conflict_notice');
    }
}

function wordchat_pro_conflict_notice() {
    echo '<div class="notice notice-warning is-dismissible">';
    echo '<p><strong>' . esc_html__('Word.Chat Pro:', 'wordchat-pro') . '</strong> ' . esc_html__('The free version has been deactivated because Word.Chat Pro is now active. Only one version can be active at a time.', 'wordchat-pro') . '</p>';
    echo '</div>';
}

add_action('plugins_loaded', 'wordchat_pro_conflict_check', 1);

// Also check on activation
function wordchat_pro_activation_conflict_check() {
    if (is_plugin_active('wordchat/wordchat.php')) {
        deactivate_plugins('wordchat/wordchat.php');
    }
}
register_activation_hook(__FILE__, 'wordchat_pro_activation_conflict_check');

// --- INTERNATIONALIZATION ---
function wordchat_load_textdomain() {
    load_plugin_textdomain('wordchat-pro', false, dirname(plugin_basename(__FILE__)) . '/languages');
}
add_action('plugins_loaded', 'wordchat_load_textdomain');

// --- INCLUDES ---
require_once plugin_dir_path(__FILE__) . 'includes/admin.php';
require_once plugin_dir_path(__FILE__) . 'includes/register.php';
require_once plugin_dir_path(__FILE__) . 'includes/api.php';
require_once plugin_dir_path(__FILE__) . 'includes/updater.php';
require_once plugin_dir_path(__FILE__) . 'includes/api-proxy.php';
require_once plugin_dir_path(__FILE__) . 'includes/content-writer.php';
require_once plugin_dir_path(__FILE__) . 'includes/content-writer-ajax.php';
require_once plugin_dir_path(__FILE__) . 'includes/sync.php';

// --- PRO LICENSE MANAGEMENT ---
// Include license admin UI (for all users - shows upgrade CTA for free users)
require_once plugin_dir_path(__FILE__) . 'includes/license-admin.php';

// Initialize Pro Updater if user has a license key
if (get_option('wordchat_license_key')) {
    require_once plugin_dir_path(__FILE__) . 'includes/pro-updater.php';

    // Global variable for updater instance
    global $wordchat_pro_updater;

    // Initialize Pro Updater
    $wordchat_pro_updater = new WordChat_Pro_Updater(
        __FILE__,                // Plugin file path
        WORDCHAT_VERSION,        // Current version
        WORDCHAT_API_URL         // Backend API URL
    );
}

// --- TELEMETRY FOR ALL USERS (FREE + PRO) ---
// Schedule daily telemetry check-in for ALL users to track plugin health
if (!wp_next_scheduled('wordchat_daily_telemetry')) {
    wp_schedule_event(time(), 'daily', 'wordchat_daily_telemetry');
}

// Hook telemetry submission to cron
add_action('wordchat_daily_telemetry', function() {
    // If Pro user, use Pro updater's telemetry
    if (get_option('wordchat_license_key')) {
        global $wordchat_pro_updater;
        if ($wordchat_pro_updater && method_exists($wordchat_pro_updater, 'daily_checkin')) {
            $wordchat_pro_updater->daily_checkin();
        }
    } else {
        // For free users, send basic telemetry
        wordchat_send_free_user_telemetry();
    }
});

// --- REGISTER SITE ON PLUGIN ACTIVATION ---
register_activation_hook(__FILE__, 'wordchat_register_plugin');

// --- DEACTIVATION CLEANUP ---
register_deactivation_hook(__FILE__, 'wordchat_deactivation_cleanup');

function wordchat_deactivation_cleanup() {
    // Clear scheduled cron jobs
    $timestamp = wp_next_scheduled('wordchat_cleanup_stuck_syncs');
    if ($timestamp) {
        wp_unschedule_event($timestamp, 'wordchat_cleanup_stuck_syncs');
    }

    // Clear telemetry cron
    $telemetry_timestamp = wp_next_scheduled('wordchat_daily_telemetry');
    if ($telemetry_timestamp) {
        wp_unschedule_event($telemetry_timestamp, 'wordchat_daily_telemetry');
    }
}

// --- INITIALIZE AUTO-UPDATER ---
new WordChat_Updater(__FILE__, WORDCHAT_VERSION);

// --- CONTENT INGEST ON PUBLISH (BACKGROUND PROCESSING) ---

// Schedule background sync instead of blocking
function wordchat_schedule_sync($post_id, $post) {
    // Prevent auto-saves and revisions from triggering sync
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id)) return;
    if (wp_is_post_autosave($post_id)) return;

    // Only sync if post is published
    if ($post->post_status !== 'publish') return;

    // Only sync posts, pages, and WooCommerce products
    if (!in_array($post->post_type, ['post', 'page', 'product'])) return;

    // Check if credentials exist
    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');
    if (!$site_id || !$api_key) return;

    // Check if this post is marked for sync in admin
    // If not manually synced, skip automatic sync
    $is_synced = get_post_meta($post_id, 'wordchat_synced', true);
    if (!$is_synced) return;

    // Mark as pending sync
    update_post_meta($post_id, 'wordchat_sync_status', 'pending');

    // Schedule background task (non-blocking)
    wp_schedule_single_event(time(), 'wordchat_background_sync', [$post_id]);
}

// Background sync handler
function wordchat_background_sync($post_id) {
    $post = get_post($post_id);
    if (!$post) {
        error_log("WordChat: Post $post_id not found for background sync");
        return;
    }

    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');

    if (!$site_id || !$api_key) {
        update_post_meta($post_id, 'wordchat_sync_status', 'error');
        error_log("WordChat: Missing credentials for post $post_id");
        return;
    }

    $url = get_permalink($post);
    $categories = get_the_category($post_id);
    $category = $categories && !empty($categories) ? $categories[0]->name : null;

    // Build text with optional WooCommerce product enrichment
    $text = strip_tags($post->post_title . ". " . $post->post_content);

    if ($post->post_type === 'product' && function_exists('wc_get_product')) {
        $product = wc_get_product($post_id);
        if ($product) {
            $meta = [];
            if ($product->get_price()) $meta[] = "Price: " . strip_tags(wc_price($product->get_price()));
            if ($product->get_sku()) $meta[] = "SKU: " . $product->get_sku();
            $stock_map = ['instock' => 'In Stock', 'outofstock' => 'Out of Stock', 'onbackorder' => 'On Backorder'];
            $meta[] = "Stock: " . ($stock_map[$product->get_stock_status()] ?? $product->get_stock_status());
            if ($product->get_short_description()) $meta[] = "Summary: " . strip_tags($product->get_short_description());
            if ($meta) $text .= "\n\nProduct Details:\n" . implode("\n", $meta);
        }
    }

    $payload = [
        'site_id' => $site_id,
        'api_key' => $api_key,
        'domain' => get_site_url(),
        'chunks' => [[
            'title' => $post->post_title,
            'text' => $text,
            'url' => $url,
            'category' => $category ? $category : 'Uncategorized',
            'content_type' => $post->post_type
        ]]
    ];

    $response = wp_remote_post(WORDCHAT_API_URL . '/ingest', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($payload),
        'timeout' => 30
    ]);

    if (is_wp_error($response)) {
        $error_msg = $response->get_error_message();
        update_post_meta($post_id, 'wordchat_sync_status', 'error');
        update_post_meta($post_id, 'wordchat_sync_error', $error_msg);
        error_log("WordChat sync error for post $post_id: $error_msg");
        return;
    }

    $status_code = wp_remote_retrieve_response_code($response);
    $response_body = wp_remote_retrieve_body($response);

    if ($status_code === 200) {
        update_post_meta($post_id, 'wordchat_synced', true);
        update_post_meta($post_id, 'wordchat_synced_at', current_time('mysql'));
        update_post_meta($post_id, 'wordchat_sync_status', 'synced');
        delete_post_meta($post_id, 'wordchat_sync_error');
    } else {
        $error_data = json_decode($response_body, true);
        $error_msg = isset($error_data['error']) ? $error_data['error'] : "HTTP $status_code";

        update_post_meta($post_id, 'wordchat_sync_status', 'error');
        update_post_meta($post_id, 'wordchat_sync_error', $error_msg);
        error_log("WordChat sync failed for post $post_id: $error_msg (HTTP $status_code)");
    }
}

// Hook into publish actions
add_action('publish_post', 'wordchat_schedule_sync', 10, 2);
add_action('publish_page', 'wordchat_schedule_sync', 10, 2);
add_action('publish_product', 'wordchat_schedule_sync', 10, 2);

// Register background sync action
add_action('wordchat_background_sync', 'wordchat_background_sync');

// Cleanup stuck "pending" syncs (runs every 15 minutes)
add_action('wordchat_cleanup_stuck_syncs', 'wordchat_cleanup_stuck_syncs_handler');

function wordchat_cleanup_stuck_syncs_handler() {
    global $wpdb;

    // Find posts with "pending" status older than 5 minutes
    $five_minutes_ago = gmdate('Y-m-d H:i:s', time() - 300);

    $stuck_posts = $wpdb->get_results($wpdb->prepare(
        "SELECT post_id FROM {$wpdb->postmeta}
         WHERE meta_key = 'wordchat_sync_status'
         AND meta_value = 'pending'
         AND post_id IN (
             SELECT post_id FROM {$wpdb->postmeta}
             WHERE meta_key = 'wordchat_synced_at'
             AND meta_value < %s
         )",
        $five_minutes_ago
    ));

    // Also find posts with "pending" but no synced_at timestamp (never completed)
    $never_completed = $wpdb->get_results(
        "SELECT pm1.post_id FROM {$wpdb->postmeta} pm1
         LEFT JOIN {$wpdb->postmeta} pm2 ON pm1.post_id = pm2.post_id AND pm2.meta_key = 'wordchat_synced_at'
         WHERE pm1.meta_key = 'wordchat_sync_status'
         AND pm1.meta_value = 'pending'
         AND pm2.post_id IS NULL"
    );

    $all_stuck = array_merge($stuck_posts, $never_completed);

    foreach ($all_stuck as $row) {
        // Mark as error with timeout message
        update_post_meta($row->post_id, 'wordchat_sync_status', 'error');
        update_post_meta($row->post_id, 'wordchat_sync_error', __('Sync timed out. Please try syncing again.', 'wordchat-pro'));
        error_log("WordChat: Cleaned up stuck sync for post {$row->post_id}");
    }

    if (count($all_stuck) > 0) {
        error_log("WordChat: Cleaned up " . count($all_stuck) . " stuck syncs");
    }
}

// Schedule cleanup task if not already scheduled
if (!wp_next_scheduled('wordchat_cleanup_stuck_syncs')) {
    wp_schedule_event(time(), 'every_15_minutes', 'wordchat_cleanup_stuck_syncs');
}

// Add custom cron schedule for 15 minutes
add_filter('cron_schedules', 'wordchat_add_cron_interval');
function wordchat_add_cron_interval($schedules) {
    $schedules['every_15_minutes'] = array(
        'interval' => 900, // 15 minutes in seconds
        'display'  => esc_html__('Every 15 Minutes', 'wordchat-pro')
    );
    return $schedules;
}

// --- FRONTEND CHAT WIDGET ---
function wordchat_enqueue_widget() {
    // Skip excluded pages
    $excluded = get_option('wordchat_excluded_pages', []);
    if (!empty($excluded) && is_singular()) {
        if (in_array(get_queried_object_id(), array_map('intval', $excluded), true)) {
            return;
        }
    }

    wp_enqueue_script('wordchat-chat', plugin_dir_url(__FILE__) . 'js/chat.js', [], WORDCHAT_VERSION, true);

    // Get custom settings
    $header_text = get_option('wordchat_header_text', 'Ask us anything');
    $site_name = get_option('wordchat_site_name', get_bloginfo('name'));
    $intro_message = get_option('wordchat_intro_message', sprintf('Welcome to %s! Can I help answer any questions?', $site_name));
    $navigate_to_response = get_option('wordchat_navigate_to_response', '1'); // Default: enabled
    $primary_color = get_option('wordchat_primary_color', '#1A73E8');
    $start_open = get_option('wordchat_start_open', '1'); // Default: open
    $position = get_option('wordchat_position', 'right'); // Default: right
    $placeholder = get_option('wordchat_placeholder', 'Ask a question...');
    $button_text = get_option('wordchat_button_text', 'Send');

    wp_localize_script('wordchat-chat', 'WordChatVars', [
        // SECURITY: Credentials are NO LONGER exposed to browser
        // API calls now go through server-side proxy (includes/api-proxy.php)
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wordchat_query_nonce'),
        'header_text' => $header_text,
        'intro_message' => $intro_message,
        'navigate_to_response' => $navigate_to_response === '1',
        'primary_color' => $primary_color,
        'start_open' => $start_open === '1',
        'position' => $position,
        'placeholder' => $placeholder,
        'button_text' => $button_text
    ]);
}
add_action('wp_enqueue_scripts', 'wordchat_enqueue_widget');

// --- ACTIVATION REDIRECT ---
function wordchat_activation_redirect($plugin) {
    if ($plugin === plugin_basename(__FILE__)) {
        exit(wp_redirect(admin_url('admin.php?page=wordchat-pro')));
    }
}
add_action('activated_plugin', 'wordchat_activation_redirect');

// --- FREE USER TELEMETRY ---
/**
 * Send telemetry for free users (daily check-in)
 * This helps track active installations and plugin health
 */
function wordchat_send_free_user_telemetry() {
    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');

    // Only send if registered
    if (!$site_id || !$api_key) {
        return;
    }

    // Get site stats
    $post_count = wp_count_posts('post');
    $page_count = wp_count_posts('page');

    // Get synced content count
    global $wpdb;
    $synced_count = $wpdb->get_var(
        "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = 'wordchat_synced' AND meta_value = '1'"
    );

    $telemetry_data = [
        'site_id' => $site_id,
        'api_key' => $api_key,
        'domain' => get_site_url(),
        'plugin_version' => WORDCHAT_VERSION,
        'wp_version' => get_bloginfo('version'),
        'php_version' => PHP_VERSION,
        'active_plugins' => count(get_option('active_plugins', [])),
        'total_posts' => $post_count->publish ?? 0,
        'total_pages' => $page_count->publish ?? 0,
        'wordchat_synced_content' => (int) $synced_count,
        'is_free_user' => true,
        'plugin_slug' => WORDCHAT_PLUGIN_SLUG,
        'timestamp' => current_time('mysql')
    ];

    // Send async (non-blocking)
    wp_remote_post(WORDCHAT_API_URL . '/telemetry/daily-checkin', [
        'blocking' => false,
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($telemetry_data),
        'timeout' => 5
    ]);

    error_log("WordChat: Daily telemetry sent (free user)");
}
