<?php

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



/**

 * ログ + 実行ログタブ のレンダリング

 *

 * 元 admin/class-aiap-admin-view.php から分離。

 * 共通基盤 (resolve_dynamic_key, log_message 等) は親クラス AIAP_Admin_View にあるため直接参照する。

 */

class AIAP_Admin_View_Logs {



    public static function render_logs() {

        // 旧「実行ログ(テキスト)」表示は WP_List_Table ベースの「生成投稿一覧」に置き換え。

        // 既存の AIAP_Logger は内部記録用としてはそのまま残す(エラー解析や cron 監視で使うため)が、

        // 管理画面 UI からは AI 生成された投稿の一覧 + 編集 / 削除アクションを提供する。



        // 一括削除アクションの処理 (WP_List_Table の bulk action)

        if ( isset( $_REQUEST['action'] ) || isset( $_REQUEST['action2'] ) ) {

            AIAP_Admin::handle_generated_posts_bulk_action();

        }



        if ( ! class_exists( 'AIAP_Generated_Posts_Table' ) ) {

            require_once AIAP_PLUGIN_DIR . 'admin/class-aiap-generated-posts-table.php';

        }

        $table = new AIAP_Generated_Posts_Table();

        $table->prepare_items();

        $total = isset( $table->_pagination_args['total_items'] ) ? (int) $table->_pagination_args['total_items'] : 0;



        // Free プランの月次スキップ件数(実行ログ機能から流用): 上限到達時の警告は維持する。

        $skip_count_this_month = 0;

        if ( ! AIAP_License::is_pro() ) {

            $logs = AIAP_Logger::get_all();

            $current_month = wp_date( 'Y-m' );

            foreach ( $logs as $log ) {

                $key = $log['message_key'] ?? '';

                if ( $key !== 'log_free_limit_reached_skip_cron' ) continue;

                $log_time = (string) ( $log['time'] ?? '' );

                if ( $log_time === '' ) continue;

                if ( substr( $log_time, 0, 7 ) === $current_month ) $skip_count_this_month++;

            }

        }

        ?>

        <header class="aiap-provider-hero">

            <?php /* Phase 12: 旧版は「History / Generation history / Generated posts」と

                   3 つの異なる訳語が同じ画面内に混在していた。すべて「Post history / 投稿履歴」に統一。 */ ?>

            <span class="aiap-provider-hero-eyebrow"><?php echo esc_html( __( 'Post history', 'ai-auto-poster' ) ); ?></span>

            <h2 class="aiap-provider-hero-title"><?php echo esc_html( __( 'Post history', 'ai-auto-poster' ) ); ?></h2>

            <p class="aiap-provider-hero-sub"><?php echo esc_html( __( 'Posts created by this plugin. View or edit from here.', 'ai-auto-poster' ) ); ?></p>

        </header>



        <?php if ( $skip_count_this_month > 0 ) : ?>

            <div class="aiap-banner aiap-banner-warning">

                <span class="dashicons dashicons-warning" aria-hidden="true"></span>

                <span class="aiap-banner-text">

                    <strong><?php

                        /* translators: %d = number of times cron was skipped this month due to free plan limit */

                        echo esc_html( sprintf( _n( 'This month: %d cron run skipped due to monthly limit.', 'This month: %d cron runs skipped due to monthly limit.', $skip_count_this_month, 'ai-auto-poster' ), $skip_count_this_month ) );

                    ?></strong>

                </span>

                <a href="<?php echo esc_url( AIAP_License::upgrade_url() ); ?>" class="aiap-banner-cta">

                    <span class="dashicons dashicons-star-filled" aria-hidden="true"></span>

                    <?php echo esc_html( __( 'Upgrade', 'ai-auto-poster' ) ); ?>

                </a>

            </div>

        <?php endif; ?>



        <div class="aiap-section aiap-logs-table-section">

            <div class="aiap-section-header">

                <?php /* Phase 12: section title「Generated posts」は hero と統一して削除。カウントだけ残す。 */ ?>

                <div class="aiap-section-title-row">

                    <span class="aiap-section-count">

                        <?php

                        /* translators: %d: number of posts */

                        if ( $total > 100 ) {

                            /* translators: %d: total number of posts */

                            printf( esc_html__( 'Showing latest 100 of %d posts.', 'ai-auto-poster' ), (int) $total );

                        } else {

                            /* translators: %d: number of posts */

                            printf( esc_html__( 'Posts: %d', 'ai-auto-poster' ), (int) $total );

                        }

                        ?>

                    </span>

                </div>

            </div>

            <div class="aiap-section-body">

                <form method="get">

                    <?php

                    // ページ情報を維持するため page パラメータを引き継ぐ

                    if ( isset( $_REQUEST['page'] ) ) {

                        printf( '<input type="hidden" name="page" value="%s" />', esc_attr( sanitize_key( wp_unslash( $_REQUEST['page'] ) ) ) );

                    }

                    if ( isset( $_REQUEST['tab'] ) ) {

                        printf( '<input type="hidden" name="tab" value="%s" />', esc_attr( sanitize_key( wp_unslash( $_REQUEST['tab'] ) ) ) );

                    }

                    wp_nonce_field( AIAP_Admin::NONCE );

                    $table->display();

                    ?>

                </form>

            </div>

        </div>

        <?php

    }



    // ================================================================

    // 実行ログ (Server-side execution log; AIAP_Logger の中身を表示)

    // ================================================================

    public static function render_run_logs() {

        $logs  = AIAP_Logger::get_all();

        $count = is_array( $logs ) ? count( $logs ) : 0;



        // ステータス → 表示ラベル + バッジ用クラス

        $status_meta = array(

            'success' => array( 'label' => __( 'Success', 'ai-auto-poster' ), 'class' => 'is-success' ),

            'error'   => array( 'label' => __( 'Error',   'ai-auto-poster' ), 'class' => 'is-error'   ),

            'info'    => array( 'label' => __( 'Info',    'ai-auto-poster' ), 'class' => 'is-info'    ),

            'warning' => array( 'label' => __( 'Warning', 'ai-auto-poster' ), 'class' => 'is-warning' ),

        );



        $clear_url = wp_nonce_url(

            add_query_arg(

                array( 'action' => 'aiap_clear_logs' ),

                admin_url( 'admin-post.php' )

            ),

            AIAP_Admin::NONCE

        );

        ?>

        <header class="aiap-provider-hero">

            <span class="aiap-provider-hero-eyebrow"><?php echo esc_html( __( 'Diagnostics', 'ai-auto-poster' ) ); ?></span>

            <h2 class="aiap-provider-hero-title"><?php echo esc_html( __( 'Execution log', 'ai-auto-poster' ) ); ?></h2>

            <p class="aiap-provider-hero-sub"><?php echo esc_html( __( 'Server-side execution log for cron runs, generation requests, and errors. Entries older than 7 days are automatically removed.', 'ai-auto-poster' ) ); ?></p>

        </header>



        <div class="aiap-section aiap-run-logs-section">

            <div class="aiap-section-header">

                <?php /* Phase 12: section title「Execution log」は hero title と完全に重複していたので削除。

                       カウントバッジと Clear ボタンだけ残す。 */ ?>

                <div class="aiap-section-title-row">

                    <span class="aiap-section-count"><?php echo esc_html( (string) $count ); ?></span>

                </div>

                <?php if ( $count > 0 ) : ?>

                <div class="aiap-section-actions">

                    <a href="<?php echo esc_url( $clear_url ); ?>"

                       class="button button-secondary aiap-btn-danger-outline js-confirm-clear-logs"

                       data-confirm-message="<?php echo esc_attr( __( 'Clear all execution log entries? This cannot be undone.', 'ai-auto-poster' ) ); ?>">

                        <span class="dashicons dashicons-trash" aria-hidden="true"></span>

                        <?php echo esc_html( __( 'Clear log', 'ai-auto-poster' ) ); ?>

                    </a>

                </div>

                <?php endif; ?>

            </div>

            <div class="aiap-section-body">

                <?php if ( $count === 0 ) : ?>

                    <p class="aiap-run-logs-empty"><?php echo esc_html( __( 'No execution log entries yet.', 'ai-auto-poster' ) ); ?></p>

                <?php else : ?>

                    <ul class="aiap-run-logs-list">

                        <?php foreach ( $logs as $log ) :

                            if ( ! is_array( $log ) ) continue;



                            $status   = isset( $log['status'] ) ? (string) $log['status'] : 'info';

                            $meta     = isset( $status_meta[ $status ] ) ? $status_meta[ $status ] : array(

                                'label' => $status,

                                'class' => 'is-info',

                            );

                            $time_str = isset( $log['time'] ) ? (string) $log['time'] : '';

                            $message  = AIAP_Admin_View::log_message( $log );

                        ?>

                        <li class="aiap-run-logs-item <?php echo esc_attr( $meta['class'] ); ?>">

                            <div class="aiap-run-logs-meta">

                                <span class="aiap-run-logs-badge"><?php echo esc_html( $meta['label'] ); ?></span>

                                <span class="aiap-run-logs-time"><?php echo esc_html( $time_str ); ?></span>

                            </div>

                            <div class="aiap-run-logs-msg"><?php echo esc_html( $message ); ?></div>

                            <?php if ( ! empty( $log['context'] ) && is_array( $log['context'] ) ) : ?>

                                <details class="aiap-run-logs-context">

                                    <summary><?php echo esc_html( __( 'Details', 'ai-auto-poster' ) ); ?></summary>

                                    <?php foreach ( $log['context'] as $ctx_key => $ctx_val ) : ?>

                                        <div class="aiap-run-logs-context-row">

                                            <span class="aiap-run-logs-context-key"><?php echo esc_html( AIAP_Admin_View::translate_context_key( (string) $ctx_key ) ); ?>:</span>

                                            <pre class="aiap-run-logs-context-val"><?php echo esc_html( is_scalar( $ctx_val ) ? (string) $ctx_val : wp_json_encode( $ctx_val, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ); ?></pre>

                                        </div>

                                    <?php endforeach; ?>

                                </details>

                            <?php endif; ?>

                        </li>

                        <?php endforeach; ?>

                    </ul>

                <?php endif; ?>

            </div>

        </div>

        <?php

    }



}

