<?php
defined( 'ABSPATH' ) || exit;

class PIPEBU_Settings {

    public static function get( string $key, $default = '' ) {
        $settings = get_option( PIPEBU_OPTION_KEY, [] );
        return $settings[ $key ] ?? $default;
    }

    public static function save( array $data ): void {
        $settings = get_option( PIPEBU_OPTION_KEY, [] );

        if ( ! empty( $data['api_key'] ) ) {
            $settings['api_key'] = self::encrypt( sanitize_text_field( $data['api_key'] ) );
        }
        if ( isset( $data['provider'] ) ) {
            $settings['provider'] = in_array( $data['provider'], self::providers(), true )
                ? $data['provider'] : 'claude';
        }
        if ( isset( $data['model'] ) ) {
            $settings['model'] = sanitize_text_field( $data['model'] );
        }
        if ( isset( $data['howto_category'] ) ) {
            $settings['howto_category'] = absint( $data['howto_category'] );
        }
        if ( isset( $data['publish_status'] ) ) {
            $settings['publish_status'] = in_array( $data['publish_status'], [ 'publish', 'draft' ], true )
                ? $data['publish_status'] : 'draft';
        }
        if ( isset( $data['ui_mode'] ) ) {
            $settings['ui_mode'] = in_array( $data['ui_mode'], [ 'simple', 'expert' ], true )
                ? $data['ui_mode'] : 'simple';
        }
        // Short description template.
        if ( isset( $data['short_desc_template'] ) ) {
            $settings['short_desc_template'] = wp_kses_post( $data['short_desc_template'] );
        }
        // How To link toggle.
        if ( isset( $data['howto_link_enabled'] ) ) {
            $settings['howto_link_enabled'] = (bool) $data['howto_link_enabled'];
        }

        update_option( PIPEBU_OPTION_KEY, $settings );
    }

    public static function api_key(): string {
        $encrypted = self::get( 'api_key', '' );
        return $encrypted ? self::decrypt( $encrypted ) : '';
    }

    public static function provider(): string {
        return self::get( 'provider', 'claude' );
    }

    public static function model(): string {
        $defaults = [
            'claude' => 'claude-sonnet-4-6',
            'openai' => 'gpt-4o',
        ];
        $saved = self::get( 'model', '' );
        return $saved ?: ( $defaults[ self::provider() ] ?? 'claude-sonnet-4-6' );
    }

    public static function howto_category(): int {
        return (int) self::get( 'howto_category', 0 );
    }

    public static function publish_status(): string {
        return self::get( 'publish_status', 'draft' );
    }

    public static function ui_mode(): string {
        return self::get( 'ui_mode', 'simple' );
    }

    public static function short_desc_template(): string {
        return self::get( 'short_desc_template',
            "<p>\xF0\x9F\x93\x96 <a href=\"[HOWTO_LINK]\"><strong>How To Use Guide &#8594;</strong></a></p><p>&nbsp;</p>"
        );
    }

    public static function howto_link_enabled(): bool {
        return (bool) self::get( 'howto_link_enabled', true );
    }

    public static function providers(): array {
        return [ 'claude', 'openai' ];
    }

    public static function content_depths(): array {
        return [
            'express'  => 'Express — tight, scannable, conversion-focused',
            'standard' => 'Standard — balanced (recommended)',
            'rich'     => 'Rich — content-dense, SEO-heavy, long-form',
        ];
    }

    public static function tones(): array {
        return [
            'professional'  => 'Professional — clean, authoritative',
            'friendly'      => 'Friendly — warm, approachable, beginner-focused',
            'technical'     => 'Technical — spec-forward, enthusiast audience',
            'playful'       => 'Playful — personality-driven, lifestyle brands',
            'philosophical' => 'Philosophical — reflective, thought-provoking',
            'custom'        => 'Custom — I\'ll describe my own brand voice',
        ];
    }

    public static function languages(): array {
        return [
            ''   => 'Auto',
            'en' => 'English',
            'es' => 'Español',
            'pt' => 'Português',
            'fr' => 'Français',
            'de' => 'Deutsch',
            'it' => 'Italiano',
            'ja' => '日本語',
            'zh' => '中文',
            'ko' => '한국어',
            'ar' => 'العربية',
        ];
    }

    public static function lang_ui_strings(): array {
        return [
            'es' => [
                'tip'             => 'Consejo: escribe tu guía en cualquier idioma y Pipeline Buster genera el listado completo — descripción, guía y campos SEO — en ese idioma.',
                'tone_ref_or'     => '— o elige un post existente como referencia de estilo —',
                'tone_ref_search' => 'Buscar posts o descripciones de productos…',
                'custom_style_ph' => 'Describe tu voz de marca… ej. "Audaz, directo, habla a fumadores experimentados."',
                'custom_pill'     => 'Personalizado',
                'custom_desc'     => 'Describiré mi propia voz de marca',
            ],
            'pt' => [
                'tip'             => 'Dica: escreva seu guia em qualquer idioma e o Pipeline Buster gera o anúncio completo — descrição, guia e campos de SEO — nesse idioma.',
                'tone_ref_or'     => '— ou escolha um post existente como referência de estilo —',
                'tone_ref_search' => 'Pesquisar posts ou descrições de produtos…',
                'custom_style_ph' => 'Descreva sua voz de marca…',
                'custom_pill'     => 'Personalizado',
                'custom_desc'     => 'Descreverei minha própria voz de marca',
            ],
            'fr' => [
                'tip'             => 'Conseil : rédigez votre guide dans n\'importe quelle langue et Pipeline Buster génère l\'annonce complète — description, guide et champs SEO — dans cette langue.',
                'tone_ref_or'     => '— ou choisissez un article existant comme référence de style —',
                'tone_ref_search' => 'Rechercher des articles ou des descriptions de produits…',
                'custom_style_ph' => 'Décrivez votre voix de marque…',
                'custom_pill'     => 'Personnalisé',
                'custom_desc'     => 'Je décrirai ma propre voix de marque',
            ],
            'de' => [
                'tip'             => 'Tipp: Schreiben Sie Ihren Brief in einer beliebigen Sprache und Pipeline Buster erstellt das gesamte Listing — Beschreibung, Anleitung und SEO-Felder — in dieser Sprache.',
                'tone_ref_or'     => '— oder wählen Sie einen vorhandenen Beitrag als Stilreferenz —',
                'tone_ref_search' => 'Beiträge oder Produktbeschreibungen suchen…',
                'custom_style_ph' => 'Beschreiben Sie Ihre Markenstimme…',
                'custom_pill'     => 'Benutzerdefiniert',
                'custom_desc'     => 'Ich beschreibe meine eigene Markenstimme',
            ],
            'it' => [
                'tip'             => 'Suggerimento: scrivi il tuo brief in qualsiasi lingua e Pipeline Buster genera la scheda completa — descrizione, guida e campi SEO — in quella lingua.',
                'tone_ref_or'     => '— oppure scegli un post esistente come riferimento di stile —',
                'tone_ref_search' => 'Cerca post o descrizioni di prodotti…',
                'custom_style_ph' => 'Descrivi la tua voce del brand…',
                'custom_pill'     => 'Personalizzato',
                'custom_desc'     => 'Descriverò la mia voce del brand',
            ],
            'ja' => [
                'tip'             => 'ヒント：どの言語でも指示を書くと、Pipeline Busterが商品説明・ガイド・SEOフィールドをすべてその言語で生成します。',
                'tone_ref_or'     => '— または既存の投稿をスタイル参照として選択 —',
                'tone_ref_search' => '投稿や商品説明を検索…',
                'custom_style_ph' => 'ブランドボイスを説明してください…',
                'custom_pill'     => 'カスタム',
                'custom_desc'     => '独自のブランドボイスを説明します',
            ],
            'zh' => [
                'tip'             => '提示：用任何语言写下您的简介，Pipeline Buster 将以该语言生成完整的列表——描述、指南和SEO字段。',
                'tone_ref_or'     => '— 或选择现有帖子作为风格参考 —',
                'tone_ref_search' => '搜索帖子或产品描述…',
                'custom_style_ph' => '描述您的品牌声音…',
                'custom_pill'     => '自定义',
                'custom_desc'     => '我来描述我自己的品牌声音',
            ],
            'ko' => [
                'tip'             => '팁: 어떤 언어로든 지침을 작성하면 Pipeline Buster가 상품 설명, 가이드, SEO 필드를 모두 해당 언어로 생성합니다.',
                'tone_ref_or'     => '— 또는 기존 게시물을 스타일 참조로 선택 —',
                'tone_ref_search' => '게시물 또는 제품 설명 검색…',
                'custom_style_ph' => '브랜드 보이스를 설명해 주세요…',
                'custom_pill'     => '맞춤',
                'custom_desc'     => '나만의 브랜드 보이스를 설명하겠습니다',
            ],
            'ar' => [
                'tip'             => 'نصيحة: اكتب موجزك بأي لغة وسيقوم Pipeline Buster بإنشاء القائمة كاملة — الوصف والدليل وحقول SEO — بتلك اللغة.',
                'tone_ref_or'     => '— أو اختر منشورًا موجودًا كمرجع للأسلوب —',
                'tone_ref_search' => 'البحث في المنشورات أو أوصاف المنتجات…',
                'custom_style_ph' => 'صف صوت علامتك التجارية…',
                'custom_pill'     => 'مخصص',
                'custom_desc'     => 'سأصف صوت علامتي التجارية',
            ],
        ];
    }

    // -------------------------------------------------------------------------
    // Settings page render
    // -------------------------------------------------------------------------

    public static function render_settings_page(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        if ( isset( $_POST['pipebu_save_settings'] ) ) {
            check_admin_referer( 'pipebu_settings_save' );
            $safe_data = array_intersect_key(
                wp_unslash( $_POST ),
                array_flip( [ 'api_key', 'provider', 'model', 'howto_category', 'publish_status', 'ui_mode', 'short_desc_template', 'howto_link_enabled' ] )
            );
            self::save( $safe_data );
            // Redirect to New Product page after save.
            wp_safe_redirect( admin_url( 'admin.php?page=pipeline-buster&pb_saved=1' ) );
            exit;
        }

        if ( isset( $_GET['pipebu_saved'] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' .
                '&#10003; ' . esc_html__( 'Settings saved! Ready to bust some pipelines.', 'pipeline-buster' ) .
                ' <a href="' . esc_url( admin_url( 'admin.php?page=pipeline-buster' ) ) . '">' .
                esc_html__( 'Add a product →', 'pipeline-buster' ) . '</a></p></div>';
        }

        $provider    = self::provider();
        $model       = self::model();
        $has_key     = ! empty( self::api_key() );
        $howto_cat   = self::howto_category();
        $pub_status  = self::publish_status();
        $ui_mode     = self::ui_mode();
        $sd_template = self::short_desc_template();
        $howto_link  = self::howto_link_enabled();
        ?>
        <div class="wrap pb-settings-wrap">
            <h1 class="pb-settings-heading">
                <span class="pb-logo-mark">&#128640;</span>
                <?php esc_html_e( 'Pipeline Buster — Settings', 'pipeline-buster' ); ?>
                <span class="pb-version-tag">v<?php echo esc_html( PIPEBU_VERSION ); ?></span>
            </h1>

            <form method="post" class="pb-settings-form">
                <?php wp_nonce_field( 'pipebu_settings_save' ); ?>

                <div class="pb-settings-grid">

                    <!-- AI Provider -->
                    <div class="pb-settings-card">
                        <h2><?php esc_html_e( 'AI Provider', 'pipeline-buster' ); ?></h2>
                        <table class="form-table" role="presentation">
                            <tr>
                                <th><label for="pb_provider"><?php esc_html_e( 'Provider', 'pipeline-buster' ); ?></label></th>
                                <td>
                                    <select name="provider" id="pb_provider">
                                        <option value="claude" <?php selected( $provider, 'claude' ); ?>>Anthropic Claude (recommended)</option>
                                        <option value="openai" <?php selected( $provider, 'openai' ); ?>>OpenAI GPT-4o</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="pb_api_key"><?php esc_html_e( 'API Key', 'pipeline-buster' ); ?></label></th>
                                <td>
                                    <input type="password" name="api_key" id="pb_api_key"
                                           value="" class="regular-text"
                                           placeholder="<?php echo $has_key ? esc_attr__( '(saved — enter new to replace)', 'pipeline-buster' ) : 'sk-ant-api03-...'; ?>" />
                                    <?php if ( $has_key ) : ?>
                                        <span class="pb-key-saved">&#10003; <?php esc_html_e( 'Key saved', 'pipeline-buster' ); ?></span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="pb_model"><?php esc_html_e( 'Model', 'pipeline-buster' ); ?></label></th>
                                <td>
                                    <input type="text" name="model" id="pb_model"
                                           value="<?php echo esc_attr( $model ); ?>" class="regular-text" />
                                    <p class="description">
                                        Claude: <code>claude-sonnet-4-6</code> (recommended) or <code>claude-haiku-4-5-20251001</code> (faster/cheaper)<br>
                                        OpenAI: <code>gpt-4o</code>
                                    </p>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <!-- Publishing -->
                    <div class="pb-settings-card">
                        <h2><?php esc_html_e( 'Publishing', 'pipeline-buster' ); ?></h2>
                        <table class="form-table" role="presentation">
                            <tr>
                                <th><label for="pb_publish_status"><?php esc_html_e( 'Default Publish Status', 'pipeline-buster' ); ?></label></th>
                                <td>
                                    <select name="publish_status" id="pb_publish_status">
                                        <option value="draft"   <?php selected( $pub_status, 'draft' ); ?>><?php esc_html_e( 'Draft — review in WP Admin before going live (recommended)', 'pipeline-buster' ); ?></option>
                                        <option value="publish" <?php selected( $pub_status, 'publish' ); ?>><?php esc_html_e( 'Published — go live immediately', 'pipeline-buster' ); ?></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="pb_howto_cat"><?php esc_html_e( '"How To" Category', 'pipeline-buster' ); ?></label></th>
                                <td>
                                    <?php
                                    wp_dropdown_categories( [
                                        'name'              => 'howto_category',
                                        'id'                => 'pb_howto_cat',
                                        'selected'          => $howto_cat,
                                        'show_option_none'  => __( '— None —', 'pipeline-buster' ),
                                        'option_none_value' => 0,
                                        'taxonomy'          => 'category',
                                        'hide_empty'        => false,
                                    ] );
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <th><?php esc_html_e( 'How To Link in Short Desc', 'pipeline-buster' ); ?></th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="howto_link_enabled" value="1"
                                               <?php checked( $howto_link ); ?> />
                                        <?php esc_html_e( 'Automatically add How To post link to product short description', 'pipeline-buster' ); ?>
                                    </label>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="pb_sd_template"><?php esc_html_e( 'Short Desc Link Template', 'pipeline-buster' ); ?></label></th>
                                <td>
                                    <textarea name="short_desc_template" id="pb_sd_template"
                                              rows="3" class="large-text"><?php echo esc_textarea( $sd_template ); ?></textarea>
                                    <p class="description"><?php esc_html_e( 'Use [HOWTO_LINK] as placeholder. HTML allowed.', 'pipeline-buster' ); ?></p>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <!-- UI Mode -->
                    <div class="pb-settings-card">
                        <h2><?php esc_html_e( 'Interface', 'pipeline-buster' ); ?></h2>
                        <table class="form-table" role="presentation">
                            <tr>
                                <th><?php esc_html_e( 'Default UI Mode', 'pipeline-buster' ); ?></th>
                                <td>
                                    <label style="display:block;margin-bottom:8px">
                                        <input type="radio" name="ui_mode" value="simple" <?php checked( $ui_mode, 'simple' ); ?> />
                                        <strong><?php esc_html_e( 'Simple', 'pipeline-buster' ); ?></strong> — <?php esc_html_e( 'Guided, one step at a time. Best for beginners.', 'pipeline-buster' ); ?>
                                    </label>
                                    <label style="display:block">
                                        <input type="radio" name="ui_mode" value="expert" <?php checked( $ui_mode, 'expert' ); ?> />
                                        <strong><?php esc_html_e( 'Expert', 'pipeline-buster' ); ?></strong> — <?php esc_html_e( 'Full review screen, everything visible at once.', 'pipeline-buster' ); ?>
                                    </label>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <!-- Google Search Console -->
                    <div class="pb-settings-card pb-gsc-card">
                        <h2>&#128202; <?php esc_html_e( 'Google Search Console', 'pipeline-buster' ); ?></h2>
                        <?php self::render_gsc_section(); ?>
                    </div>

                </div><!-- .pb-settings-grid -->

                <div class="pb-settings-submit">
                    <?php submit_button( __( 'Save Settings', 'pipeline-buster' ), 'primary large', 'pipebu_save_settings', false ); ?>
                </div>
            </form>
        </div>
        <?php
    }

    private static function render_gsc_section(): void {
        $connected    = PIPEBU_GSC::is_connected();
        $selected     = PIPEBU_GSC::get_selected_site();
        $baseline     = PIPEBU_GSC::get_baseline();
        $connect_url  = PIPEBU_GSC::get_auth_url();

        if ( isset( $_GET['pipebu_gsc'] ) ) {
            $pb_gsc = sanitize_key( wp_unslash( $_GET['pipebu_gsc'] ) );
            if ( 'connected' === $pb_gsc ) {
                echo '<div class="notice notice-success inline"><p>&#10003; ' .
                    esc_html__( 'Google Search Console connected!', 'pipeline-buster' ) . '</p></div>';
            } elseif ( 'error' === $pb_gsc ) {
                echo '<div class="notice notice-error inline"><p>' .
                    esc_html__( 'Connection failed. Please try again.', 'pipeline-buster' ) . '</p></div>';
            } elseif ( 'baseline_saved' === $pb_gsc ) {
                echo '<div class="notice notice-success inline"><p>&#10003; ' .
                    esc_html__( 'Baseline snapshot saved.', 'pipeline-buster' ) . '</p></div>';
            }
        }

        if ( ! $connected ) : ?>
            <p class="description"><?php esc_html_e( 'Connect your Google Search Console account to enable baseline tracking and before/after performance comparisons.', 'pipeline-buster' ); ?></p>
            <a href="<?php echo esc_url( $connect_url ); ?>" class="button button-primary pb-gsc-connect-btn">
                &#128279; <?php esc_html_e( 'Connect Google Search Console', 'pipeline-buster' ); ?>
            </a>
        <?php else : ?>
            <p class="pb-gsc-status">
                <span class="pb-gsc-dot pb-gsc-dot--green"></span>
                <strong><?php esc_html_e( 'Connected', 'pipeline-buster' ); ?></strong>
            </p>

            <?php
            // Site selector.
            $sites = PIPEBU_GSC::get_sites();
            if ( $sites ) : ?>
                <div class="pb-gsc-site-row">
                    <label for="pb_gsc_site"><strong><?php esc_html_e( 'Tracked Site', 'pipeline-buster' ); ?></strong></label>
                    <select id="pb_gsc_site" class="pb-gsc-site-select">
                        <option value=""><?php esc_html_e( '— Select a site —', 'pipeline-buster' ); ?></option>
                        <?php foreach ( $sites as $site ) :
                            $url = $site['siteUrl'] ?? '';
                            ?>
                            <option value="<?php echo esc_attr( $url ); ?>" <?php selected( $selected, $url ); ?>>
                                <?php echo esc_html( $url ); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" class="button" id="pb-gsc-save-site-btn">
                        <?php esc_html_e( 'Save', 'pipeline-buster' ); ?>
                    </button>
                    <span id="pb-gsc-site-saved" style="display:none;color:#46b450;margin-left:8px;">&#10003;</span>
                </div>
            <?php endif; ?>

            <?php if ( $selected ) : ?>
                <div class="pb-gsc-baseline-section">
                    <h3><?php esc_html_e( 'Baseline Snapshot', 'pipeline-buster' ); ?></h3>
                    <?php if ( $baseline ) : ?>
                        <table class="pb-gsc-baseline-table">
                            <tr>
                                <td><?php esc_html_e( 'Captured', 'pipeline-buster' ); ?></td>
                                <td><strong><?php echo esc_html( $baseline['date'] ); ?></strong></td>
                            </tr>
                            <tr>
                                <td><?php esc_html_e( 'Period', 'pipeline-buster' ); ?></td>
                                <td><?php echo esc_html( $baseline['period'] ); ?></td>
                            </tr>
                            <tr>
                                <td><?php esc_html_e( 'Impressions', 'pipeline-buster' ); ?></td>
                                <td><strong><?php echo esc_html( number_format( $baseline['impressions'] ) ); ?></strong></td>
                            </tr>
                            <tr>
                                <td><?php esc_html_e( 'Clicks', 'pipeline-buster' ); ?></td>
                                <td><strong><?php echo esc_html( number_format( $baseline['clicks'] ) ); ?></strong></td>
                            </tr>
                            <tr>
                                <td><?php esc_html_e( 'Keywords Ranking', 'pipeline-buster' ); ?></td>
                                <td><strong><?php echo esc_html( number_format( $baseline['keywords'] ) ); ?></strong></td>
                            </tr>
                            <tr>
                                <td><?php esc_html_e( 'Avg. Position', 'pipeline-buster' ); ?></td>
                                <td><strong><?php echo esc_html( $baseline['position'] ); ?></strong></td>
                            </tr>
                        </table>
                        <button type="button" class="button" id="pb-gsc-baseline-btn">
                            &#8635; <?php esc_html_e( 'Update Baseline', 'pipeline-buster' ); ?>
                        </button>
                    <?php else : ?>
                        <p class="description"><?php esc_html_e( 'No baseline yet. Capture a snapshot of your current GSC performance before PB content goes live. This is your T=0 reference point.', 'pipeline-buster' ); ?></p>
                        <button type="button" class="button button-primary" id="pb-gsc-baseline-btn">
                            &#128248; <?php esc_html_e( 'Take Baseline Snapshot', 'pipeline-buster' ); ?>
                        </button>
                    <?php endif; ?>
                    <span id="pb-gsc-baseline-spinner" style="display:none;" class="spinner is-active" style="float:none;"></span>
                    <p id="pb-gsc-baseline-msg" style="display:none;"></p>
                </div>
            <?php endif; ?>

            <div class="pb-gsc-disconnect-row">
                <button type="button" class="button pb-gsc-disconnect-btn" id="pb-gsc-disconnect-btn">
                    <?php esc_html_e( 'Disconnect', 'pipeline-buster' ); ?>
                </button>
            </div>
        <?php endif;
    }

    // -------------------------------------------------------------------------
    // Encryption helpers
    // -------------------------------------------------------------------------

    private static function encrypt( string $value ): string {
        if ( ! $value ) return '';
        $key    = substr( hash( 'sha256', AUTH_KEY . SECURE_AUTH_KEY ), 0, 32 );
        $iv     = random_bytes( 16 );
        $cipher = openssl_encrypt( $value, 'aes-256-cbc', $key, 0, $iv );
        return base64_encode( $iv . $cipher );
    }

    private static function decrypt( string $value ): string {
        if ( ! $value ) return '';
        $key    = substr( hash( 'sha256', AUTH_KEY . SECURE_AUTH_KEY ), 0, 32 );
        $raw    = base64_decode( $value );
        $iv     = substr( $raw, 0, 16 );
        $cipher = substr( $raw, 16 );
        $plain  = openssl_decrypt( $cipher, 'aes-256-cbc', $key, 0, $iv );
        return $plain ?: '';
    }
}
