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

function podcastmaker_render_bulk_voice_page()
{
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('Permission denied.', 'quikvox-ai'));
    }
    if (!Podcastmaker_License::is_business()) {
        echo '<div class="wrap"><p>' . esc_html__('Bulk Voice Creation requires a Business plan.', 'quikvox-ai') . '</p></div>';
        return;
    }

    $categories = get_categories(array('hide_empty' => false));
    $authors    = get_users(array('capability' => 'edit_posts', 'fields' => array('ID', 'display_name')));

    $available_voices  = array('Aoede', 'Charon', 'Fenrir', 'Kore', 'Leda', 'Orus', 'Puck', 'Zephyr');
    $tts_models        = get_option('Podcastmaker_gemini_available_tts_models', array('gemini-2.5-flash-preview-tts', 'gemini-2.5-pro-preview-tts'));
    $default_tts_model = get_option('Podcastmaker_gemini_tts_model', 'gemini-2.5-flash-preview-tts');

    if (!class_exists('Podcastmaker_Prompt_Sets')) {
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-podcastmaker-prompt-sets.php';
    }
    $prompt_sets = (new Podcastmaker_Prompt_Sets())->get_all();

    if (!class_exists('Podcastmaker_Smart_Tone')) {
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-podcastmaker-smart-tone.php';
    }
    // Podcastmaker_Smart_Tone uses static get_styles(); each entry has 'id' and 'name' keys.
    $smart_tones = Podcastmaker_Smart_Tone::get_styles();

    $nonce = wp_create_nonce('podcastmaker_bulk_nonce');
    ?>
    <div class="wrap" id="podcastmaker-bulk-wrap">
        <h1><?php esc_html_e('一括音声作成', 'quikvox-ai'); ?> <span class="podcastmaker-plan-badge">BUSINESS</span></h1>

        <div class="notice notice-success podcastmaker-bulk-fix-notice">
            <p><?php echo esc_html__('v1.0.16 bug fix: Resolved an issue where Bulk Voice Creation could get stuck mid-queue on low-traffic sites. Processing is now driven from this page while it stays open, in addition to WP-Cron.', 'quikvox-ai'); ?></p>
        </div>

        <div class="podcastmaker-bulk-card">
            <div class="podcastmaker-bulk-card-header">
                <span class="podcastmaker-step-num">1</span>
                <h2><?php esc_html_e('対象投稿を絞り込む', 'quikvox-ai'); ?></h2>
            </div>
            <div class="podcastmaker-bulk-card-body">
                <div class="podcastmaker-bulk-filters">
                    <div class="podcastmaker-bulk-filter-group">
                        <label for="pm-bulk-category"><?php esc_html_e('カテゴリ', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-category">
                            <option value="0"><?php esc_html_e('すべてのカテゴリ', 'quikvox-ai'); ?></option>
                            <?php foreach ($categories as $cat) : ?>
                                <option value="<?php echo esc_attr($cat->term_id); ?>"><?php echo esc_html($cat->name); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="podcastmaker-bulk-filter-group">
                        <label for="pm-bulk-author"><?php esc_html_e('投稿者', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-author">
                            <option value="0"><?php esc_html_e('すべての投稿者', 'quikvox-ai'); ?></option>
                            <?php foreach ($authors as $author) : ?>
                                <option value="<?php echo esc_attr($author->ID); ?>"><?php echo esc_html($author->display_name); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="podcastmaker-bulk-filter-group">
                        <label for="pm-bulk-date-after"><?php esc_html_e('投稿日（開始）', 'quikvox-ai'); ?></label>
                        <input type="date" id="pm-bulk-date-after">
                    </div>
                    <div class="podcastmaker-bulk-filter-group">
                        <label for="pm-bulk-date-before"><?php esc_html_e('投稿日（終了）', 'quikvox-ai'); ?></label>
                        <input type="date" id="pm-bulk-date-before">
                    </div>
                    <div class="podcastmaker-bulk-filter-group">
                        <label><?php esc_html_e('音声未生成のみ', 'quikvox-ai'); ?></label>
                        <label class="podcastmaker-toggle">
                            <input type="checkbox" id="pm-bulk-no-audio" checked>
                            <span class="podcastmaker-toggle-slider"></span>
                        </label>
                    </div>
                    <div class="podcastmaker-bulk-filter-group podcastmaker-bulk-filter-group--search">
                        <button id="pm-bulk-search-btn" class="button button-secondary">
                            <?php esc_html_e('絞り込みを実行', 'quikvox-ai'); ?>
                        </button>
                        <span class="podcastmaker-count-badge" id="pm-bulk-count-badge" style="display:none;">
                            <strong id="pm-bulk-count">0</strong> <?php esc_html_e('件', 'quikvox-ai'); ?>
                        </span>
                    </div>
                </div>
                <p class="podcastmaker-bulk-note"><?php esc_html_e('※「音声未生成のみ」をONにすると、すでに音声ファイルが存在する投稿はスキップされます。', 'quikvox-ai'); ?></p>
            </div>
        </div>

        <div class="podcastmaker-bulk-card" id="pm-bulk-preview-card" style="display:none;">
            <div class="podcastmaker-bulk-card-header">
                <h2><?php esc_html_e('対象投稿一覧', 'quikvox-ai'); ?></h2>
            </div>
            <div class="podcastmaker-bulk-card-body">
                <div id="pm-bulk-preview-list"></div>
                <button id="pm-bulk-expand-btn" class="pm-expand-btn" style="display:none;"></button>
            </div>
        </div>

        <div class="podcastmaker-bulk-card">
            <div class="podcastmaker-bulk-card-header">
                <span class="podcastmaker-step-num">2</span>
                <h2><?php esc_html_e('音声設定（全投稿に一括適用）', 'quikvox-ai'); ?></h2>
            </div>
            <div class="podcastmaker-bulk-card-body">
                <div class="podcastmaker-bulk-voice-settings">
                    <div class="podcastmaker-bulk-form-group">
                        <label for="pm-bulk-language"><?php esc_html_e('言語', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-language">
                            <option value="ja"><?php esc_html_e('日本語', 'quikvox-ai'); ?></option>
                            <option value="en"><?php esc_html_e('英語', 'quikvox-ai'); ?></option>
                        </select>
                    </div>
                    <div class="podcastmaker-bulk-form-group">
                        <label for="pm-bulk-tts-model"><?php esc_html_e('TTSモデル', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-tts-model">
                            <?php foreach ($tts_models as $model) : ?>
                                <option value="<?php echo esc_attr($model); ?>" <?php selected($model, $default_tts_model); ?>><?php echo esc_html($model); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="podcastmaker-bulk-form-group">
                        <label for="pm-bulk-script-mode"><?php esc_html_e('スピーカータイプ', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-script-mode">
                            <option value="single"><?php esc_html_e('シングルスピーカー', 'quikvox-ai'); ?></option>
                            <option value="multi"><?php esc_html_e('マルチスピーカー', 'quikvox-ai'); ?></option>
                        </select>
                    </div>
                    <div class="podcastmaker-bulk-form-group" id="pm-bulk-voice-a-group">
                        <label id="pm-bulk-voice-a-label" for="pm-bulk-voice-id"><?php esc_html_e('ボイス', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-voice-id">
                            <?php foreach ($available_voices as $voice) : ?>
                                <option value="<?php echo esc_attr($voice); ?>"><?php echo esc_html($voice); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="podcastmaker-bulk-form-group" id="pm-bulk-voice-b-group" style="display:none;">
                        <label for="pm-bulk-voice-b-id"><?php esc_html_e('ボイスB（2人目）', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-voice-b-id">
                            <?php foreach ($available_voices as $voice) : ?>
                                <option value="<?php echo esc_attr($voice); ?>"><?php echo esc_html($voice); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="podcastmaker-bulk-form-group">
                        <label for="pm-bulk-prompt-id"><?php esc_html_e('プロンプトセット', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-prompt-id">
                            <option value=""><?php esc_html_e('デフォルト', 'quikvox-ai'); ?></option>
                            <?php foreach ($prompt_sets as $ps_id => $ps) : ?>
                                <option value="<?php echo esc_attr($ps_id); ?>"><?php echo esc_html($ps['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php if (!empty($smart_tones)) : ?>
                    <div class="podcastmaker-bulk-form-group">
                        <label for="pm-bulk-smart-tone-id"><?php esc_html_e('スタイル（Smart Tone）', 'quikvox-ai'); ?></label>
                        <select id="pm-bulk-smart-tone-id">
                            <option value=""><?php esc_html_e('なし', 'quikvox-ai'); ?></option>
                            <?php foreach ($smart_tones as $st) : ?>
                                <option value="<?php echo esc_attr($st['id']); ?>"><?php echo esc_html($st['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php else : ?>
                    <input type="hidden" id="pm-bulk-smart-tone-id" value="">
                    <?php endif; ?>
                </div>
            </div>
            <div class="podcastmaker-bulk-action-area">
                <button id="pm-bulk-start-btn" class="button button-primary button-large" disabled>
                    <?php esc_html_e('キューに追加して生成開始', 'quikvox-ai'); ?>
                </button>
                <span class="podcastmaker-bulk-note"><?php esc_html_e('処理中はページを閉じても続きます', 'quikvox-ai'); ?></span>
            </div>
        </div>

        <div class="podcastmaker-bulk-card podcastmaker-bulk-cron-tip">
            <details>
                <summary><?php echo esc_html__('For more reliable processing (optional, for advanced users)', 'quikvox-ai'); ?></summary>
                <div class="podcastmaker-bulk-card-body">
                    <p><?php echo esc_html__('Bulk voice generation runs on WordPress\'s built-in scheduling system (WP-Cron). On sites with low traffic, this can cause delays in processing. For more reliable execution, add the following command to your server\'s system cron (requires server administrator access):', 'quikvox-ai'); ?></p>
                    <pre class="podcastmaker-bulk-cron-code">*/5 * * * * cd /path/to/wordpress && wp cron event run --due-now --quiet</pre>
                    <p class="podcastmaker-bulk-note"><?php echo esc_html__('Replace /path/to/wordpress with the actual WordPress installation path on your server. You can usually add this via your hosting provider\'s "Cron Jobs" panel, or by running crontab -e via SSH. This step is optional — processing will continue automatically while this page remains open.', 'quikvox-ai'); ?></p>
                </div>
            </details>
        </div>

        <div class="podcastmaker-bulk-card" id="pm-bulk-progress-card" style="display:none;">
            <div class="podcastmaker-bulk-card-header">
                <span class="podcastmaker-step-num">3</span>
                <h2><?php esc_html_e('処理状況', 'quikvox-ai'); ?></h2>
            </div>
            <div class="podcastmaker-bulk-card-body">
                <div class="podcastmaker-bulk-progress-header">
                    <span id="pm-bulk-progress-text"></span>
                    <span id="pm-bulk-started-at"></span>
                </div>
                <div class="podcastmaker-bulk-bar-wrap">
                    <div class="podcastmaker-bulk-bar" id="pm-bulk-bar" style="width:0%"></div>
                </div>
                <div class="podcastmaker-bulk-stats">
                    <div class="podcastmaker-bulk-stat">
                        <span class="podcastmaker-bulk-stat-val success" id="pm-bulk-stat-success">0</span>
                        <span class="podcastmaker-bulk-stat-label"><?php esc_html_e('成功', 'quikvox-ai'); ?></span>
                    </div>
                    <div class="podcastmaker-bulk-stat">
                        <span class="podcastmaker-bulk-stat-val fail" id="pm-bulk-stat-failed">0</span>
                        <span class="podcastmaker-bulk-stat-label"><?php esc_html_e('失敗', 'quikvox-ai'); ?></span>
                    </div>
                    <div class="podcastmaker-bulk-stat">
                        <span class="podcastmaker-bulk-stat-val pending" id="pm-bulk-stat-pending">0</span>
                        <span class="podcastmaker-bulk-stat-label"><?php esc_html_e('待機中', 'quikvox-ai'); ?></span>
                    </div>
                </div>
                <div id="pm-bulk-processing-item" class="podcastmaker-bulk-processing-item" style="display:none;"></div>
                <table class="wp-list-table widefat fixed striped" id="pm-bulk-results-table">
                    <thead>
                        <tr>
                            <th style="width:40px;">#</th>
                            <th><?php esc_html_e('投稿タイトル', 'quikvox-ai'); ?></th>
                            <th style="width:120px;"><?php esc_html_e('ステータス', 'quikvox-ai'); ?></th>
                            <th style="width:80px;"><?php esc_html_e('処理時間', 'quikvox-ai'); ?></th>
                            <th style="width:80px;"><?php esc_html_e('操作', 'quikvox-ai'); ?></th>
                        </tr>
                    </thead>
                    <tbody id="pm-bulk-results-tbody"></tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
    var podcastmakerBulk = {
        nonce: '<?php echo esc_js($nonce); ?>',
        ajaxUrl: '<?php echo esc_js(admin_url('admin-ajax.php')); ?>'
    };
    </script>
    <?php
}
