<?php
/**
 * Plugin Name: AI Content Wizard Lite by BuyReadySite.com
 * Plugin URI: https://aiwizard.buyreadysite.com/
 * Description: Advanced AI-driven content creation and SEO optimization tool (Lite version). Generate SEO-optimized articles with OpenAI and track content generation progress. Since version 2.0, Lite adds support for the newest intonation-aware text model gpt-5-mini for more natural phrasing and improved context retention. Lite supports OpenAI text generation models (including gpt-5-mini) and DALL-E image generation; advanced models and features are in Pro.
 * Version: 2.5
 * Author: BuyReadySite.com
 * Author URI: https://buyreadysite.com/
 * Text Domain: ai-content-wizard
 * Domain Path: /languages/
 * Requires at least: 5.5
 * Tested up to: 6.8
 * Requires PHP: 7.4
 * License: GPLv2 or later
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

// Basic plugin constants.
define( 'AI_CONTENT_WIZARD_VERSION', '2.5' );
define( 'AI_CONTENT_WIZARD_PATH', plugin_dir_path( __FILE__ ) );
define( 'AI_CONTENT_WIZARD_URL', plugin_dir_url( __FILE__ ) );
define( 'AI_CONTENT_WIZARD_PLUGIN_FILE', __FILE__ );

// --- Activation hook ---
register_activation_hook( __FILE__, 'ai_content_wizard_activate' );
/**
 * Runs on plugin activation.
 */
function ai_content_wizard_activate() {
    if ( get_option( 'ai_content_wizard_wizard_completed' ) === false ) {
        update_option( 'ai_content_wizard_wizard_completed', 0 );
    }
    ai_content_wizard_send_activation_notification();
}

// Deactivation feedback.
require_once AI_CONTENT_WIZARD_PATH . 'deactivation-feedback.php';

// Load text domain.
add_action( 'init', 'ai_content_wizard_load_textdomain' );
function ai_content_wizard_load_textdomain() {
    load_plugin_textdomain( 'ai-content-wizard', false, basename( dirname( __FILE__ ) ) . '/languages/' );
}

// Main initialization.
add_action( 'plugins_loaded', 'ai_content_wizard_init' );
function ai_content_wizard_init() {
    global $wpdb;
    // Update stored version if needed.
    update_option( 'ai_content_wizard_plugin_version', AI_CONTENT_WIZARD_VERSION );
    
    // Check for content plan table.
    $table_content_plan = $wpdb->prefix . 'ai_content_wizard_content_plan';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_content_plan'" ) != $table_content_plan ) {
        ai_content_wizard_create_content_plan_table();
    }
    
    // Check for other necessary tables.
    $tables_to_check = [
        'settings'      => $wpdb->prefix . 'ai_content_wizard_settings',
        'posts_logs'    => $wpdb->prefix . 'ai_content_wizard_posts_logs',
        'content_plan_logs' => $wpdb->prefix . 'ai_content_wizard_content_plan_logs'
    ];
    
    foreach ( $tables_to_check as $table_key => $table_name ) {
        if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) != $table_name ) {
            switch ( $table_key ) {
                case 'settings':
                    ai_content_wizard_create_settings_table();
                    break;
                case 'posts_logs':
                case 'content_plan_logs':
                    ai_content_wizard_create_logs_tables();
                    break;
            }
        }
    }
    
    // Include admin pages and functions.
    require_once AI_CONTENT_WIZARD_PATH . 'admin/menu.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/settings-functions.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/api-settings-page.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/logs-page.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/settings-page.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/statistics-page.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/create-post-page.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/main-page.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/ai-content-wizard-system-check.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/ai-wizard-help.php';
    require_once AI_CONTENT_WIZARD_PATH . 'admin/ai_content_wizard_logger.php';

    require_once AI_CONTENT_WIZARD_PATH . 'includes/ai_content_wizard_cost_calculator.php';
    require_once AI_CONTENT_WIZARD_PATH . 'includes/ai_content_wizard_news_fetcher.php';
    require_once AI_CONTENT_WIZARD_PATH . 'includes/promopilot-banner.php';
	require_once AI_CONTENT_WIZARD_PATH . 'includes/ai_content_wizard_toc_function.php';

    require_once AI_CONTENT_WIZARD_PATH . 'admin/wizard-setup/settings-wizard.php';
    
    // Optionally, redirect to wizard if not completed.
    //add_action( 'admin_init', 'ai_content_wizard_check_wizard_redirect' );
    
    // Enqueue scripts and styles.
    add_action( 'admin_enqueue_scripts', 'ai_content_wizard_enqueue_scripts' );
    
    // Add links for documentation, support and Buy Pro.
    add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'ai_content_wizard_add_action_links' );
    add_filter( 'plugin_row_meta', 'ai_content_wizard_add_support_link', 10, 2 );
    
    // Display admin notices.
    //add_action( 'admin_notices', 'ai_content_wizard_check_plugin_update_notice' );
    //add_action( 'admin_notices', 'ai_content_wizard_check_content_plan_existence_and_api_key_notice' );
    // Removed: Model update notice.
}

// Function to create settings table.
function ai_content_wizard_create_settings_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_settings';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        setting_key varchar(191) NOT NULL,
        setting_value text NOT NULL,
        PRIMARY KEY (id),
        UNIQUE KEY setting_key (setting_key)
    ) $charset_collate;";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );

    if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) != $table_name ) {
        error_log( "AI Content Wizard: Table $table_name was not created successfully." );
        return false;
    } else {
        //error_log( "AI Content Wizard: Table $table_name was created successfully." );
        return true;
    }
}

// Function to create logs tables.
function ai_content_wizard_create_logs_tables() {
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();

    // Posts logs table.
    $table_posts_logs = $wpdb->prefix . 'ai_content_wizard_posts_logs';
    $sql_posts_logs = "CREATE TABLE $table_posts_logs (
        id BIGINT(20) NOT NULL AUTO_INCREMENT,
        post_id BIGINT(20) NOT NULL,
        type VARCHAR(50) NOT NULL,
        category VARCHAR(255) NOT NULL,
        generation_time DATETIME NOT NULL,
        publish_time DATETIME NOT NULL,
        title VARCHAR(255) NOT NULL,
        keyword VARCHAR(255) NOT NULL,
        language VARCHAR(10) NOT NULL,
        text_model VARCHAR(100) NOT NULL,
        image_model VARCHAR(100) NOT NULL,
        image_cost DECIMAL(10,3) NOT NULL,
        text_cost DECIMAL(10,3) NOT NULL,
        total_cost DECIMAL(10,3) NOT NULL,
        format VARCHAR(50) NOT NULL,
        text_length VARCHAR(50) NOT NULL,
        writing_style VARCHAR(50) NOT NULL,
        target_audience VARCHAR(50) NOT NULL,
        image_quality VARCHAR(50) NOT NULL,
        image_size VARCHAR(50) NOT NULL,
        site_type VARCHAR(50) NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

    // Content plan logs table.
    $table_content_plan_logs = $wpdb->prefix . 'ai_content_wizard_content_plan_logs';
    $sql_content_plan_logs = "CREATE TABLE $table_content_plan_logs (
        id BIGINT(20) NOT NULL AUTO_INCREMENT,
        type VARCHAR(50) NOT NULL,
        text_model VARCHAR(100) NOT NULL,
        date DATETIME NOT NULL,
        total_articles INT(11) NOT NULL,
        interval_days VARCHAR(50) NOT NULL,
        period_days INT(11) NOT NULL,
        language VARCHAR(10) NOT NULL,
        categories INT(11) NOT NULL,
        total_cost DECIMAL(10,2) NOT NULL,
        type_plugin VARCHAR(50) NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql_posts_logs );
    dbDelta( $sql_content_plan_logs );
}

// Function to create content plan table.
function ai_content_wizard_create_content_plan_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_content_plan';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id BIGINT(20) NOT NULL AUTO_INCREMENT,
        category_id VARCHAR(255) NOT NULL,
        title TEXT NOT NULL,
        keyword TEXT NOT NULL,
        date_time DATETIME NOT NULL,
        status VARCHAR(50) NOT NULL,
        action VARCHAR(50) NOT NULL,
        cost DECIMAL(20,10) NOT NULL,
        post_id BIGINT(20) DEFAULT NULL,
        uid VARCHAR(255) DEFAULT NULL,
        post_url VARCHAR(255) DEFAULT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );

    if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) != $table_name ) {
        error_log( "AI Content Wizard: Table $table_name was not created successfully." );
        return false;
    } else {
        //error_log( "AI Content Wizard: Table $table_name was created successfully." );
        return true;
    }
}

/**********************************************/
// Enqueue front-end scripts and styles.
function ai_content_wizard_enqueue_frontend_scripts() {
    if ( is_singular() && ai_content_wizard_has_toc() ) {
        wp_enqueue_style(
            'ai-content-wizard-frontend-style',
            AI_CONTENT_WIZARD_URL . 'css/frontend-style.css',
            array(),
            AI_CONTENT_WIZARD_VERSION
        );
    }
}
add_action( 'wp_enqueue_scripts', 'ai_content_wizard_enqueue_frontend_scripts' );

function ai_content_wizard_has_toc() {
    $post = get_post();
    if ( $post && ( has_shortcode( $post->post_content, 'ai_content_wizard_toc' ) || strpos( $post->post_content, 'custom-toc' ) !== false ) ) {
        return true;
    }
    return false;
}
/***************************************************/

// Optional redirect after activation.
function ai_content_wizard_redirect_after_activation() {
    if ( get_option( 'ai_content_wizard_redirect_on_activation', false ) ) {
        delete_option( 'ai_content_wizard_redirect_on_activation' );
        if ( ! isset( $_GET['page'] ) || $_GET['page'] !== 'ai_content_wizard_wizard' ) {
            wp_redirect( admin_url( 'admin.php?page=ai_content_wizard_wizard' ) );
            exit;
        }
    }
}
add_action( 'admin_init', 'ai_content_wizard_redirect_after_activation' );

// Enqueue admin scripts and styles.
function ai_content_wizard_enqueue_scripts( $hook ) {
    wp_enqueue_style( 'jquery-ui-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css' );
    wp_enqueue_style( 'font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css' );
    wp_enqueue_style( 'ai-content-wizard-style', AI_CONTENT_WIZARD_URL . 'css/style.css', array(), AI_CONTENT_WIZARD_VERSION );

    wp_enqueue_script( 'jquery-ui-accordion' );
    wp_enqueue_script( 'ai-content-wizard-script', AI_CONTENT_WIZARD_URL . 'js/ai-content-wizard-script.js', array( 'jquery', 'jquery-ui-accordion' ), AI_CONTENT_WIZARD_VERSION, true );
    wp_localize_script( 'ai-content-wizard-script', 'aiContentWizard', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    wp_localize_script( 'ai-content-wizard-script', 'clockLocalization', array(
        'hours'   => __( 'HOURS', 'ai-content-wizard' ),
        'minutes' => __( 'MINUTES', 'ai-content-wizard' ),
        'seconds' => __( 'SECONDS', 'ai-content-wizard' )
    ) );

    if ( 'toplevel_page_ai_content_wizard' === $hook ) {
        // Additional scripts for main plugin page.
    }
}

/**********************************************/
// Add links for Documentation, Support and Buy Pro.
function ai_content_wizard_add_action_links( $links ) {
    $docs_link = '<a href="https://aiwizard.buyreadysite.com/docs" target="_blank">' . __( 'Documentation', 'ai-content-wizard' ) . '</a>';
    $support_link = '<a href="https://aiwizard.buyreadysite.com/support" target="_blank">' . __( 'Support', 'ai-content-wizard' ) . '</a>';
    $buypro_link = '<a href="https://aiwizard.buyreadysite.com/" target="_blank">' . __( 'Buy Pro', 'ai-content-wizard' ) . '</a>';
    array_push( $links, $docs_link, $support_link, $buypro_link );
    return $links;
}

function ai_content_wizard_add_support_link( $links, $file ) {
    if ( $file == plugin_basename( __FILE__ ) ) {
        $support_link = '<a href="https://aiwizard.buyreadysite.com/support" target="_blank">' . __( 'Support', 'ai-content-wizard' ) . '</a>';
        $buypro_link = '<a href="https://aiwizard.buyreadysite.com/" target="_blank">' . __( 'Buy Pro', 'ai-content-wizard' ) . '</a>';
        array_push( $links, $support_link, $buypro_link );
    }
    return $links;
}

if ( ! function_exists( 'ai_content_wizard_format_env_info' ) ) {
    /**
     * Returns a multiline string with key environment details for Telegram messages.
     */
    function ai_content_wizard_format_env_info() {
        global $wpdb;

        $domain = preg_replace( '#^https?://#', '', home_url() );
        $site_title = get_bloginfo( 'name' );

        $plugin_version = defined( 'AI_CONTENT_WIZARD_VERSION' ) ? AI_CONTENT_WIZARD_VERSION : 'n/a';
        $wp_version     = get_bloginfo( 'version' );
        $php_version    = PHP_VERSION;

        $theme      = function_exists( 'wp_get_theme' ) ? wp_get_theme() : null;
        $theme_line = $theme ? ( $theme->get( 'Name' ) . ' ' . $theme->get( 'Version' ) ) : 'n/a';

        $user     = function_exists( 'wp_get_current_user' ) ? wp_get_current_user() : null;
        $user_str = ( $user && isset( $user->ID ) && $user->ID )
            ? ( $user->user_login . ( $user->display_name && $user->display_name !== $user->user_login ? ' (' . $user->display_name . ')' : '' ) )
            : 'guest';

        try {
            $dt    = new DateTime( 'now', function_exists( 'wp_timezone' ) ? wp_timezone() : new DateTimeZone( wp_timezone_string() ?: 'UTC' ) );
            $time  = $dt->format( 'Y-m-d H:i:s (P)' );
        } catch ( Exception $e ) {
            $time = current_time( 'mysql' );
        }

        $active_plugins = (array) get_option( 'active_plugins', array() );
        if ( is_multisite() ) {
            $network_plugins = array_keys( (array) get_site_option( 'active_sitewide_plugins', array() ) );
            $active_plugins  = array_unique( array_merge( $active_plugins, $network_plugins ) );
        }
        $plugins_count = count( $active_plugins );

        $db_ver = method_exists( $wpdb, 'db_version' ) ? $wpdb->db_version() : '';

        $lines = array(
            "🌐 Домен: {$domain}",
            "🏷️ Сайт: {$site_title}",
            "🔖 Версия плагина: {$plugin_version}",
            "🧩 WordPress: {$wp_version}",
            "🐘 PHP: {$php_version}",
            "🎨 Тема: {$theme_line}",
            "🔌 Активных плагинов: {$plugins_count}",
            $db_ver ? "🗄️ БД: {$db_ver}" : '',
            "👤 Пользователь: {$user_str}",
            "🕒 Время: {$time}",
        );

        // Remove empty lines and join.
        return implode( "\n", array_filter( $lines ) );
    }
}
// Plugin update notice.
function ai_content_wizard_check_plugin_update_notice() {
    if ( get_option( 'ai_content_wizard_wizard_completed', 0 ) == 0 ) {
        return;
    }
    $plugin_data = get_site_transient( 'update_plugins' );
    $plugin_slug = plugin_basename( __FILE__ );
    $update_url  = wp_nonce_url( self_admin_url( 'update.php?action=upgrade-plugin&plugin=' ) . $plugin_slug, 'upgrade-plugin_' . $plugin_slug );

    if ( isset( $plugin_data->response[ $plugin_slug ] ) ) {
        $update    = $plugin_data->response[ $plugin_slug ];
        $image_url = plugins_url( 'ai-content-wizard/css/img/notice.jpg', __DIR__ );
        ?>
        <div class="ai-content-wizard-notice" style="display: flex; align-items: center; padding: 20px; background-color: #fff; border-left: 4px solid #0073aa; margin: 20px 20px 20px 0; font-family: 'Open Sans', sans-serif;">
            <div class="ai-notice-col ai-notice-image" style="margin-right: 20px;">
                <img src="<?php echo esc_url( $image_url ); ?>" alt="<?php esc_attr_e( 'AI Content Wizard Update Available', 'ai-content-wizard' ); ?>" style="width: 100px;">
            </div>
            <div class="ai-notice-col ai-notice-text" style="flex-grow: 1;">
                <?php
                /* translators: %1$s — номер новой версии, %2$s — URL для обновления. */
                $translation_string = __( 'A new version of <strong>AI Content Wizard Lite</strong> (%1$s) is available. <a href="%2$s">Update now</a> to access the latest improvements. Lite version activated.', 'ai-content-wizard' );
                echo wp_kses_post(
                    sprintf(
                        $translation_string,
                        esc_html( $update->new_version ),
                        esc_url( $update_url )
                    )
                );
                ?>
            </div>
            <div class="ai-notice-col ai-notice-button" style="margin-left: auto;">
                <a href="<?php echo esc_url( $update_url ); ?>" class="button button-primary">
                    <?php esc_html_e( 'Update Now', 'ai-content-wizard' ); ?>
                </a>
            </div>
        </div>
        <?php
    }
}



function ai_content_wizard_dismiss_content_plan_notice() {
    check_ajax_referer( 'ai_content_wizard_dismiss_content_plan_notice', 'nonce' );
    update_option( 'ai_content_wizard_content_plan_notice_dismissed', true );
    wp_die();
}
add_action( 'wp_ajax_ai_content_wizard_dismiss_content_plan_notice', 'ai_content_wizard_dismiss_content_plan_notice' );

// Activation notification – modified for Lite version.
if ( ! function_exists( 'ai_content_wizard_send_activation_notification' ) ) {
    function ai_content_wizard_send_activation_notification() {
        $header  = "✅ Плагин активирован — AI Content Wizard Lite";
        $payload = function_exists( 'ai_content_wizard_format_env_info' ) ? ai_content_wizard_format_env_info() : '';
        $message = $header . "\n\n" . $payload;

        // Prefer helper from deactivation‑feedback.php if available.
        if ( function_exists( 'ai_content_wizard_send_telegram_message' ) ) {
            ai_content_wizard_send_telegram_message( $message );
            return;
        }

        // Fallback: direct Telegram API call (requires constants).
        $token   = defined( 'AI_CONTENT_WIZARD_TELEGRAM_TOKEN' ) ? AI_CONTENT_WIZARD_TELEGRAM_TOKEN : '';
        $chat_id = defined( 'AI_CONTENT_WIZARD_TELEGRAM_CHAT_ID' ) ? AI_CONTENT_WIZARD_TELEGRAM_CHAT_ID : '';

        if ( $token && $chat_id ) {
            wp_remote_post(
                "https://api.telegram.org/bot{$token}/sendMessage",
                array(
                    'timeout'  => 15,
                    'blocking' => false,
                    'body'     => array(
                        'chat_id'    => $chat_id,
                        'text'       => $message,
                        'parse_mode' => 'Markdown',
                    ),
                )
            );
        } else {
            error_log( 'AI Content Wizard: Telegram credentials are missing.' );
            error_log( $message ); // fallback log
        }
    }
}

// Generic Telegram helper (used by both activation and deactivation) —
// only defined if not already present.
if ( ! function_exists( 'ai_content_wizard_send_telegram_message' ) &&
     defined( 'AI_CONTENT_WIZARD_TELEGRAM_TOKEN' ) &&
     defined( 'AI_CONTENT_WIZARD_TELEGRAM_CHAT_ID' ) ) {

    /**
     * Sends Markdown text to Telegram.
     *
     * @param string $text
     */
    function ai_content_wizard_send_telegram_message( $text ) {
        wp_remote_post(
            "https://api.telegram.org/bot" . AI_CONTENT_WIZARD_TELEGRAM_TOKEN . "/sendMessage",
            [
                'timeout'  => 15,
                'blocking' => false,
                'body'     => [
                    'chat_id'    => AI_CONTENT_WIZARD_TELEGRAM_CHAT_ID,
                    'text'       => $text,
                    'parse_mode' => 'Markdown',
                ],
            ]
        );
    }
}

