<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * 管理画面の RSS フィード機能。
 *
 * RSS フィードタブの描画と、フィードの保存/削除/有効切替/接続テスト/履歴削除を
 * 担う独立した機能モジュール。AIAP_Admin の他ロジックには依存せず、共有するのは
 * メニュースラッグとnonceアクション名の 2 定数のみ (AIAP_Admin::MENU_SLUG /
 * AIAP_Admin::NONCE を明示参照)。肥大化した AIAP_Admin からの切り出し (Phase 3 ステップ2)。
 *
 * フック登録 (admin_post_* / wp_ajax_*) は AIAP_Admin::init() が行い、本クラスの
 * メソッドをコールバックに指定する。タブ描画は AIAP_Admin_View::render_page() から呼ばれる。
 */
class AIAP_Admin_RSS {

    /**
     * RSS フィードタブのレンダリング
     */
    public static function render_rss_feeds() {
        $is_pro = class_exists( 'AIAP_License' ) && AIAP_License::is_pro();
        $feeds  = AIAP_RSS_Feeds::get_all();
        $not_set_label    = __( 'Not set', 'ai-auto-poster' );
        $configured_label = __( 'Configured', 'ai-auto-poster' );
        ?>
        <div class="aiap-card aiap-rss-tab">
            <header class="aiap-provider-hero">
                <span class="aiap-provider-hero-eyebrow"><?php echo esc_html__( 'RSS Feeds', 'ai-auto-poster' ); ?></span>
                <h2 class="aiap-provider-hero-title"><?php echo esc_html__( 'Which news feeds should we read?', 'ai-auto-poster' ); ?></h2>
                <p class="aiap-provider-hero-sub"><?php echo esc_html__( 'Use news RSS as source material for AI generation.', 'ai-auto-poster' ); ?></p>
            </header>

            <?php if ( ! $is_pro ) : ?>
                <div class="aiap-pro-upsell">
                    <p><strong><?php echo esc_html__( 'This is a Pro feature.', 'ai-auto-poster' ); ?></strong></p>
                </div>
            <?php endif; ?>

            <fieldset class="aiap-rss-fieldset" <?php echo $is_pro ? '' : 'disabled'; ?>>
                <div class="aiap-provider-section-label"><?php echo esc_html__( 'Add Feed', 'ai-auto-poster' ); ?></div>
                <div class="aiap-rss-add-card">
                    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-rss-feed-form">
                        <?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
                        <input type="hidden" name="action" value="aiap_save_rss_feed" />
                        <input type="hidden" name="aiap_rss_op" value="add" />
                        <div class="aiap-rss-add-grid">
                            <div class="aiap-rss-add-field">
                                <label class="aiap-rss-add-label"><?php echo esc_html__( 'Display Name', 'ai-auto-poster' ); ?></label>
                                <input type="text" name="name" class="aiap-input-text" placeholder="<?php echo esc_attr__( 'e.g. TechCrunch JP', 'ai-auto-poster' ); ?>" required />
                            </div>
                            <div class="aiap-rss-add-field">
                                <label class="aiap-rss-add-label"><?php echo esc_html__( 'RSS URL', 'ai-auto-poster' ); ?></label>
                                <input type="url" name="url" class="aiap-input-text" placeholder="https://example.com/feed.xml" required />
                            </div>
                        </div>
                        <div class="aiap-rss-add-row">
                            <label class="aiap-rss-add-toggle">
                                <input type="checkbox" name="enabled" value="1" checked />
                                <span><?php echo esc_html__( 'Enabled', 'ai-auto-poster' ); ?></span>
                            </label>
                            <div class="aiap-rss-add-actions">
                                <button type="button" class="button js-aiap-rss-test"><?php echo esc_html__( 'Test Connection', 'ai-auto-poster' ); ?></button>
                                <button type="submit" class="button button-primary"><?php echo esc_html__( 'Add Feed', 'ai-auto-poster' ); ?></button>
                            </div>
                        </div>
                        <span class="aiap-rss-test-result" aria-live="polite"></span>
                    </form>
                </div>

                <div class="aiap-provider-section-label"><?php echo esc_html__( 'Registered Feeds', 'ai-auto-poster' ); ?></div>
                <?php if ( empty( $feeds ) ) : ?>
                    <p class="aiap-rss-empty-state"><?php echo esc_html__( 'No feeds registered yet.', 'ai-auto-poster' ); ?></p>
                <?php else : ?>
                    <div class="aiap-rss-feed-list">
                    <?php foreach ( $feeds as $feed ) :
                        $feed_id      = isset( $feed['id'] )      ? $feed['id']      : '';
                        $name         = isset( $feed['name'] )    ? $feed['name']    : '';
                        $url          = isset( $feed['url'] )     ? $feed['url']     : '';
                        $enabled      = ! empty( $feed['enabled'] );
                        $last_fetched = isset( $feed['last_fetched_at'] ) ? $feed['last_fetched_at'] : '';
                        $last_error   = isset( $feed['last_error'] )      ? $feed['last_error']      : '';
                        $used_count   = AIAP_RSS_State::count_used( $feed_id );
                    ?>
                        <div class="aiap-rss-feed-card<?php echo $enabled ? ' is-enabled' : ' is-disabled'; ?>" data-feed-id="<?php echo esc_attr( $feed_id ); ?>">
                            <div class="aiap-rss-feed-card-head">
                                <span class="aiap-rss-feed-icon dashicons dashicons-rss" aria-hidden="true"></span>
                                <div class="aiap-rss-feed-titlebox">
                                    <strong class="aiap-rss-feed-name"><?php echo esc_html( $name ); ?></strong>
                                    <span class="aiap-rss-feed-url"><?php echo esc_html( $url ); ?></span>
                                </div>
                                <span class="aiap-provider-tile-status<?php echo $enabled ? ' is-configured' : ' is-empty'; ?>" aria-label="<?php echo esc_attr( $enabled ? $configured_label : $not_set_label ); ?>">
                                    <?php echo esc_html( $enabled ? $configured_label : $not_set_label ); ?>
                                </span>
                                <label class="aiap-toggle-switch" title="<?php echo esc_attr__( 'Enabled', 'ai-auto-poster' ); ?>" aria-label="<?php echo esc_attr__( 'Enabled', 'ai-auto-poster' ); ?>">
                                    <input type="checkbox" class="js-aiap-rss-toggle-enabled" <?php checked( $enabled ); ?> />
                                    <span class="aiap-toggle-slider"></span>
                                </label>
                            </div>
                            <div class="aiap-rss-feed-card-body">
                                <div class="aiap-rss-feed-meta">
                                    <span class="aiap-rss-feed-meta-item">
                                        <span class="aiap-rss-feed-meta-label"><?php echo esc_html__( 'Last fetched', 'ai-auto-poster' ); ?></span>
                                        <span class="aiap-rss-feed-meta-value"><?php echo esc_html( $last_fetched !== '' ? $last_fetched : '—' ); ?></span>
                                    </span>
                                    <span class="aiap-rss-feed-meta-item">
                                        <span class="aiap-rss-feed-meta-label"><?php echo esc_html__( 'Used', 'ai-auto-poster' ); ?></span>
                                        <span class="aiap-rss-feed-meta-value"><?php
                                            /* translators: 1: used count, 2: limit */
                                            echo esc_html( sprintf( __( '%1$d / %2$d', 'ai-auto-poster' ), $used_count, AIAP_RSS_State::HISTORY_PER_FEED ) );
                                        ?></span>
                                    </span>
                                    <?php if ( $last_error !== '' ) : ?>
                                        <span class="aiap-rss-feed-meta-item aiap-rss-feed-meta-item-error">
                                            <span class="aiap-rss-feed-meta-label"><?php echo esc_html__( 'Last error', 'ai-auto-poster' ); ?></span>
                                            <span class="aiap-rss-feed-meta-value"><?php echo esc_html( $last_error ); ?></span>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <div class="aiap-rss-feed-actions">
                                    <button type="button" class="aiap-btn aiap-btn-icon-only js-aiap-rss-edit" title="<?php echo esc_attr__( 'Edit', 'ai-auto-poster' ); ?>" aria-label="<?php echo esc_attr__( 'Edit', 'ai-auto-poster' ); ?>">
                                        <span class="dashicons dashicons-edit" aria-hidden="true"></span>
                                    </button>
                                    <button type="button" class="aiap-btn aiap-btn-icon-only js-aiap-rss-test" data-url="<?php echo esc_attr( $url ); ?>" title="<?php echo esc_attr__( 'Test Connection', 'ai-auto-poster' ); ?>" aria-label="<?php echo esc_attr__( 'Test Connection', 'ai-auto-poster' ); ?>">
                                        <span class="dashicons dashicons-update" aria-hidden="true"></span>
                                    </button>
                                    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-rss-inline-form">
                                        <?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
                                        <input type="hidden" name="action" value="aiap_delete_rss_feed" />
                                        <input type="hidden" name="feed_id" value="<?php echo esc_attr( $feed_id ); ?>" />
                                        <button type="submit" class="aiap-btn aiap-btn-icon-only aiap-btn-danger-icon js-aiap-rss-delete-confirm" title="<?php echo esc_attr__( 'Delete', 'ai-auto-poster' ); ?>" aria-label="<?php echo esc_attr__( 'Delete', 'ai-auto-poster' ); ?>">
                                            <span class="dashicons dashicons-trash" aria-hidden="true"></span>
                                        </button>
                                    </form>
                                </div>
                                <span class="aiap-rss-test-result" aria-live="polite"></span>
                            </div>
                            <!--
                                編集フォーム: 初期は hidden、.js-aiap-rss-edit クリックで
                                親カードに .is-editing が付与され、CSS で表示／既存ビュー(head/body)を非表示にする。
                                送信は通常の POST → handle_save_rss_feed (op=update) → リダイレクト。
                            -->
                            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="aiap-rss-feed-edit-form aiap-rss-feed-form">
                                <?php wp_nonce_field( AIAP_Admin::NONCE ); ?>
                                <input type="hidden" name="action" value="aiap_save_rss_feed" />
                                <input type="hidden" name="aiap_rss_op" value="update" />
                                <input type="hidden" name="feed_id" value="<?php echo esc_attr( $feed_id ); ?>" />
                                <div class="aiap-rss-add-grid">
                                    <div class="aiap-rss-add-field">
                                        <label class="aiap-rss-add-label"><?php echo esc_html__( 'Display Name', 'ai-auto-poster' ); ?></label>
                                        <input type="text" name="name" class="aiap-input-text" value="<?php echo esc_attr( $name ); ?>" required />
                                    </div>
                                    <div class="aiap-rss-add-field">
                                        <label class="aiap-rss-add-label"><?php echo esc_html__( 'RSS URL', 'ai-auto-poster' ); ?></label>
                                        <input type="url" name="url" class="aiap-input-text" value="<?php echo esc_attr( $url ); ?>" required />
                                    </div>
                                </div>
                                <div class="aiap-rss-add-row">
                                    <label class="aiap-rss-add-toggle">
                                        <input type="checkbox" name="enabled" value="1" <?php checked( $enabled ); ?> />
                                        <span><?php echo esc_html__( 'Enabled', 'ai-auto-poster' ); ?></span>
                                    </label>
                                    <div class="aiap-rss-add-actions">
                                        <button type="button" class="button js-aiap-rss-edit-cancel"><?php echo esc_html__( 'Cancel', 'ai-auto-poster' ); ?></button>
                                        <button type="submit" class="button button-primary"><?php echo esc_html__( 'Save', 'ai-auto-poster' ); ?></button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </fieldset>
        </div>
        <?php
    }

    // ================================================================
    // RSS フィード AJAX / admin-post ハンドラ
    // ================================================================

    /**
     * RSS フィードの追加・編集
     */
    public static function handle_save_rss_feed() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Insufficient permissions.', 'ai-auto-poster' ) );
        }
        check_admin_referer( AIAP_Admin::NONCE );
        if ( ! class_exists( 'AIAP_License' ) || ! AIAP_License::is_pro() ) {
            wp_die( esc_html__( 'This is a Pro feature.', 'ai-auto-poster' ) );
        }
        $op = isset( $_POST['aiap_rss_op'] ) ? sanitize_key( wp_unslash( $_POST['aiap_rss_op'] ) ) : 'add';
        $name    = isset( $_POST['name'] )    ? sanitize_text_field( wp_unslash( $_POST['name'] ) )    : '';
        $url     = isset( $_POST['url'] )     ? esc_url_raw( wp_unslash( $_POST['url'] ) )             : '';
        $enabled = ! empty( $_POST['enabled'] ) ? 1 : 0;

        if ( $op === 'add' ) {
            $result = AIAP_RSS_Feeds::add( array(
                'name'    => $name,
                'url'     => $url,
                'enabled' => $enabled,
            ) );
            if ( is_wp_error( $result ) ) {
                $back = add_query_arg( array(
                    'page'              => AIAP_Admin::MENU_SLUG,
                    'tab'               => 'rss_feeds',
                    'aiap_rss_error'    => rawurlencode( $result->get_error_message() ),
                ), admin_url( 'admin.php' ) );
                wp_safe_redirect( $back );
                exit;
            }
        } elseif ( $op === 'update' ) {
            $feed_id = isset( $_POST['feed_id'] ) ? sanitize_key( wp_unslash( $_POST['feed_id'] ) ) : '';
            $result  = AIAP_RSS_Feeds::update( $feed_id, array(
                'name'    => $name,
                'url'     => $url,
                'enabled' => $enabled,
            ) );
            if ( is_wp_error( $result ) ) {
                $back = add_query_arg( array(
                    'page'              => AIAP_Admin::MENU_SLUG,
                    'tab'               => 'rss_feeds',
                    'aiap_rss_error'    => rawurlencode( $result->get_error_message() ),
                ), admin_url( 'admin.php' ) );
                wp_safe_redirect( $back );
                exit;
            }
        }

        wp_safe_redirect( admin_url( 'admin.php?page=' . AIAP_Admin::MENU_SLUG . '&tab=rss_feeds' ) );
        exit;
    }

    /**
     * RSS フィードの削除（履歴も連動削除）
     */
    public static function handle_delete_rss_feed() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Insufficient permissions.', 'ai-auto-poster' ) );
        }
        check_admin_referer( AIAP_Admin::NONCE );
        if ( ! class_exists( 'AIAP_License' ) || ! AIAP_License::is_pro() ) {
            wp_die( esc_html__( 'This is a Pro feature.', 'ai-auto-poster' ) );
        }
        $feed_id = isset( $_POST['feed_id'] ) ? sanitize_key( wp_unslash( $_POST['feed_id'] ) ) : '';

        // 削除結果はリダイレクト先でエラー処理する余地があるが、現状はログを残さずに一覧へ戻す。
        // 設定変更系の操作ログは実行ログのスコープ外のため出力しない。
        AIAP_RSS_Feeds::delete( $feed_id );
        wp_safe_redirect( admin_url( 'admin.php?page=' . AIAP_Admin::MENU_SLUG . '&tab=rss_feeds' ) );
        exit;
    }

    /**
     * RSS フィードの有効/無効トグル
     */
    public static function ajax_rss_toggle_enabled() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-auto-poster' ) ) );
        }
        check_ajax_referer( AIAP_Admin::NONCE );
        if ( ! class_exists( 'AIAP_License' ) || ! AIAP_License::is_pro() ) {
            wp_send_json_error( array( 'message' => __( 'This is a Pro feature.', 'ai-auto-poster' ) ) );
        }
        $feed_id = isset( $_POST['feed_id'] ) ? sanitize_key( wp_unslash( $_POST['feed_id'] ) ) : '';
        $enabled = ! empty( $_POST['enabled'] ) ? 1 : 0;

        $result = AIAP_RSS_Feeds::update( $feed_id, array( 'enabled' => $enabled ) );
        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
        }
        wp_send_json_success( array( 'enabled' => $enabled ) );
    }

    /**
     * RSS フィード接続テスト
     */
    public static function ajax_test_rss_feed() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-auto-poster' ) ) );
        }
        check_ajax_referer( AIAP_Admin::NONCE );
        if ( ! class_exists( 'AIAP_License' ) || ! AIAP_License::is_pro() ) {
            wp_send_json_error( array( 'message' => __( 'This is a Pro feature.', 'ai-auto-poster' ) ) );
        }
        $url = isset( $_POST['url'] ) ? esc_url_raw( wp_unslash( $_POST['url'] ) ) : '';
        $result = AIAP_RSS_Feeds::test_connection( $url );
        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array(
                'message' => sprintf(
                    /* translators: %s = error message */
                    __( 'Connection failed: %s', 'ai-auto-poster' ),
                    $result->get_error_message()
                ),
            ) );
        }
        wp_send_json_success( array(
            'message' => sprintf(
                /* translators: %d = item count */
                __( 'Connection successful: %d items found', 'ai-auto-poster' ),
                (int) $result['item_count']
            ),
            'sample'  => $result['sample_title'],
        ) );
    }

    /**
     * RSS 履歴のみ削除（フィード自体は残す）
     */
    public static function ajax_rss_purge_history() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-auto-poster' ) ) );
        }
        check_ajax_referer( AIAP_Admin::NONCE );
        if ( ! class_exists( 'AIAP_License' ) || ! AIAP_License::is_pro() ) {
            wp_send_json_error( array( 'message' => __( 'This is a Pro feature.', 'ai-auto-poster' ) ) );
        }
        $feed_id = isset( $_POST['feed_id'] ) ? sanitize_key( wp_unslash( $_POST['feed_id'] ) ) : '';
        $feed    = AIAP_RSS_Feeds::get_by_id( $feed_id );
        if ( ! $feed ) {
            wp_send_json_error( array( 'message' => __( 'Feed not found.', 'ai-auto-poster' ) ) );
        }
        // 設定変更系の操作ログは実行ログのスコープ外のため、ログには出力しない。
        $purged = AIAP_RSS_State::purge_feed( $feed_id );
        wp_send_json_success( array( 'purged' => $purged ) );
    }
}
