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

/**
 * 管理画面の静的コンテンツページ (FAQ / 利用規約)。
 *
 * いずれも AI Auto Poster のメイン管理画面とは独立したサブメニューページで、
 * ハードコードされたコンテンツを描画するだけ。状態を一切持たず他の管理ロジックに
 * 依存しないため、肥大化した AIAP_Admin から最初に切り出した (Phase 3 ステップ1)。
 *
 * メニュー登録は AIAP_Admin::register_menu() が行い、本クラスの
 * render_faq_page / render_terms_page をページコールバックとして指定する。
 */
class AIAP_Admin_Pages {

    /**
     * FAQサブメニューを表示する
     *
     * FAQ本文は WordPress 標準の gettext 翻訳(.po/.mo)で管理する。
     * PHP内には英語の msgid のみを置き、日本語は languages/*.po/*.mo に分離する。
     */
    public static function render_faq_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $sections = self::get_faq_items();
        ?>
        <div class="wrap aiap-wrap aiap-faq-wrap">
            <div class="aiap-page-head">
                <h1 class="aiap-page-title"><?php echo esc_html( __( 'FAQ', 'ai-auto-poster' ) ); ?></h1>
            </div>
            <div class="aiap-card aiap-card-accent">
                <p class="description"><?php echo esc_html( __( 'Find answers about plans, API keys, article generation, scheduling, retry behavior, images, SEO, logs, and data handling.', 'ai-auto-poster' ) ); ?></p>
            </div>
            <?php foreach ( $sections as $section ) : ?>
                <div class="aiap-card aiap-faq-section">
                    <h2 class="aiap-faq-section-title"><?php echo esc_html( $section['title'] ); ?></h2>
                    <div class="aiap-faq-list">
                        <?php foreach ( $section['items'] as $item ) : ?>
                            <details class="aiap-faq-item">
                                <summary><?php echo esc_html( $item['question'] ); ?></summary>
                                <p><?php echo esc_html( $item['answer'] ); ?></p>
                            </details>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
    }

    /**
     * FAQ項目を返す
     *
     * @return array<int,array{title:string,items:array<int,array{question:string,answer:string}>}>
     */
    private static function get_faq_items() {
        return array(

            // ========================================
            // 1. Getting started
            // ========================================
            array(
                'title' => __( 'Getting started', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'What is the minimum setup to publish my first article?', 'ai-auto-poster' ),
                        'answer'   => __( 'Three steps: (1) Open the Providers tab and save an API key for one text AI provider. (2) Open the Tasks tab and create a task with a prompt. (3) Click Quick Post to generate immediately, or wait for the scheduled time. We recommend keeping the post status as Draft for the first few articles so you can review them before publishing.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Which AI provider should I choose first?', 'ai-auto-poster' ),
                        'answer'   => __( 'If you are not sure, Gemini Flash and Groq are good starting points because they offer free tiers and very low per-article cost. For higher article quality, Claude (Anthropic) and GPT-4 class models from OpenAI are popular choices. You can change the provider any time, so it is fine to start cheap and switch later.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Where do I get an API key?', 'ai-auto-poster' ),
                        'answer'   => __( 'Each provider issues its own API key. The Providers tab in this plugin links directly to the API key page of every supported provider. You will need to create an account with that provider, add a payment method (most providers require it even for free tiers), and copy the key into this plugin.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Will my article be published immediately, or can I review it first?', 'ai-auto-poster' ),
                        'answer'   => __( 'You decide. The post status setting has three options: Draft, Pending Review, and Publish. With Draft (the default and our recommendation for new users), every generated article waits in your draft list until you publish it manually. Switch to Publish only after you trust the output.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 2. AI providers and API keys
            // ========================================
            array(
                'title' => __( 'AI providers and API keys', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'Are API keys stored securely?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. API keys are encrypted with AES-256-CBC using your WordPress AUTH_KEY before being saved in the database. Keys are never written to execution logs and are never displayed in the admin UI after saving.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'The Test button fails. What should I check?', 'ai-auto-poster' ),
                        'answer'   => __( 'Check four things in order: (1) The API key is correct and still active in the provider dashboard. (2) Your provider account has remaining credit or quota - running out of credit is the most common cause. (3) The selected model is currently available on your account. (4) Your server can reach the provider (some hosting environments block outbound HTTPS). If a key has been saved before, the test uses the saved key even when the field is blank.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Can I use multiple AI providers at the same time?', 'ai-auto-poster' ),
                        'answer'   => __( 'You cannot switch providers per task. The plugin uses one active text AI provider and one active image provider site-wide. You can change the active provider in the Providers tab at any time, and saved API keys for inactive providers are kept so switching back is instant.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'I want to use a newer model that is not in the dropdown.', 'ai-auto-poster' ),
                        'answer'   => __( 'Enter the model ID directly in the custom model field. The custom model value takes priority over whatever is selected in the dropdown, so you can always use the latest model the moment a provider releases it.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'The settings page says my selected model is unavailable.', 'ai-auto-poster' ),
                        'answer'   => __( 'A model that has been deprecated or removed by the provider is still selected. When you save the settings, the plugin will automatically switch to a working replacement model. You can also pick a different model manually before saving.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'I have credits but generation still fails.', 'ai-auto-poster' ),
                        'answer'   => __( 'Common causes: a per-minute rate limit on the provider side (wait a few minutes and retry), a model that requires a specific account tier, a regional restriction, or a network timeout. The execution log records the provider response, which usually points to the exact reason.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 3. Article generation
            // ========================================
            array(
                'title' => __( 'Article generation', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'How should I write prompts to get better articles?', 'ai-auto-poster' ),
                        'answer'   => __( 'The more specifically you describe the target reader, the writing style, the tone, and the structure you expect, the more consistent the result. A short generic prompt like "Write about coffee" produces generic articles. A specific prompt like "Write a 1500-word article for beginner home baristas, friendly tone, with three practical tips and one common mistake" produces much better output. Adjust prompts gradually while reviewing what you get.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Are generated articles published automatically?', 'ai-auto-poster' ),
                        'answer'   => __( 'Only if you set the post status to Publish. The default is Draft, which is the safest option while you are tuning your prompts. With Pending Review, articles wait in the editorial queue. With Publish, articles go live immediately at the scheduled time.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Can I specify the category and author for generated articles?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. Both can be set in the General Settings section. All articles created by the plugin will use that category and that author. If no category is specified, articles go into the default WordPress category.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Can I generate articles in English or other non-Japanese languages?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. About 50 languages are supported. Set the Content Language option per task. Even if your prompt is written in a different language, the article is generated in the language you select. A single site can publish in multiple languages by using different tasks.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Can I control the article length?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. Each task has a Content Length setting (in characters). Set 0 to let the AI decide based on the prompt. Set a specific number to instruct the AI to target that length. Note that AI providers do not always hit the exact target - treat it as a guideline rather than a hard limit.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Will the same prompt always produce the same article?', 'ai-auto-poster' ),
                        'answer'   => __( 'No. AI models are non-deterministic, so the same prompt produces different articles each time. This is normal and is what makes a daily schedule work - you do not need to vary the prompt to avoid repetition. The duplicate prevention feature exists for cases where the variations are still too similar to each other.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Can I control the writing tone or style?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes, through the prompt itself. Add instructions like "professional and concise tone," "friendly and conversational," or "academic style with citations" to your prompt. Different AI models respond to style instructions with different fidelity - Claude and GPT-4 class models tend to follow style cues most closely.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 4. Scheduling
            // ========================================
            array(
                'title' => __( 'Scheduling', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'WP-Cron does not seem to be running.', 'ai-auto-poster' ),
                        'answer'   => __( 'WordPress built-in WP-Cron only runs when someone visits the site, so on low-traffic sites it can be delayed or skipped. For reliable execution at the scheduled time, we recommend a real system cron that calls wp-cron.php every few minutes. Most managed WordPress hosts already do this - check with your host if you are unsure.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Will scheduled posting work when my computer is turned off?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. WordPress runs on the server, not on your computer. As long as the server is online, scheduled posting works regardless of whether your computer is on or off.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Which time zone is used for scheduled times?', 'ai-auto-poster' ),
                        'answer'   => __( 'The time zone configured in WordPress Settings > General > Timezone. This is independent of your server time zone. If your scheduled times look wrong, check that setting first.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'A post was not published at the scheduled time.', 'ai-auto-poster' ),
                        'answer'   => __( 'If missed schedule recovery is enabled, missed schedules are retried the next time WP-Cron runs. The plugin restores the original scheduled date and time on the recovered post, so your archive looks the same as if the schedule had not been missed. Recovery can be turned off if you prefer to skip missed slots entirely.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'How precisely can I schedule? Can I post on weekdays only, or every hour?', 'ai-auto-poster' ),
                        'answer'   => __( 'Each task has two scheduling modes. Fixed mode: a day-of-week selector (any combination of Monday through Sunday) and time slots in HH:MM format. You can configure weekdays-only schedules, weekend-only schedules, or any mix. Random mode: the plugin picks N to M random times within the day, with optional allowed hours and a minimum gap between posts. Both modes can be combined across different tasks. The plugin checks for scheduled tasks every 5 minutes, which is also the minimum granularity for reliable execution.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Can I post multiple articles per day?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. In fixed mode, a single task can have multiple time slots per day, and you can have multiple tasks running in parallel. In random mode, a single task can be configured to post N to M times per day automatically at random times. Be mindful of API costs and the Free plan monthly limit (10 posts) when scheduling high-frequency posting.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What happens if multiple tasks are scheduled at the same time?', 'ai-auto-poster' ),
                        'answer'   => __( 'They are executed sequentially within the same WP-Cron tick. Because each task waits for the AI response, total execution time can be several minutes when many tasks fire together. Spreading task times by a few minutes makes execution smoother.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What is random scheduling and how does it work?', 'ai-auto-poster' ),
                        'answer'   => __( 'Random mode lets a task post a randomized number of articles (between a minimum and a maximum you set) at randomized times throughout the day. Each day at 0:00 the plugin draws a fresh count and time list for that day. Times are picked on a 5-minute grid. This is useful when you want output to feel less mechanical than a fixed daily schedule. Time slots that have already passed for today are kept as-is when you edit task settings, so already-posted articles are never duplicated.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Can I restrict random posts to certain hours?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. The allowed hours option in random mode lets you define one or more time windows (for example 09:00 to 18:00) within which random times must fall. If you leave it empty, the entire 24-hour day is eligible. You can also set a minimum gap (in minutes) so two random posts will not fall too close together.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Why does the planned post count change after I edit a random task?', 'ai-auto-poster' ),
                        'answer'   => __( 'When you change random-mode settings (min, max, allowed hours, or minimum gap), the plugin redraws the count and refreshes future time slots for today using the new settings. Past time slots for today are kept unchanged so already-posted articles are preserved. Because the count is randomized within your min and max, two consecutive edits can produce different planned totals even if you did not change the min/max values.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Random mode for tomorrow shows no upcoming posts. Is that a bug?', 'ai-auto-poster' ),
                        'answer'   => __( 'No. Random times for a given day are generated only on that day (at 0:00 or on first access). The dashboard cannot show specific upcoming times for future days because they have not been drawn yet. Fixed-mode tasks, by contrast, do display upcoming times for future days.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 5. Featured images
            // ========================================
            array(
                'title' => __( 'Featured images', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'Featured images are not being added to my posts.', 'ai-auto-poster' ),
                        'answer'   => __( 'Open the Image Provider tab, choose a provider, save its API key, and make sure it is set to in use. Without an active image provider, posts are created without a featured image. Stock providers (Unsplash, Pexels, Pixabay, Openverse) search existing photos; AI providers (DALL-E, Imagen, Stability, Flux/fal.ai) generate new images.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'AI image generation vs stock photos - which should I choose?', 'ai-auto-poster' ),
                        'answer'   => __( 'Stock photos are essentially free and have predictable quality, but you are limited to what already exists in the library. AI generation gives you exactly what you asked for and a unique image every time, but costs money per image and quality varies. A practical approach: use stock for general topics and AI generation for niche or branded content.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'How much do AI images cost compared to text generation?', 'ai-auto-poster' ),
                        'answer'   => __( 'AI image generation is usually significantly more expensive per item than text generation - sometimes 10x or more. Check the provider pricing page for current rates. If cost is a concern, stock image providers are essentially free aside from API account requirements.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Who owns the copyright of generated or searched images?', 'ai-auto-poster' ),
                        'answer'   => __( 'Rules differ by provider and you should review each provider terms before commercial use. As a general guide: most AI image providers grant commercial use rights to the user who generated the image. Stock providers each have their own license - Unsplash, Pexels, and Pixabay are typically free for commercial use with attribution requirements that vary; Openverse aggregates Creative Commons content with per-image license differences.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Can I customize image size, aspect ratio, or style?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. The Image Provider tab has size, aspect ratio (where supported by the provider), and style options. Available styles depend on the model - for example, DALL-E 3 supports vivid and natural; Flux and Imagen have their own preset lists. The plugin shows only the options the selected model actually supports.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'The featured image often does not match the article content.', 'ai-auto-poster' ),
                        'answer'   => __( 'Image relevance depends on the prompt the plugin sends to the image API, which is derived from the article title and a short excerpt. If results feel off, try a more descriptive article title, switch to a different image model, or use a stock provider where you can search by keyword. AI image models also vary widely in how literal their interpretation is.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 6. SEO features
            // ========================================
            array(
                'title' => __( 'SEO features', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'Does this plugin integrate with Yoast SEO, Rank Math, or All in One SEO?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. With the SEO plugin link option enabled, this plugin writes generated meta descriptions, focus keywords, and SEO titles into the fields used by Yoast SEO, Rank Math, and All in One SEO. Your existing SEO plugin remains the source of truth for site-wide SEO settings.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What SEO features does this plugin add to my posts?', 'ai-auto-poster' ),
                        'answer'   => __( 'When the SEO section is enabled, the plugin can add: meta description, focus keyword, JSON-LD article schema, OGP tags, canonical URL, reading time, automatic internal links to related posts, related-posts block, table of contents, FAQ sections, and image alt text. Each item can be turned on or off individually.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Are SEO features available on the Free plan?', 'ai-auto-poster' ),
                        'answer'   => __( 'No. All SEO features are part of the Pro plan. On the Free plan, articles are created without schema, OGP, or other SEO enhancements. The plan card on the dashboard shows your current plan.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What is llms.txt and should I enable it?', 'ai-auto-poster' ),
                        'answer'   => __( 'llms.txt is a public text file that tells AI crawlers which content on your site is available for them. Some site owners enable it to improve discoverability in AI search engines; others prefer not to expose this information. It is opt-in and off by default. The file is generated at the WordPress root only when this option is on.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What does the Sitemap ping option do?', 'ai-auto-poster' ),
                        'answer'   => __( 'When enabled, the plugin notifies the IndexNow protocol (used by Bing, Yandex, and others) that a new article has been published, so search engines can index it faster. IndexNow requires a key file placed in your wp-content directory; without it, ping is silently skipped. Google and most other engines no longer support sitemap ping and are not contacted.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 7. Duplicate prevention (Pro)
            // ========================================
            array(
                'title' => __( 'Duplicate prevention (Pro)', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'Is duplicate prevention available on the Free plan?', 'ai-auto-poster' ),
                        'answer'   => __( 'No. Duplicate prevention is a Pro-only feature. On the Free plan, every generated article is published as-is without similarity checks. If you publish frequently and want to avoid near-duplicate content, this is one of the main reasons to consider upgrading.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What do "Similarity avoidance succeeded" and "Retry requested" mean in the log?', 'ai-auto-poster' ),
                        'answer'   => __( 'They are messages from the duplicate prevention feature. The plugin compares each newly generated article against your recent posts using two methods: keyword overlap and optional AI scoring. When an article is judged too similar, regeneration is requested ("Retry requested"). When the regenerated article passes, it is logged as "Similarity avoidance succeeded."', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What is the difference between Loose, Balanced, and Strict?', 'ai-auto-poster' ),
                        'answer'   => __( 'They use different similarity thresholds. Strict rejects even articles that are only somewhat similar - safer for archives where uniqueness matters. Loose rejects only clearly duplicate articles - minimizes API usage. Balanced is the default and works well for most sites. Strict consumes more API calls because it requests more regenerations.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What happens if the article still does not pass after the maximum retries?', 'ai-auto-poster' ),
                        'answer'   => __( 'That run is skipped and recorded in the execution log. The next scheduled run is unaffected. The retry maximum is configurable from 1 to 10 (default 3); higher values increase the chance of producing a unique article but also increase API cost.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 7b. RSS feeds (Pro)
            // ========================================
            array(
                'title' => __( 'RSS feeds (Pro)', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'What does the RSS feature do?', 'ai-auto-poster' ),
                        'answer'   => __( 'Per-task RSS integration lets the plugin fetch the latest articles from RSS feeds you register, and pass them to the AI as reference material when generating a new post. Useful for news commentary, curation sites, or topical roundups where you want articles grounded in current external sources rather than the AI writing from general knowledge alone.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Is RSS available on the Free plan?', 'ai-auto-poster' ),
                        'answer'   => __( 'No. RSS feed integration is a Pro-only feature. On the Free plan the RSS settings are visible but cannot be activated.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What is the difference between pick mode and digest mode?', 'ai-auto-poster' ),
                        'answer'   => __( 'Pick mode: the AI is shown several candidate articles and chooses the single most interesting one to write about. Digest mode: the AI is shown several articles and writes one cross-topic summary that covers all of them. Pick produces focused single-topic articles; digest produces broader overview articles.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'How many RSS feeds can I register?', 'ai-auto-poster' ),
                        'answer'   => __( 'Up to 30 feeds total. Per task you can select which feeds it should read from and how many candidate articles to pass to the AI (1 to 10).', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'How does the plugin avoid using the same article twice?', 'ai-auto-poster' ),
                        'answer'   => __( 'The plugin remembers the most recent 500 article identifiers (GUID/link) per feed. Articles already used are skipped automatically. If you delete the article history for a feed (or delete the feed itself), all of its identifiers are cleared and previously-used articles can be picked again.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What happens when there are no new (unused) articles in a feed?', 'ai-auto-poster' ),
                        'answer'   => __( 'Each task with RSS enabled has a fallback option. "Skip post" cancels that run entirely until new articles are available. "Generate without RSS" lets the task fall back to a normal AI-only article. Choose based on whether your editorial concept requires external sources.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Why do I sometimes see "AI returned invalid selected_rss_index" in the log?', 'ai-auto-poster' ),
                        'answer'   => __( 'In pick mode the AI is asked to return the number of the article it chose (between 1 and N). If the AI returns 0 or a number out of range, the plugin uses the first candidate as a safe fallback and logs a warning. The post itself is still created normally.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 8. Troubleshooting
            // ========================================
            array(
                'title' => __( 'Troubleshooting', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'I set up everything but no articles are being created.', 'ai-auto-poster' ),
                        'answer'   => __( 'Run through this checklist: (1) Is the task enabled (toggle in the Tasks tab)? (2) Is an API key saved and tested for an active provider? (3) Does your provider account have remaining credit? (4) Is WP-Cron running on your site? (5) Have you reached the Free plan monthly limit (10 posts)? The execution log usually shows which step failed.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'I see "Free plan monthly post limit reached" in the log.', 'ai-auto-poster' ),
                        'answer'   => __( 'The Free plan allows 10 posts per calendar month. The counter resets at 00:00 on the first day of the next month. If you need more, you can upgrade to Pro from the plan card on the dashboard. Quick Posts and scheduled posts share the same monthly counter.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'The article was generated in the wrong language.', 'ai-auto-poster' ),
                        'answer'   => __( 'Check that the Content Language is set on the task (not just the global setting). Some AI models follow language instructions less strictly than others - if a provider keeps producing English despite a Japanese setting, try a different model or add an explicit language instruction to the end of your prompt (for example, "Write the entire article in Japanese.").', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Image generation fails but text generation works.', 'ai-auto-poster' ),
                        'answer'   => __( 'Image and text providers usually require separate accounts and separate credit. Confirm that the image provider has its own valid API key and remaining credit. Some image models also have stricter content filters that reject prompts the text model accepts - try a more neutral prompt or switch to a stock photo provider as a workaround.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Where can I see what went wrong?', 'ai-auto-poster' ),
                        'answer'   => __( 'The Logs tab shows execution history for the past 7 days. Filter by status to see only errors. Each error log entry includes the task name, the AI provider response, and the step that failed (text generation, image generation, similarity check, post creation, etc.).', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'I generated too many posts by mistake. How do I find and delete them all?', 'ai-auto-poster' ),
                        'answer'   => __( 'Every post created by this plugin is tagged internally with the meta key "_aiap_generated". You can find them by going to Posts and filtering, or with a database query that selects posts with that meta key. This makes mass deletion straightforward without affecting articles you wrote yourself.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 9. Plans, trial, and data
            // ========================================
            array(
                'title' => __( 'Plans, trial, and data', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'question' => __( 'What is the difference between the Free plan and the Pro plan?', 'ai-auto-poster' ),
                        'answer'   => __( 'The Free plan is limited to 10 posts per month and does not include duplicate prevention, SEO features, or configurable missed-schedule recovery. The Pro plan removes the post limit and unlocks all of those features. All AI providers and all image providers are available on both plans.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'When does the monthly limit of 10 posts reset?', 'ai-auto-poster' ),
                        'answer'   => __( 'The count resets automatically at 00:00 on the first day of each calendar month, in the WordPress site time zone. Quick Posts and scheduled automatic posts share the same counter.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'How much do AI provider API fees cost?', 'ai-auto-poster' ),
                        'answer'   => __( 'Costs vary widely by provider, model, and article length, and prices change frequently - please check each provider current pricing page. As a rough guide, budget models such as Gemini Flash, Groq, and DeepSeek can produce a short article for a fraction of a cent, while premium models can cost several cents per article. The most reliable estimate is to generate a few articles and check usage in the provider dashboard.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Is there a free trial of the Pro plan?', 'ai-auto-poster' ),
                        'answer'   => __( 'Yes. A 7-day Pro trial is available from the plan card and does not require a payment method to start. During the trial, the post limit is removed and all Pro features (duplicate prevention, SEO, recovery settings) are unlocked.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'Where are logs stored?', 'ai-auto-poster' ),
                        'answer'   => __( 'In the WordPress wp_options table on your own site. Logs are automatically deleted after 7 days. They are never sent to any external server.', 'ai-auto-poster' ),
                    ),
                    array(
                        'question' => __( 'What happens to my data when I deactivate or uninstall the plugin?', 'ai-auto-poster' ),
                        'answer'   => __( 'Deactivation keeps all data so you can re-enable later without losing settings. Uninstall (deleting the plugin from the Plugins screen) removes plugin settings, encrypted API keys, tasks, schedules, execution logs, transient cache, and the plugin internal post metadata. The articles themselves and their featured images in the Media Library are kept - your published content is never deleted by uninstall.', 'ai-auto-poster' ),
                    ),
                ),
            ),

        );
    }

    /**
     * 使用許諾(Terms of Use)サブメニューを表示する
     *
     * 本文は WordPress 標準の gettext 翻訳(.po/.mo)で管理する。
     * PHP内には英語の msgid のみを置き、日本語は languages/*.po/*.mo に分離する。
     */
    public static function render_terms_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $sections   = self::get_terms_items();
        $intro      = __( 'By installing, activating, or using this plugin, you agree to the terms below. Please read them carefully before use.', 'ai-auto-poster' );
        $updated_at = __( 'Last updated: October 30, 2026', 'ai-auto-poster' );
        $consent_h  = __( 'Important: Use this plugin ONLY if you agree to these Terms of Use', 'ai-auto-poster' );
        $consent_p1 = __( 'These terms are NOT optional. Installing, activating, or otherwise using this plugin in any form constitutes your full and unconditional agreement to every article below, including the disclaimer of any and all damages.', 'ai-auto-poster' );
        $consent_p2 = __( 'If you do not agree to any part of these terms, you must stop using the plugin immediately, deactivate it, and uninstall it from your site. Continued use after disagreement is strictly prohibited.', 'ai-auto-poster' );
        ?>
        <div class="wrap aiap-wrap aiap-faq-wrap">
            <div class="aiap-page-head">
                <h1 class="aiap-page-title"><?php echo esc_html( __( 'Terms of Use', 'ai-auto-poster' ) ); ?></h1>
            </div>
            <div class="aiap-terms-consent" role="alert">
                <h2 class="aiap-terms-consent-title"><?php echo esc_html( $consent_h ); ?></h2>
                <p><strong><?php echo esc_html( $consent_p1 ); ?></strong></p>
                <p><?php echo esc_html( $consent_p2 ); ?></p>
            </div>
            <div class="aiap-card aiap-card-accent">
                <p class="description"><?php echo esc_html( $intro ); ?></p>
                <p class="description aiap-doc-updated-at"><?php echo esc_html( $updated_at ); ?></p>
            </div>
            <?php foreach ( $sections as $section ) : ?>
                <div class="aiap-card aiap-faq-section">
                    <h2 class="aiap-faq-section-title"><?php echo esc_html( $section['title'] ); ?></h2>
                    <div class="aiap-faq-list">
                        <?php foreach ( $section['items'] as $item ) : ?>
                            <details class="aiap-faq-item" open>
                                <summary><?php echo esc_html( $item['heading'] ); ?></summary>
                                <p><?php echo esc_html( $item['body'] ); ?></p>
                            </details>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
        <?php
    }

    /**
     * 使用許諾の項目を返す
     *
     * @return array<int,array{title:string,items:array<int,array{heading:string,body:string}>}>
     */
    private static function get_terms_items() {
        return array(

            // ========================================
            // 1. Application
            // ========================================
            array(
                'title' => __( 'Article 1. Application', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Acceptance of these terms', 'ai-auto-poster' ),
                        'body'    => __( 'These Terms of Use govern the relationship between the user (the site administrator who installs and operates this plugin) and the developer of this plugin. The user must use this plugin ONLY IF they fully agree to every provision of these terms. By installing, activating, or using this plugin in any way, the user is deemed to have given their full and unconditional agreement to all terms below, including the complete disclaimer of damages. If the user does not agree to any part of these terms, the user MUST NOT use this plugin: they must deactivate it and uninstall it from their site immediately. Continued use without agreement is strictly prohibited and is itself a violation of these terms.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 2. Disclaimer (no liability)
            // ========================================
            array(
                'title' => __( 'Article 2. Disclaimer', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'No liability for any damages', 'ai-auto-poster' ),
                        'body'    => __( 'The developer assumes no liability whatsoever for any damages of any kind arising out of or in connection with the use of this plugin, including but not limited to direct, indirect, incidental, special, consequential, or punitive damages, loss of profits, loss of business opportunity, loss of data, site downtime, search ranking impact, third-party claims, or any other damages, regardless of whether such damages were foreseeable. The plugin is provided on an "as is" and "as available" basis, with no warranty of any kind, express or implied, including merchantability, fitness for a particular purpose, accuracy, or non-infringement.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 3. Bugs, defects, and unexpected behavior
            // ========================================
            array(
                'title' => __( 'Article 3. Bugs, defects, and unexpected behavior', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'The plugin may contain bugs and the developer is not obligated to fix them', 'ai-auto-poster' ),
                        'body'    => __( 'Like any software, this plugin may contain bugs, defects, regressions, security vulnerabilities, performance issues, or unexpected behavior, whether known or unknown to the developer. The developer does not guarantee that all such issues are eliminated, that the plugin operates without error, or that any specific issue will be fixed within any specific timeframe. The developer is under no obligation to provide bug fixes, patches, hotfixes, workarounds, individual support, or even a response to inquiries. Any decision to fix, postpone, or not address an issue is at the developer\'s sole discretion.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 4. Updates, continued availability, and support
            // ========================================
            array(
                'title' => __( 'Article 4. Updates, continued availability, and support', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'No guarantee of updates, continued availability, or support', 'ai-auto-poster' ),
                        'body'    => __( 'The developer makes no guarantee regarding the continued availability of this plugin, the frequency or timing of updates, or the provision of any support. The developer may, at any time and at the developer\'s sole discretion, discontinue development, stop releasing updates, terminate distribution, add new features, remove existing features, change specifications, change pricing, change the license model, or transfer the plugin to another party, all without prior notice and without any obligation of compensation, refund, migration assistance, or replacement. Existing users have no right to demand continued operation, feature parity, or backward compatibility.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 5. AI service changes / interruptions
            // ========================================
            array(
                'title' => __( 'Article 5. Changes and interruptions of AI services', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Third-party AI services may change or stop without notice', 'ai-auto-poster' ),
                        'body'    => __( 'This plugin works by calling external AI services (OpenAI, Anthropic, Google, Groq, Unsplash, Pixabay, Pexels, and others). Any of these services may, at any time and without notice, change their API specifications, change pricing, deprecate or remove models, restrict regions, suspend service, or terminate service entirely. As a result, all or part of this plugin may stop functioning, return errors, or produce different results. The developer cannot prevent these changes and provides no compensation, refund, or guarantee of continued operation in such cases.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 6. WordPress / PHP / server environment changes
            // ========================================
            array(
                'title' => __( 'Article 6. Changes to WordPress, PHP, and server environment', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Environment changes may break the plugin without warning', 'ai-auto-poster' ),
                        'body'    => __( 'This plugin runs on top of WordPress, PHP, MySQL/MariaDB, web servers (Apache, Nginx, etc.), and the user\'s hosting provider. Updates, specification changes, security tightening, deprecations, or policy changes by any of these layers - including WordPress core releases, PHP version upgrades, database engine changes, server configuration changes, hosting provider restrictions, or third-party CDN/firewall behavior - may cause this plugin to malfunction, return errors, lose data, or stop working entirely. The developer is under no obligation to track, anticipate, or follow up on such environmental changes, and assumes no liability for any damages arising from them.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 7. Conflicts with other plugins and themes
            // ========================================
            array(
                'title' => __( 'Article 7. Conflicts with other plugins and themes', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'No guarantee of compatibility with other plugins or themes', 'ai-auto-poster' ),
                        'body'    => __( 'WordPress is an open ecosystem with thousands of plugins and themes that hook into the same core. The developer does not test or guarantee compatibility with every combination, and conflicts may occur. Plugins in the following categories are particularly prone to causing issues: caching plugins, SEO plugins, security plugins, REST API restriction plugins, multilingual plugins, page builders, custom post type plugins, and Cron-control plugins. Themes that override WordPress core hooks or admin styling may also cause display or behavioral issues. Investigating, isolating, and resolving such conflicts is the user\'s responsibility, and the developer is not liable for any malfunction, data loss, or damage arising from them.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 8. WP-Cron and scheduling
            // ========================================
            array(
                'title' => __( 'Article 8. WP-Cron and scheduling', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Scheduled jobs may be delayed, missed, duplicated, or executed at unexpected times', 'ai-auto-poster' ),
                        'body'    => __( 'This plugin schedules article generation and posting through WP-Cron, the WordPress task scheduler. WP-Cron is not a real-time scheduler: it depends on visitor traffic to the site to trigger execution. As a result, scheduled jobs may be delayed (especially on low-traffic sites), missed entirely, executed earlier or later than intended, executed multiple times in unexpected ways, or fail silently. Server-level Cron, hosting-side limitations, WP-Cron-disabling plugins, object caches, persistent transients, page caches, and other factors may further affect timing. Configuring server-side Cron and verifying execution timing are the user\'s responsibility, and the developer is not liable for any consequences arising from missed posts, delayed posts, duplicated posts, or posts published at unexpected times.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 9. Data loss, corruption, and backup
            // ========================================
            array(
                'title' => __( 'Article 9. Data loss, corruption, and backup', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Backup is the user\'s responsibility', 'ai-auto-poster' ),
                        'body'    => __( 'Use of this plugin may, in connection with bugs, environmental changes, conflicts, server failures, manual operations, or other causes, result in loss, corruption, partial truncation, or unintended modification of posts, media files, taxonomy terms, plugin settings, options, transients, or any other data stored in the WordPress database or on the server. Taking regular full backups (database and files) before installation, before any update, and on an ongoing basis, and verifying that those backups can actually be restored, is the sole responsibility of the user. The developer is not liable for any data loss or for the cost, effort, or impossibility of recovery.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 10. Security incidents and unauthorized access
            // ========================================
            array(
                'title' => __( 'Article 10. Security incidents and unauthorized access', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'No liability for security incidents', 'ai-auto-poster' ),
                        'body'    => __( 'Despite reasonable care, this plugin may contain security vulnerabilities, whether known or unknown. Through such vulnerabilities, through compromised credentials elsewhere on the site, or through attacks on the underlying WordPress, server, or hosting environment, third parties may gain unauthorized access, leak or steal API keys, leak or steal database content, modify or delete content, install malware, or otherwise harm the site. The developer is not liable for any damage, loss, regulatory penalty, customer notification cost, recovery cost, reputational harm, or any other consequence arising from security incidents, and is under no obligation to provide breach notifications, forensic support, or remediation assistance. Site security, monitoring, hardening, and incident response are the user\'s responsibility.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 11. Responsibility for generated content
            // ========================================
            array(
                'title' => __( 'Article 11. Responsibility for generated content', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'The user is solely responsible for what is published', 'ai-auto-poster' ),
                        'body'    => __( 'AI-generated content may contain factual errors, misleading information, copyright infringement, defamation, privacy violations, discriminatory expressions, or violations of laws or platform policies. The user is solely responsible for reviewing every generated article before publication and bears full responsibility for the content that is actually published on their site. Using the Draft post status and reviewing manually before publishing is strongly recommended. The developer is not responsible for any consequences of published content.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 12. API keys and usage fees
            // ========================================
            array(
                'title' => __( 'Article 12. API keys and usage fees', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Fees and key management are the user\'s responsibility', 'ai-auto-poster' ),
                        'body'    => __( 'All usage fees charged by AI providers (text generation, image generation, search, etc.) are the sole responsibility of the user. The developer does not pay any portion of these fees. The user is responsible for safely managing their API keys, monitoring usage, setting spending limits in each provider dashboard, and preventing unauthorized use. The developer is not liable for unexpectedly high charges, leaked keys, or misuse, even if these result from a bug, misconfiguration, or unexpected behavior of this plugin.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 13. Compliance with third-party terms
            // ========================================
            array(
                'title' => __( 'Article 13. Compliance with third-party service terms', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'The user must follow each provider\'s terms', 'ai-auto-poster' ),
                        'body'    => __( 'The user must comply with the terms of service, usage policies, content policies, and applicable laws of every external service called by this plugin (OpenAI, Anthropic, Google, Groq, Unsplash, Pixabay, Pexels, and others). This includes restrictions on automated content generation, prohibited content categories, attribution requirements, and commercial use rules. Any violation is the sole responsibility of the user, and the developer is not liable for account suspensions, bans, or legal action taken by these providers.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 14. Search engines, SEO, platform evaluations
            // ========================================
            array(
                'title' => __( 'Article 14. Search engines, SEO, and platform evaluations', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'No guarantee about search rankings or platform evaluations', 'ai-auto-poster' ),
                        'body'    => __( 'Publishing AI-generated content, especially in large volume or at high frequency, may negatively affect the site\'s search engine rankings, indexation status, advertising eligibility (Google AdSense and others), social media reach, and other forms of platform evaluation. Search engines and platforms periodically change their content policies and evaluation criteria, sometimes specifically targeting AI-generated content, automated publishing, or low-quality content at scale. The developer makes no representation or warranty regarding any SEO outcome, ranking, traffic level, click-through rate, or platform standing, and is not liable for any drop in rankings, deindexing, manual action, advertising account suspension, or related damages.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 15. Data handling
            // ========================================
            array(
                'title' => __( 'Article 15. Data handling', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Data is sent to AI providers during generation', 'ai-auto-poster' ),
                        'body'    => __( 'During article generation, the prompts, task settings, and other inputs configured by the user are transmitted to the selected AI provider over HTTPS. The data handling, retention, and learning policies of the provider apply to this transmitted data. API keys are encrypted with AES-256-CBC using the WordPress AUTH_KEY and stored in the local database, but the developer cannot guarantee absolute security. The user is responsible for not entering personal information, confidential information, or other sensitive data into prompts.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 16. Prohibited acts
            // ========================================
            array(
                'title' => __( 'Article 16. Prohibited acts', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Acts the user must not perform', 'ai-auto-poster' ),
                        'body'    => __( 'The user must not use this plugin for any of the following: generating illegal content, infringing the rights of third parties (copyright, trademark, privacy, portrait rights, etc.), generating content that defames or discriminates against specific individuals or groups, mass-producing low-quality content for the purpose of search engine spam, generating misleading information that could cause real-world harm, reverse engineering or modifying the plugin in violation of its license, or any other act that violates applicable law or these terms.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 17. Changes to these terms
            // ========================================
            array(
                'title' => __( 'Article 17. Changes to these terms', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Terms may be updated without prior notice', 'ai-auto-poster' ),
                        'body'    => __( 'These Terms of Use may be updated from time to time without prior individual notice. The latest version will always be available on this page. Continued use of the plugin after an update constitutes acceptance of the updated terms. The user is encouraged to review this page periodically.', 'ai-auto-poster' ),
                    ),
                ),
            ),

            // ========================================
            // 18. Governing law and jurisdiction
            // ========================================
            array(
                'title' => __( 'Article 18. Governing law and jurisdiction', 'ai-auto-poster' ),
                'items' => array(
                    array(
                        'heading' => __( 'Japanese law applies', 'ai-auto-poster' ),
                        'body'    => __( 'These Terms of Use are governed by and construed in accordance with the laws of Japan. Any dispute arising out of or in connection with these terms or the use of this plugin shall be subject to the exclusive jurisdiction of the court having jurisdiction over the location of the developer, as the court of first instance.', 'ai-auto-poster' ),
                    ),
                ),
            ),

        );
    }
}
