<?php

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


/* ==========================================================================
   OPTIONS.PHP SAFE — register_setting WITH sanitization
   ========================================================================== */
function reeid_register_settings_early() {

   
    register_setting(
        'reeid_translate_settings',
        'reeid_openai_model',
        array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        )
    );

    register_setting(
        'reeid_translate_settings',
        'reeid_translation_tones',
        array(
            'type'              => 'array',
            'sanitize_callback' => 'reeid_sanitize_tones_array',
            'default'           => array(),
        )
    );



    register_setting(
        'reeid_translate_settings',
        'reeid_translation_source_lang',
        array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_key',
            'default'           => 'en',
        )
    );

    
    
}



if ( ! function_exists( 'reeid_sanitize_tones_array' ) ) {

    function reeid_sanitize_tones_array( $input ) {

        if ( ! is_array( $input ) ) {
            return array();
        }

        $clean = array();

        foreach ( $input as $key => $label ) {

            $key   = sanitize_key( $key );
            $label = sanitize_text_field( $label );

            if ( $key !== '' && $label !== '' ) {
                $clean[ $key ] = $label;
            }
        }

        return $clean;
    }
}

if ( ! function_exists( 'reeid_sanitize_prompt' ) ) {

    function reeid_sanitize_prompt( $v ) {

        $v = wp_unslash( (string) $v );
        $v = wp_kses_post( $v );

        return trim( $v );
    }
}
if ( ! function_exists( 'reeid_sanitize_lang_array' ) ) {

    function reeid_sanitize_lang_array( $input ) {

        if ( ! is_array( $input ) ) {
            return array();
        }

        $clean = array();

        foreach ( $input as $lang ) {

            $lang = sanitize_key( $lang );

            if ( $lang !== '' ) {
                $clean[] = $lang;
            }
        }

        return array_values( array_unique( $clean ) );
    }
}

// options.php safe
reeid_register_settings_early();

// admin UI only
add_action( 'admin_init', 'reeid_register_settings_admin' );
add_action( 'admin_menu', 'reeid_add_settings_page' );



function reeid_register_settings_admin() {


    /* --- API KEY --- */
    register_setting(
        'reeid_translate_settings',
        'reeid_openai_api_key',
        array(
            'type'              => 'string',
            'sanitize_callback' => function( $v ) {

    $v = trim( (string) wp_unslash( $v ) );
    $stored = (string) get_option( 'reeid_openai_api_key', '' );

    // If empty → user did not change key
    if ( $v === '' && $stored !== '' ) {
        return $stored;
    }

    // If completely empty (no previous key)
    if ( $v === '' ) {
        update_option( 'reeid_openai_status', 'empty', false );
        return '';
    }

    $v = sanitize_text_field( $v );

    $response = wp_remote_get(
        'https://api.openai.com/v1/models',
        array(
            'timeout' => 15,
            'headers' => array(
                'Authorization' => 'Bearer ' . $v,
            ),
        )
    );

    if ( is_wp_error( $response ) ) {
        update_option( 'reeid_openai_status', 'invalid', false );
        return $v;
    }

    $code = (int) wp_remote_retrieve_response_code( $response );

    if ( $code === 200 ) {
        update_option( 'reeid_openai_status', 'valid', false );
    } else {
        update_option( 'reeid_openai_status', 'invalid', false );
    }

    return $v;
},

            'default'           => '',
        )
    );


    /* --- MODEL (fixed to gpt-5.4-mini) --- */
    register_setting(
        'reeid_translate_settings',
        'reeid_openai_model',
        array(
            'type'              => 'string',
            'sanitize_callback' => 'reeid_sanitize_model',
            'default'           => 'gpt-5.4-mini',
        )
    );

    /* --- Tone presets --- */
  register_setting(
    'reeid_translate_settings',
    'reeid_translation_tones',
    array(
        'type'              => 'array',
        'sanitize_callback' => 'reeid_sanitize_tones',
        'default'           => array(),
    )
);




    /* --- Default source language --- */
    register_setting(
        'reeid_translate_settings',
        'reeid_translation_source_lang',
        array(
            'type'              => 'string',
            'sanitize_callback' => function( $v ) {
    $lang = sanitize_key( (string) wp_unslash( $v ) );
    return '' !== $lang ? $lang : 'en';
},
            'default'           => 'en',
        )
    );


    /* =======================================================================
       SETTINGS SECTION
       ======================================================================= */
    add_settings_section(
        'reeid_section_general',
        __( 'General Settings', 'reeid-translate' ),
        function() {
echo '<p>' . esc_html__( 'Configure your API key, tone presets, default source language, and translation options.', 'reeid-translate' ) . '</p>';        },
        'reeid-translate-settings'
    );

    /* --- Fields --- */

    add_settings_field(
        'reeid_openai_api_key',
        __( 'OpenAI API Key', 'reeid-translate' ),
        'reeid_render_api_key_field',
        'reeid-translate-settings',
        'reeid_section_general'
    );

    


    add_settings_field(
        'reeid_translation_source_lang',
        __( 'Default Source Language', 'reeid-translate' ),
        'reeid_render_source_lang_field',
        'reeid-translate-settings',
        'reeid_section_general'
    );

                               

}

/*==============================================================================
  SANITIZERS
==============================================================================*/

/** Enforce model hard-lock to gpt-5.4-mini. */
function reeid_sanitize_model( $input ) {
    return 'gpt-5.4-mini';
}

/**
 * Sanitize tone presets (max two).
 * UI uses lowercase tone keys.
 */
function reeid_sanitize_tones( $input ) {

    // Allowed tone keys (must match UI exactly)
    $valid = array(
        'neutral',
        'friendly',
        'professional',
        'casual',
        'formal',
        'marketing',
        'seo',
    );

    $out = array();

    if ( is_array( $input ) ) {
        foreach ( $input as $tone ) {
            $tone = sanitize_text_field( (string) wp_unslash( $tone ) );

            if ( in_array( $tone, $valid, true ) ) {
                $out[] = $tone;
            }

            // Max two tones
            if ( count( $out ) >= 2 ) {
                break;
            }
        }
    }

    // Fallback: always at least neutral
    return ! empty( $out ) ? $out : array( 'neutral' );
}




/*==============================================================================
  FIELD RENDERERS
==============================================================================*/

/** API key field */
function reeid_render_api_key_field() {

    $key    = trim( get_option( 'reeid_openai_api_key', '' ) );
    $status = get_option( 'reeid_openai_status', 'empty' );

    if ( $key === '' ) {
        $status = 'empty';
    }

    ?>
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:8px;">
        <input type="password"
            name="reeid_openai_api_key"
            value=""
            placeholder="<?php echo $key ? 'Leave blank to keep existing key.' : 'sk-...'; ?>"
            style="width:300px;"
            autocomplete="new-password">
    </div>

    <!-- <p style="margin:0;color:#666;font-size:12px;">
        <?php esc_html_e( 'Leave blank to keep existing key.', 'reeid-translate' ); ?>
    </p> -->

    <div id="reeid_openai_key_status" style="margin-top:6px;">
        <?php if ( $status === 'valid' ) : ?>
            <span style="color:green;font-weight:bold;">&#10004; <?php esc_html_e( 'Valid API Key', 'reeid-translate' ); ?></span>
        <?php elseif ( $status === 'invalid' ) : ?>
            <span style="color:red;font-weight:bold;">&#10006; <?php esc_html_e( 'Invalid API Key', 'reeid-translate' ); ?></span>
        <?php else : ?>
            <span style="color:#777;font-weight:bold;">&#9711; <?php esc_html_e( 'API Key not configured', 'reeid-translate' ); ?></span>
        <?php endif; ?>
    </div>
    <?php
}


/** (Disabled model field for completeness) */
function reeid_render_model_field() {

    $val     = 'gpt-5.4-mini';
    $options = array(
        'gpt-5.4-mini' => 'gpt-5.4-mini (Fast, affordable, precise)',
    );

    echo '<select name="reeid_openai_model" style="width:300px;" disabled>';
    foreach ( $options as $model => $label ) {
        printf(
            '<option value="%s"%s>%s</option>',
            esc_attr( $model ),
            selected( $val, $model, false ),
            esc_html( $label )
        );
    }
    echo '</select>';

    echo '<p class="description" style="margin-top:6px;">' .
        esc_html__( 'Model selection is internally fixed in this build.', 'reeid-translate' ) .
        '</p>';
}


/** Source language dropdown */
function reeid_render_source_lang_field() {

    $cur = get_option( 'reeid_translation_source_lang', 'en' );
    $all = reeid_get_supported_languages();

    echo '<select name="reeid_translation_source_lang" style="width:300px;">';
    foreach ( $all as $code => $label ) {
        printf(
            '<option value="%s"%s>%s</option>',
            esc_attr( $code ),
            selected( $cur, $code, false ),
            esc_html( $label )
        );
    }
    echo '</select>';
}




/* ===========================================================
 * Canonical: get enabled target languages from Admin Settings.
 * Used by translation UI and language-aware workflows.
 * =========================================================== */
if ( ! function_exists( 'reeid_get_enabled_languages' ) ) {
    function reeid_get_enabled_languages(): array {

        static $cache = null;
        if ( is_array( $cache ) ) {
            return $cache;
        }

        /* -------- 1) Candidate option names -------- */
        $candidates = array(
            'reeid_enabled_languages',
            'reeid_translation_target_languages',
            'reeid_translation_languages',
        );
 
        $acc = array();

        foreach ( $candidates as $opt ) {
            $val = get_option( $opt, array() );

            if ( is_array( $val ) ) {
                foreach ( $val as $v ) {
                    $acc[] = (string) $v;
                }
            } elseif ( is_string( $val ) && $val !== '' ) {
                $parts = array_map( 'trim', explode( ',', $val ) );
                foreach ( $parts as $p ) {
                    $acc[] = (string) $p;
                }
            }
        }

        /* -------- 2) Sanitize language codes -------- */
        $acc = array_map(
            static function( $lang ) {
                $lang = strtolower( trim( (string) $lang ) );
                return preg_replace( '/[^a-z0-9\-_]/i', '', $lang );
            },
            $acc
        );

        /* -------- 3) Remove empty -------- */
        $acc = array_values( array_filter( $acc, static fn( $l ) => $l !== '' ) );

        /* -------- 4) Intersect with supported -------- */
        if ( function_exists( 'reeid_get_supported_languages' ) ) {
            $supported = array_keys( (array) reeid_get_supported_languages() );
            $acc       = array_values( array_intersect( $acc, $supported ) );
        }

        /* -------- 5) Cache & return -------- */
        $cache = $acc;
        return $acc;
    }
}
