<?php
// Protection from direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

function ai_content_wizard_add_admin_menu() {

    // Читаем содержимое SVG-файла
    $icon_svg = file_get_contents( AI_CONTENT_WIZARD_PATH . 'css/img/witch-hat.svg' );
    // Кодируем в base64
    $icon_base64 = base64_encode( $icon_svg );
    // Формируем data URI
    $custom_icon = 'data:image/svg+xml;base64,' . $icon_base64;

    add_menu_page(
        esc_html__( 'AI Content Wizard', 'ai-content-wizard' ),
        esc_html__( 'AI Content Wizard', 'ai-content-wizard' ),
        'manage_options',
        'ai_content_wizard',
        'ai_content_wizard_main_page',
        $custom_icon,
        6
    );

    // Проверяем, завершён ли мастер или настроены ли ключ и модель
    $wizard_completed = get_option( 'ai_content_wizard_wizard_completed', 0 );
    $api_key = ai_content_wizard_get_setting( 'ai_content_wizard_api_key' );
    
    // Если мастер не завершён и ключ/модель не настроены – добавляем пункт мастера
    if ( $wizard_completed != 1 ) {
        add_submenu_page(
            'ai_content_wizard', // parent slug
            esc_html__( '🚀 Setup Wizard', 'ai-content-wizard' ),
            esc_html__( '🚀 Setup Wizard', 'ai-content-wizard' ),
            'manage_options',
            'ai_content_wizard_wizard',
            'ai_content_wizard_wizard_page'
        );
    }

    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ Settings', 'ai-content-wizard' ),
        esc_html__( '➡ Settings', 'ai-content-wizard' ),
        'manage_options',
        'ai_content_wizard_settings',
        'ai_content_wizard_settings_page'
    );

    // Для Lite-версии блокируем пункты Content Plan, Content Stream и AI Training,
    // всегда используя "disabled" вариант и добавляя бейдж PRO.
    $content_plan_menu_slug   = 'ai_content_wizard_content_plan_disabled';
    $content_stream_menu_slug = 'ai_content_wizard_content_stream_disabled';
    $ai_training_menu_slug    = 'ai_content_wizard_ai_training_disabled';

    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ Content Plan', 'ai-content-wizard' ),
        // Разрешаем только тег <span> для бейджа
        wp_kses( __( '➡ Content Plan <span class="pro-badge" style="background:#dc3232; color:#fff; font-size:10px; padding:1px 4px; margin-left:5px; border-radius:3px;">PRO</span>', 'ai-content-wizard' ), array( 'span' => array( 'class' => true, 'style' => true ) ) ),
        'manage_options',
        $content_plan_menu_slug,
        '__return_false'
    );

    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ Create Post', 'ai-content-wizard' ),
        wp_kses( __( '➡ Create Post <span class="ai-content-wizard-new-badge" style="background: #ffba00; color: #000; margin-left: 5px; padding: 0 5px;">AI</span>', 'ai-content-wizard' ), array( 'span' => array( 'class' => true, 'style' => true ) ) ),
        'manage_options',
        empty( $api_key ) ? 'ai_content_wizard_create_post_disabled' : 'ai_content_wizard_create_post',
        empty( $api_key ) ? '__return_false' : 'ai_content_wizard_create_post_page'
    );

    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ Content Stream', 'ai-content-wizard' ),
        wp_kses( __( '➡ Content Stream <span class="pro-badge" style="background:#dc3232; color:#fff; font-size:10px; padding:1px 4px; margin-left:5px; border-radius:3px;">PRO</span>', 'ai-content-wizard' ), array( 'span' => array( 'class' => true, 'style' => true ) ) ),
        'manage_options',
        $content_stream_menu_slug,
        '__return_false'
    );

    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ API Settings', 'ai-content-wizard' ),
        esc_html__( '➡ API Settings', 'ai-content-wizard' ),
        'manage_options',
        'ai_content_wizard_api_settings',
        'ai_content_wizard_api_settings_page'
    );

    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ AI Training (Beta)', 'ai-content-wizard' ),
        wp_kses( __( '➡ AI Training <span class="pro-badge" style="background:#dc3232; color:#fff; font-size:10px; padding:1px 4px; margin-left:5px; border-radius:3px;">PRO</span>', 'ai-content-wizard' ), array( 'span' => array( 'class' => true, 'style' => true ) ) ),
        'manage_options',
        $ai_training_menu_slug,
        '__return_false'
    );

    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ Statistics', 'ai-content-wizard' ),
        esc_html__( '➡ Statistics', 'ai-content-wizard' ),
        'manage_options',
        'ai_content_wizard_statistics',
        'ai_content_wizard_statistics_page'
    );

    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ Logs', 'ai-content-wizard' ),
        esc_html__( '➡ Logs', 'ai-content-wizard' ),
        'manage_options',
        'ai_content_wizard_logs',
        'ai_content_wizard_logs_page'
    );
    
    add_submenu_page(
        'ai_content_wizard',
        esc_html__( '➡ System Check', 'ai-content-wizard' ),
        esc_html__( '➡ System Check', 'ai-content-wizard' ),
        'manage_options',
        'ai_content_wizard_system_check',
        'ai_content_wizard_system_check_page'
    );
}
add_action( 'admin_menu', 'ai_content_wizard_add_admin_menu' );

function ai_content_wizard_admin_styles() {
    ?>
    <style>
        /* Стили для отключенных пунктов меню */
        #adminmenu .wp-has-submenu .wp-submenu .ai-content-wizard-disabled {
            color: #6a6a6a;
            pointer-events: none;
        }
        /* Общие стили для бейджей */
        .pro-badge {
            background-color: #dc3232;
            color: #fff;
            font-size: 10px;
            padding: 1px 4px;
            margin-left: 5px;
            border-radius: 3px;
            vertical-align: middle;
        }
        .ai-content-wizard-new-badge {
            background-color: #ffba00;
            color: #000;
            font-size: 12px;
            padding: 2px 6px;
            margin-left: 5px;
            border-radius: 3px;
            vertical-align: middle;
        }
		
        /* Стили для уведомлений */
        .ai-content-wizard-notice {
            padding: 10px;
            background: linear-gradient(90deg, rgb(255 212 133 / 57%) 0%, rgb(242 156 156 / 76%) 100%);
            background-size: 400% 400%;
            animation: GradientBG 5s ease infinite;
            display: inline-flex;
            align-items: center;
            margin-top: 20px;
            margin-right: 20px;
            border-radius: 5px;
            border: 1px solid #616168;
        }
        .ai-notice-col {
            margin-right: 15px;
        }
        .ai-notice-image img {
            width: 80px;
            height: auto;
        }
        .ai-notice-text {
            flex-grow: 2;
        }
        .ai-notice-text p {
            font-size: 18px;
            line-height: 1.5;
            margin: 1em 0;
            font-weight: 500;
        }
        @keyframes GradientBG {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
        .ai-content-wizard-notice .button {
            padding: 10px 20px;
            font-size: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .ai-content-wizard-notice .dashicons {
            margin-right: 8px;
        }
        .ai-notice-button {
            margin-top: 10px;
        }
    </style>
    <?php
}
add_action( 'admin_head', 'ai_content_wizard_admin_styles' );

/**
 * Функция для блокировки меню
 */
function ai_content_wizard_disable_menu_items( $parent_file ) {
    global $submenu;
    if ( isset( $submenu['ai_content_wizard'] ) ) {
        foreach ( $submenu['ai_content_wizard'] as $key => $item ) {
            if ( in_array( $item[2], array(
                'ai_content_wizard_content_plan_disabled',
                'ai_content_wizard_create_post_disabled',
                'ai_content_wizard_content_stream_disabled',
                'ai_content_wizard_ai_training_disabled'
            ) ) ) {
                $submenu['ai_content_wizard'][ $key ][4] = 'ai-content-wizard-disabled';
            }
        }
    }
    return $parent_file;
}
add_filter( 'parent_file', 'ai_content_wizard_disable_menu_items' );

function ai_content_wizard_admin_notice() {
    // Не выводим уведомление, если мы на странице мастера установки
    if ( isset( $_GET['page'] ) && $_GET['page'] === 'ai_content_wizard_wizard' ) {
        return;
    }
    // Проверяем наличие API ключа
    if ( empty( ai_content_wizard_get_setting( 'ai_content_wizard_api_key' ) ) ) {
        $image_url = plugins_url( '/css/img/notice.jpg', dirname( __FILE__, 1 ) );
        ?>
        <div class="ai-content-wizard-notice">
            <div class="ai-notice-col ai-notice-image">
                <img src="<?php echo esc_url( $image_url ); ?>" alt="<?php esc_attr_e( 'AI Content Wizard', 'ai-content-wizard' ); ?>">
            </div>
            <div class="ai-notice-col ai-notice-text">
                <p>
                    <?php
                    echo wp_kses(
                        __( 'AI Content Wizard requires an API key to function properly. Please enter your API key and configure the necessary settings using the Setup Wizard.', 'ai-content-wizard' ),
                        array()
                    );
                    ?>
                </p>
            </div>
            <div class="ai-notice-col ai-notice-button">
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=ai_content_wizard_wizard' ) ); ?>" class="button button-primary ai-wizard-button">
                    <span class="dashicons dashicons-welcome-learn-more"></span>
                    <?php esc_html_e( 'Setup Wizard', 'ai-content-wizard' ); ?>
                </a>
            </div>
        </div>
        <?php
    }
}
add_action( 'admin_notices', 'ai_content_wizard_admin_notice' );

function ai_content_wizard_get_content_plan_status() {
    $is_running = get_content_plan_status(); // Логика проверки
    $remaining_posts = get_remaining_posts_count(); // Логика подсчета

    $status_icon = $is_running ? '<span class="dashicons dashicons-controls-play"></span>' : '<span class="dashicons dashicons-controls-pause"></span>';
    $count_badge = $is_running ? '<span class="ai-content-wizard-count-badge">' . intval( $remaining_posts ) . '</span>' : '';

    return $is_running ? $status_icon . ' ' . $count_badge : $status_icon;
}

function get_content_plan_status() {
    return wp_next_scheduled( 'ai_content_wizard_generate_post_event' ) !== false;
}

function get_remaining_posts_count() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ai_content_wizard_content_plan';
    $remaining_posts = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name WHERE status = 'Waiting'" );
    return $remaining_posts ? intval( $remaining_posts ) : 0;
}

function ai_content_wizard_add_create_post_submenu_correctly() {
    global $submenu;
    $api_key = ai_content_wizard_get_setting( 'ai_content_wizard_api_key' );
    $create_post_menu_slug = empty( $api_key ) ? 'ai_content_wizard_create_post_disabled' : 'ai_content_wizard_create_post';
    $menu_title = esc_html__( 'Create Post', 'ai-content-wizard' ) . ' <span class="ai-content-wizard-new-badge" style="background: #ffba00; color: #000; margin-left: 5px; padding: 0 5px;">AI</span>';

    if ( isset( $submenu['edit.php'] ) ) {
        $submenu_item = array(
            $menu_title,
            'edit_posts',
            empty( $api_key ) ? '' : esc_url( admin_url( 'admin.php?page=' . $create_post_menu_slug ) )
        );
        if ( empty( $api_key ) ) {
            $submenu_item[4] = 'ai-content-wizard-disabled';
        }
        array_splice( $submenu['edit.php'], 2, 0, array( $submenu_item ) );
    }
}
add_action( 'admin_menu', 'ai_content_wizard_add_create_post_submenu_correctly' );

function ai_content_wizard_add_custom_button_with_translation_and_access_check() {
    $current_screen = get_current_screen();
    $api_key = ai_content_wizard_get_setting( 'ai_content_wizard_api_key' );
    
    if ( 'edit-post' === $current_screen->id && current_user_can( 'manage_options' ) && ! empty( $api_key ) ) {
        $create_post_url = esc_url( admin_url( 'admin.php?page=ai_content_wizard_create_post' ) );
        ?>
		<script type="text/javascript">
			jQuery(document).ready(function($) {
				var customButtonHtml = '<a class="page-title-action ai-custom-create-post" href="<?php echo esc_url($create_post_url); ?>">' +
									   '<?php echo esc_html__( "Create Post", "ai-content-wizard" ); ?> <span class="ai-badge">AI</span>' +
									   '</a>';
				$(".wrap .page-title-action").last().after(customButtonHtml);
			});
		</script>

        <style>
            .ai-custom-create-post {
                background: linear-gradient(270deg, #32a852, #3294a8) !important;
                background-size: 400% 400% !important;
                animation: GradientAnimation 8s ease infinite !important;
                color: #ffffff !important;
                margin-left: 8px !important;
                transition: all 0.4s !important;
                border: none !important;
                text-shadow: none !important;
                font-weight: bold !important;
                padding: 0px 20px !important; 
                font-size: 16px !important; 
            }
            .ai-custom-create-post:hover {
                background: linear-gradient(270deg, #3294a8, #32a852) !important;
                box-shadow: 0 4px 8px rgba(50, 152, 88, 0.5) !important;
            }
            .ai-badge {
                background-color: #ffba00 !important;
                color: #000000 !important;
                font-size: 12px !important;
                padding: 2px 6px !important;
                margin-left: 6px !important;
                border-radius: 3px !important;
                vertical-align: middle !important;
            }
            @keyframes GradientAnimation {
                0% {background-position: 0% 50%;}
                50% {background-position: 100% 50%;}
                100% {background-position: 0% 50%;}
            }
        </style>
        <?php
    }
}
add_action( 'admin_head', 'ai_content_wizard_add_custom_button_with_translation_and_access_check' );

function ai_content_wizard_add_content_plan_button() {
    $current_screen = get_current_screen();
    $api_key = ai_content_wizard_get_setting( 'ai_content_wizard_api_key' );
    if ( 'edit-post' === $current_screen->id && current_user_can( 'manage_options' ) && ! empty( $api_key ) ) {
        $content_plan_status = ai_content_wizard_get_content_plan_status(); // Получаем статус (иконка + счетчик)
        // Здесь можно оставить URL пустым или сделать его неактивным
        $content_plan_url = '#';
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                var contentPlanButtonHtml = '<a class="page-title-action ai-custom-content-plan" href="<?php echo esc_url( $content_plan_url ); ?>" style="pointer-events: none; opacity: 0.5; cursor: not-allowed;">' +
                                            '<?php echo esc_html__( "Content Plan", "ai-content-wizard" ); ?> <span class="pro-badge">PRO</span>' +
                                            ' ' + '<?php echo wp_kses_post( $content_plan_status ); ?>' +
                                            '</a>';
                $(".wrap .page-title-action").last().after(contentPlanButtonHtml);
            });
        </script>
        <style>
            .ai-custom-content-plan {
                background: linear-gradient(270deg, #a83292, #a83260) !important;
                background-size: 400% 400% !important;
                animation: GradientAnimation 8s ease infinite !important;
                color: #ffffff !important;
                margin-left: 8px !important;
                transition: all 0.4s !important;
                border: none !important;
                text-shadow: none !important;
                font-weight: bold !important;
                padding: 0px 20px !important; 
                font-size: 16px !important;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .ai-custom-content-plan:hover {
                background: linear-gradient(270deg, #a83260, #a83292) !important;
                box-shadow: 0 4px 8px rgba(168, 50, 146, 0.5) !important;
            }
            .ai-content-wizard-count-badge {
                background-color: #ffba00 !important;
                color: #000000 !important;
                font-size: 12px !important;
                padding: 2px 6px !important;
                border-radius: 3px !important;
                vertical-align: middle !important;
                margin-left: 6px !important;
                line-height: normal !important;
            }
            @keyframes GradientAnimation {
                0% {background-position: 0% 50%;}
                50% {background-position: 100% 50%;}
                100% {background-position: 0% 50%;}
            }
        </style>
        <?php
    }
}
add_action( 'admin_head', 'ai_content_wizard_add_content_plan_button' );

function ai_content_wizard_seo_plugin_notice() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }
    $seo_fields = ai_content_wizard_check_seo_plugin();
    if ( empty( $seo_fields ) ) {
        $rank_math_install_url = esc_url( wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=seo-by-rank-math' ), 'install-plugin_seo-by-rank-math' ) );
        ?>
        <div style="padding: 15px; background: linear-gradient(90deg, rgba(255, 235, 59, 0.3) 0%, rgba(244, 67, 54, 0.3) 100%); background-size: 400% 400%; animation: GradientBG 5s ease infinite; display: flex; align-items: center; margin: 20px 0; border-radius: 8px; border: 1px solid #D32F2F; box-shadow: 0 5px 15px rgba(244, 67, 54, 0.2); max-width: 100%;">
            <div style="margin-right: 15px;">
                <svg width="24" height="24" style="vertical-align: middle;" fill="none" stroke="#D32F2F" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <path d="M12 2L2 7l10 5 10-5-10-5z"/>
                    <path d="M2 17l10 5 10-5"/>
                    <path d="M2 12l10 5 10-5"/>
                </svg>
            </div>
            <div style="flex-grow: 1;">
                <p style="font-size: 16px; line-height: 1.5; margin: 0; font-weight: 500; color: #333;">
                    <?php
                    // Разрешаем только теги <strong> в этом сообщении
                    echo wp_kses(
                        __( 'SEO Plugin is required for optimal performance. We highly recommend installing <strong>Rank Math</strong> for the best experience.', 'ai-content-wizard' ),
                        array( 'strong' => array() )
                    );
                    ?>
                    <a href="<?php echo esc_url( $rank_math_install_url ); ?>" style="color: #4A148C; text-decoration: underline; transition: color 0.3s; font-weight: bold;">
                        <?php echo esc_html__( 'Click here to install Rank Math.', 'ai-content-wizard' ); ?>
                    </a>
                </p>
            </div>
            <button type="button" class="notice-dismiss" style="position: absolute; top: 5px; right: 5px; border: none; background: transparent; padding: 5px; cursor: pointer; font-size: 16px; color: #D32F2F; transition: color 0.3s;">
                <span class="screen-reader-text"><?php echo esc_html__( 'Dismiss this notice', 'ai-content-wizard' ); ?></span>
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <style>
            @keyframes GradientBG {
                0% { background-position: 0% 50%; }
                50% { background-position: 100% 50%; }
                100% { background-position: 0% 50%; }
            }
            .notice-dismiss:hover {
                color: #B71C1C;
            }
            .notice-dismiss:focus {
                outline: none;
                box-shadow: 0 0 0 2px #D32F2F;
            }
            a:hover {
                color: #3A1070;
            }
        </style>
        <?php
    }
}
add_action( 'admin_notices', 'ai_content_wizard_seo_plugin_notice' );

