<?php
/**
 * Plugin Name:       EONSR AEO Agent
 * Description:       Generate long-form SEO, AEO articles with a 2-pane UI using Google Gemini API. Integrates a highly detailed, structured prompt for superior quality.
 * Version:           3.7.9
 * Author:            Eonsr Team
 * Author URI:        https://eonsr.com/en/
 * License:           GPL-2.0+
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       eonsr-aeo-agent
 * Domain Path:       /languages
 * Requires at least: 6.8
 * Requires PHP:      7.4
 */

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

// ============================================================================
// CONSTANTS
// ============================================================================
define('EONSR_AEO_AGENT_VERSION', '3.7.9');
define('EONSR_AEO_AGENT_PATH', plugin_dir_path(__FILE__));
define('EONSR_AEO_AGENT_URL', plugin_dir_url(__FILE__));
define('EONSR_AEO_AGENT_API_URL', 'https://commercial-api.congtyeon.com');

// ============================================================================
// FILE LOADER
// ============================================================================

/**
 * Load required plugin files.
 */
function eonsr_aeo_agent_load_plugin_files()
{
    // Core Functionality
    require_once EONSR_AEO_AGENT_PATH . 'includes/api-functions.php';
    require_once EONSR_AEO_AGENT_PATH . 'includes/helpers.php';
    require_once EONSR_AEO_AGENT_PATH . 'includes/keyphrase-api.php';
    require_once EONSR_AEO_AGENT_PATH . 'includes/ajax-handlers.php';
    
    // Licensing & Purchase
    require_once EONSR_AEO_AGENT_PATH . 'includes/license-handler.php';
    require_once EONSR_AEO_AGENT_PATH . 'includes/purchase-ui.php';
    require_once EONSR_AEO_AGENT_PATH . 'includes/payment-handlers.php';
    
    // Core Logic & Sync
    require_once EONSR_AEO_AGENT_PATH . 'includes/rest-api-sync.php';
    require_once EONSR_AEO_AGENT_PATH . 'includes/translation-poller-cron.php';
    require_once EONSR_AEO_AGENT_PATH . 'includes/single-tab-lock.php'; 
    require_once EONSR_AEO_AGENT_PATH . 'includes/bulk-processor.php';

    // Polylang Integrations
    if (file_exists(EONSR_AEO_AGENT_PATH . 'includes/polylang-helpers.php')) {
        require_once EONSR_AEO_AGENT_PATH . 'includes/polylang-helpers.php';
    }
    
    if (file_exists(EONSR_AEO_AGENT_PATH . 'includes/polylang-background-translation.php')) {
        require_once EONSR_AEO_AGENT_PATH . 'includes/polylang-background-translation.php';
    }

    // Admin UI
    require_once EONSR_AEO_AGENT_PATH . 'includes/admin-ui.php';
}
add_action('plugins_loaded', 'eonsr_aeo_agent_load_plugin_files');

// ============================================================================
// ADMIN MENUS
// ============================================================================

/**
 * Register Admin Menus.
 */
function eonsr_aeo_agent_register_admin_menus()
{
    // Check CSV Feature Permission
    $features  = get_option('eonsr_aeo_agent_license_features', []);
    $allow_csv = $features['allowCSV'] ?? false;

    // Main Menu
    add_menu_page(
        'AEO Agent',              
        'AEO Agent',              
        'edit_posts',             
        'eonsr_aeo_agent',               
        'eonsr_aeo_agent_article_studio_page',
        'dashicons-editor-textcolor',     
        30
    );

    // Submenu: Dashboard
    add_submenu_page(
        'eonsr_aeo_agent',              
        'AEO Agent',           
        'AEO Agent',           
        'edit_posts',             
        'eonsr_aeo_agent',               
        'eonsr_aeo_agent_article_studio_page' 
    );

    // Submenu: Upgrade
    add_submenu_page(
        'eonsr_aeo_agent',
        __( 'Nâng Cấp', 'eonsr-aeo-agent' ),
        __( 'Nâng Cấp', 'eonsr-aeo-agent' ),
        'manage_options',
        'eonsr_aeo_agent_purchase',
        'eonsr_aeo_agent_purchase_page_content'
    );

    // Submenu: License Activation
    add_submenu_page(
        'eonsr_aeo_agent',
        __( 'Kích hoạt bản quyền', 'eonsr-aeo-agent' ),
        __( 'Kích hoạt bản quyền', 'eonsr-aeo-agent' ),
        'manage_options',
        'eonsr_aeo_agent_license',
        'eonsr_aeo_agent_license_page_content'
    );

    // Submenu: Bulk Generator (Conditional)
    if ($allow_csv) {
        add_submenu_page(
            'eonsr_aeo_agent',
            __( 'Tạo bài hàng loạt', 'eonsr-aeo-agent' ),
            __( 'Tạo bài hàng loạt', 'eonsr-aeo-agent' ),
            'publish_posts',
            'eonsr_aeo_agent_bulk_generate',
            'eonsr_aeo_agent_bulk_generate_page'
        );
    }
}
add_action('admin_menu', 'eonsr_aeo_agent_register_admin_menus');

// ============================================================================
// ASSETS ENQUEUE
// ============================================================================

/**
 * Enqueue Admin Scripts & Styles.
 */
add_action('admin_enqueue_scripts', function ($hook) {
    // Determine allowed hooks
    $is_main_page = ($hook === 'toplevel_page_eonsr_aeo_agent');
    $is_bulk_page = ($hook === 'aeo-agent_page_eonsr_aeo_agent_bulk_generate'); 
    
    // Only load on plugin pages
    if (strpos($hook, 'eonsr_aeo_agent') === false) {
        return;
    }

    // 1. Global Assets (CSS & SweetAlert)
    wp_enqueue_style(
        'eonsr-aeo-agent-admin-style',
        EONSR_AEO_AGENT_URL . 'assets/css/admin-style.css',
        [],
        EONSR_AEO_AGENT_VERSION
    );

    // Load local SweetAlert to avoid external resource warning
    wp_enqueue_script(
        'sweetalert2', 
        EONSR_AEO_AGENT_URL . 'assets/js/sweetalert2.all.min.js', 
        [], 
        EONSR_AEO_AGENT_VERSION, 
        true
    );

    // Fix Z-Index for SweetAlert
    wp_add_inline_style('eonsr-aeo-agent-admin-style', '.swal2-container { z-index: 999999 !important; }');

    // 2. Main Dashboard Assets
    if ($is_main_page) {
        wp_enqueue_script(
            'eonsr-aeo-agent-admin-script',
            EONSR_AEO_AGENT_URL . 'assets/js/admin-script.js',
            ['jquery', 'sweetalert2'],
            EONSR_AEO_AGENT_VERSION,
            true
        );

        wp_localize_script('eonsr-aeo-agent-admin-script', 'eonsr_aeo_agent_ajax', [
            'ajax_url'                => admin_url('admin-ajax.php'),
            'generate_text_nonce'     => wp_create_nonce('eonsr_aeo_agent_generate_ajax'),
            'generate_images_nonce'   => wp_create_nonce('eonsr_aeo_agent_generate_images_ajax'),
            'update_categories_nonce' => wp_create_nonce('eonsr_aeo_agent_update_categories_ajax'),
            'update_content_nonce'    => wp_create_nonce('eonsr_aeo_agent_update_content_ajax'),
            'translate_nonce'         => wp_create_nonce('eonsr_aeo_agent_polylang_translate_ajax'),
            'poll_nonce'              => wp_create_nonce('eonsr_aeo_agent_poll_job_ajax'),
            'auto_translate_nonce'    => wp_create_nonce('eonsr_aeo_agent_auto_translate'),
            'check_active_nonce'      => wp_create_nonce('eonsr_aeo_agent_check_active_nonce'), 
            'setup_nonce'             => wp_create_nonce('eonsr_aeo_agent_setup_nonce'), 
        ]);
    }
    
    // 3. Bulk Processor Assets
    if ($is_bulk_page) {
        wp_enqueue_script(
            'eonsr-aeo-agent-bulk-processor',
            EONSR_AEO_AGENT_URL . 'assets/js/bulk-processor.js',
            ['jquery', 'sweetalert2'],
            EONSR_AEO_AGENT_VERSION,
            true
        );
        
        wp_localize_script('eonsr-aeo-agent-bulk-processor', 'eonsrAeoAgentData', [
            'ajaxurl'         => admin_url('admin-ajax.php'),
            'bulkNonce'       => wp_create_nonce('eonsr_aeo_agent_bulk_upload_csv'),
            'bulkStatusNonce' => wp_create_nonce('eonsr_aeo_agent_bulk_status_ajax'),
        ]);
    }
    wp_enqueue_style(
        'eonsr-aeo-agent-purchase-ui',
        EONSR_AEO_AGENT_URL . 'assets/css/purchase-ui.css',
        [],
        EONSR_AEO_AGENT_VERSION
    );
});

/**
 * Enqueue Frontend Scripts.
 */
add_action('wp_enqueue_scripts', function() {
    if (is_singular('post')) {
        wp_enqueue_script(
            'eonsr-aeo-youtube-handler',
            EONSR_AEO_AGENT_URL . 'assets/js/frontend-youtube.js',
            [],
            EONSR_AEO_AGENT_VERSION,
            true
        );
        wp_enqueue_script(
            'eonsr-aeo-summary-widget',
            EONSR_AEO_AGENT_URL . 'assets/js/frontend-summary.js',
            [],
            EONSR_AEO_AGENT_VERSION,
            true
        );
    }
});

// ============================================================================
// REST API: INTERNAL LINK V5
// ============================================================================

add_action('rest_api_init', function () {
    register_rest_route('eonsr-aeo-agent/v1', '/posts', [
        'methods'             => 'GET',
        'callback'            => 'eonsr_aeo_agent_get_posts_api_v5_safe',
        'permission_callback' => '__return_true',
    ]);
});

/**
 * Retrieve posts for Internal Linking.
 * Using get_posts() with caching to satisfy WP DirectQuery standards.
 */
function eonsr_aeo_agent_get_posts_api_v5_safe($request)
{
    // 1. Performance Optimization
    wp_suspend_cache_addition(true);
    wp_suspend_cache_invalidation(true);

    $limit = intval($request->get_param('limit') ?: 50);

    // 2. Query with Caching
    $cache_key   = 'eonsr_aeo_posts_v5_' . $limit;
    $cache_group = 'eonsr_aeo_agent';
    $rows        = wp_cache_get($cache_key, $cache_group);

    if (false === $rows) {
        // Use get_posts instead of $wpdb to comply with WP standards
        $args = [
            'numberposts'            => $limit,
            'post_type'              => 'post',
            'post_status'            => 'publish',
            'orderby'                => 'date',
            'order'                  => 'DESC',
            'no_found_rows'          => true,  // Optimize: don't calc total rows
            'update_post_meta_cache' => false, // Optimize: don't load meta
            'update_post_term_cache' => false, // Optimize: don't load terms
            'suppress_filters'       => true,  // Optimize: skip most filters
        ];

        $posts_data = get_posts($args);

        // Transform WP_Post objects to simple array of objects matching previous structure
        $rows = [];
        if (!empty($posts_data)) {
            foreach ($posts_data as $p) {
                $rows[] = (object) [
                    'ID' => $p->ID,
                    'post_title' => $p->post_title
                ];
            }
        }

        // Cache the results for 5 minutes
        wp_cache_set($cache_key, $rows, $cache_group, 300);
    }

    $home = home_url('/');
    $response = ['all' => []];

    // 3. Get Saved Languages
    $saved_langs = get_option('eonsr_aeo_agent_selected_languages', ['Vietnamese', 'English']);

    // 4. Language Mapping
    $lang_map = [
        'Vietnamese' => 'vi', 'English' => 'en', 'French' => 'fr', 'German' => 'de',
        'Japanese' => 'ja', 'Korean' => 'ko', 'Chinese' => 'zh', 'Russian' => 'ru',
        'Spanish' => 'es', 'Italian' => 'it', 'Thai' => 'th', 'Indonesian' => 'id',
        'Portuguese' => 'pt', 'Hindi' => 'hi', 'Arabic' => 'ar', 'Turkish' => 'tr',
        'Dutch' => 'nl', 'Swedish' => 'sv', 'Norwegian' => 'no', 'Danish' => 'da',
        'Finnish' => 'fi', 'Polish' => 'pl', 'Ukrainian' => 'uk', 'Hebrew' => 'he'
    ];

    // 5. Initialize Response Arrays
    $active_lang_codes = [];
    foreach ($saved_langs as $lang_name) {
        if (isset($lang_map[$lang_name])) {
            $code = $lang_map[$lang_name];
            $response[$code] = [];
            $active_lang_codes[] = $code;
        }
    }

    // 6. Distribute Data
    if ($rows) {
        foreach ($rows as $row) {
            $item = [
                'id'    => (int)$row->ID,
                'title' => $row->post_title,
                'url'   => $home . '?p=' . $row->ID
            ];

            $response['all'][] = $item;

            foreach ($active_lang_codes as $code) {
                $response[$code][] = $item;
            }
        }
    }

    wp_send_json($response, 200);
    exit;
}

// ============================================================================
// DATABASE & ACTIVATION
// ============================================================================

/**
 * Create custom database tables on activation.
 */
function eonsr_aeo_agent_create_tables()
{
    global $wpdb;
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $charset_collate = $wpdb->get_charset_collate();

    // Table 1: Cost Logs
    $table_cost = $wpdb->prefix . 'eonsr_aeo_agent_cost_logs';
    $sql_cost = "CREATE TABLE $table_cost (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        post_id bigint(20) UNSIGNED NOT NULL,
        generation_date datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        primary_term tinytext NOT NULL,
        model_name varchar(55) DEFAULT '' NOT NULL,
        gemini_usage_details longtext,
        images_generated tinyint(2) UNSIGNED DEFAULT 0 NOT NULL,
        search_queries tinyint(3) UNSIGNED DEFAULT 0 NOT NULL,
        youtube_queries tinyint(3) UNSIGNED DEFAULT 0 NOT NULL,
        PRIMARY KEY  (id),
        KEY post_id (post_id)
    ) $charset_collate;";
    dbDelta($sql_cost);

    // Table 2: Bulk Logs
    $table_bulk = $wpdb->prefix . 'eonsr_aeo_agent_bulk_logs';
    $sql_bulk = "CREATE TABLE $table_bulk (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        bulk_id varchar(100) NOT NULL,
        filename varchar(255) NOT NULL,
        total_jobs int(11) DEFAULT 0,
        status varchar(50) DEFAULT 'processing',
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY  (id),
        KEY bulk_id (bulk_id)
    ) $charset_collate;";
    dbDelta($sql_bulk);
}
register_activation_hook(__FILE__, 'eonsr_aeo_agent_create_tables');

/**
 * Set default options on activation.
 */
function eonsr_aeo_agent_on_activation()
{
    add_option('eonsr_aeo_agent_license_status', 'unsubmitted');
    add_option('eonsr_aeo_agent_needs_activation_redirect', true);
}
register_activation_hook(__FILE__, 'eonsr_aeo_agent_on_activation');

/**
 * Redirect to purchase page after first activation.
 */
add_action('admin_init', function () {
    if (get_option('eonsr_aeo_agent_needs_activation_redirect', false)) {
        delete_option('eonsr_aeo_agent_needs_activation_redirect');
        
        // FIX: Use safe redirect
        $target_url = admin_url('admin.php?page=eonsr_aeo_agent_purchase');
        wp_safe_redirect($target_url);
        exit;
    }
});

/**
 * Hide License Menu if activated.
 */
add_action('admin_menu', function () {
    $license_status = get_option('eonsr_aeo_agent_license_status', 'unsubmitted');
    if ($license_status === 'activated') {
        remove_submenu_page('eonsr_aeo_agent', 'eonsr_aeo_agent_license');
    }
}, 99);

// ============================================================================
// FRONTEND WIDGETS
// ============================================================================

/**
 * Render Summary Widget in Footer and move it via JS.
 */
add_action('wp_footer', 'eonsr_aeo_agent_output_widget_and_script');

function eonsr_aeo_agent_output_widget_and_script()
{
    if (!is_singular('post')) return;

    $post_id = get_the_ID();
    $summary_paragraph = get_post_meta($post_id, '_eonsr_aeo_summary_paragraph', true);
    $summary_bullets_json = get_post_meta($post_id, '_eonsr_aeo_summary_bullets', true);
    $summary_bullets = !empty($summary_bullets_json) ? json_decode($summary_bullets_json, true) : [];

    if (empty($summary_paragraph) && empty($summary_bullets)) {
        return;
    }
    ?>
    <!-- HTML Widget -->
    <div id="eonsr-aeo-ai-summary-wrapper" style="display:none;">
        <div class="project-summary-button-row dropdown">
            <a href="javascript:void(0);" class="btn btn-summary" data-bs-toggle="dropdown"
                data-bs-auto-close="outside" aria-expanded="false" data-bs-display="static">
                <i class="fas fa-wand-magic-sparkles magic-icon"></i>
                <span>Đọc bản tóm tắt do AI tạo ra</span>
                <i class="fas fa-chevron-down ms-2"></i>
            </a>

            <div class="dropdown-menu ai-summary-dropdown-menu p-4">
                <div class="tab-content" id="aiSummaryTabContent">
                    <div class="tab-pane fade show active" id="pills-general" role="tabpanel">
                        <h2 class="ai-summary-title">Tóm tắt chung</h2>
                        <div class="ai-summary-text">
                            <!-- FIX: Use wp_kses_post instead of wpautop directly to prevent XSS warnings -->
                            <?php echo wp_kses_post(wpautop($summary_paragraph)); ?>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="pills-bullets" role="tabpanel">
                        <h2 class="ai-summary-title">Dấu đầu dòng</h2>
                        <ul class="ai-summary-list">
                            <?php 
                            if (is_array($summary_bullets)) {
                                foreach ($summary_bullets as $bullet) {
                                    echo '<li>' . esc_html($bullet) . '</li>';
                                }
                            }
                            ?>
                        </ul>
                    </div>
                </div>

                <p class="ai-summary-disclaimer">
                    Tóm tắt được tạo ra bởi trợ lý ảo EONSR. Trí tuệ nhân tạo (AI) là công nghệ thử nghiệm.
                </p>

                <div class="ai-summary-styles">
                    <p class="styles-title">Khám phá các phong cách khác:</p>
                    <div class="styles-buttons">
                        <ul class="nav nav-pills" id="aiSummaryTab" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active eonsr-aeo-tab-trigger" id="pills-general-tab" 
                                    data-bs-target="#pills-general" type="button" role="tab">
                                    Tóm tắt chung
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link eonsr-aeo-tab-trigger" id="pills-bullets-tab" 
                                    data-bs-target="#pills-bullets" type="button" role="tab">
                                    Dấu đầu dòng
                                </button>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php
}