<?php
/**
 * Admin Functionality
 *
 * @package HDSofT\AISummary
 */

namespace HDSofT\AISummary;

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Admin Class
 */
class Admin {

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
        add_action( 'wp_ajax_hdsoft_ai_summary_test_connection', array( $this, 'ajax_test_connection' ) );
        add_action( 'wp_ajax_hdsoft_ai_summary_get_models', array( $this, 'ajax_get_models' ) );
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_options_page(
            __( 'HD SofT AI Summary Settings', 'hd-soft-ai-summary' ),
            __( 'HD SofT AI Summary', 'hd-soft-ai-summary' ),
            'manage_options',
            'hd-soft-ai-summary',
            array( $this, 'settings_page' )
        );
    }

    /**
     * Register settings
     */
    public function register_settings() {
        // Register settings group
        register_setting(
            'hdsoft_ai_summary_settings_group',
            'hdsoft_ai_summary_settings',
            array(
                'sanitize_callback' => array( $this, 'sanitize_settings' ),
            )
        );

        // Register API key separately with autoload=false
        register_setting(
            'hdsoft_ai_summary_settings_group',
            'hdsoft_ai_summary_openrouter_api_key',
            array(
                'sanitize_callback' => 'sanitize_text_field',
            )
        );

        // API Settings Section
        add_settings_section(
            'hdsoft_ai_summary_api_section',
            __( 'OpenRouter API Settings', 'hd-soft-ai-summary' ),
            array( $this, 'api_section_callback' ),
            'hd-soft-ai-summary'
        );

        // API Key Field
        add_settings_field(
            'openrouter_api_key',
            __( 'OpenRouter API Key', 'hd-soft-ai-summary' ),
            array( $this, 'api_key_field_callback' ),
            'hd-soft-ai-summary',
            'hdsoft_ai_summary_api_section'
        );

        // Model Selection Field
        add_settings_field(
            'model_name',
            __( 'AI Model', 'hd-soft-ai-summary' ),
            array( $this, 'model_field_callback' ),
            'hd-soft-ai-summary',
            'hdsoft_ai_summary_api_section'
        );

        // Max Tokens Field
        add_settings_field(
            'max_tokens',
            __( 'Maximum Tokens', 'hd-soft-ai-summary' ),
            array( $this, 'max_tokens_field_callback' ),
            'hd-soft-ai-summary',
            'hdsoft_ai_summary_api_section'
        );

        // Prompt Style Field
        add_settings_field(
            'prompt_style',
            __( 'Summary Style', 'hd-soft-ai-summary' ),
            array( $this, 'prompt_style_field_callback' ),
            'hd-soft-ai-summary',
            'hdsoft_ai_summary_api_section'
        );

        // Pro settings are handled in pro/class-pro-admin.php

        // Display Settings Section
        add_settings_section(
            'hdsoft_ai_summary_display_section',
            __( 'Display Settings', 'hd-soft-ai-summary' ),
            array( $this, 'display_section_callback' ),
            'hd-soft-ai-summary'
        );


        // Append Position Field
        add_settings_field(
            'append_position',
            __( 'Auto Append Position', 'hd-soft-ai-summary' ),
            array( $this, 'append_position_field_callback' ),
            'hd-soft-ai-summary',
            'hdsoft_ai_summary_display_section'
        );

        // Allow Pro to add additional fields via action
        do_action( 'hdsoft_ai_summary_register_settings_fields' );
    }

    /**
     * Test API key directly
     *
     * @param string $api_key API key to test.
     * @return array|WP_Error
     */
    private function test_api_key( $api_key ) {
        if ( empty( $api_key ) ) {
            return new \WP_Error( 'no_api_key', __( 'OpenRouter API key is required.', 'hd-soft-ai-summary' ) );
        }

        // Make direct API request to test the key - use auth endpoint for proper key validation
        $url = 'https://openrouter.ai/api/v1/auth/key';
        
        $headers = array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
            'HTTP-Referer'  => home_url(),
            'X-Title'       => get_bloginfo( 'name' ) . ' - HD SofT AI Summary',
        );

        $args = array(
            'method'  => 'GET',
            'headers' => $headers,
            'timeout' => 30,
        );

        $response = wp_remote_request( $url, $args );
        
        if ( is_wp_error( $response ) ) {
            return new \WP_Error( 'network_error', 'Network error: ' . $response->get_error_message() );
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        // Check HTTP status codes first - this is the key test
        if ( $response_code < 200 || $response_code >= 300 ) {
            $error_message = 'HTTP ' . $response_code;
            
            if ( $data && isset( $data['error']['message'] ) ) {
                $error_message = $data['error']['message'];
            }
            
            return new \WP_Error( 'http_error', $error_message );
        }

        // Check for API-level errors in response body
        if ( isset( $data['error'] ) ) {
            $error_message = isset( $data['error']['message'] ) ? $data['error']['message'] : 'API error occurred';
            return new \WP_Error( 'api_error', $error_message );
        }

        // /auth/key endpoint returns key info, not models - just check if we got valid response
        if ( ! isset( $data['data'] ) ) {
            return new \WP_Error( 'invalid_key', 'Invalid API key - authentication failed' );
        }

        // Now get models count for display - but don't fail if this fails
        $models_count = 0;
        $models_response = wp_remote_request( 'https://openrouter.ai/api/v1/models', array(
            'method'  => 'GET',
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
                'HTTP-Referer'  => home_url(),
                'X-Title'       => get_bloginfo( 'name' ) . ' - HD SofT AI Summary',
            ),
            'timeout' => 10,
        ) );
        
        if ( ! is_wp_error( $models_response ) ) {
            $models_body = wp_remote_retrieve_body( $models_response );
            $models_data = json_decode( $models_body, true );
            if ( isset( $models_data['data'] ) && is_array( $models_data['data'] ) ) {
                $models_count = count( $models_data['data'] );
            }
        }

        return array(
            'success'      => true,
            'model_info'   => null, // We'll get this when loading models
            'total_models' => $models_count,
            'debug_info'   => 'Key valid, ' . $models_count . ' models available',
        );
    }

    /**
     * Sanitize settings
     *
     * @param array $input Input settings.
     * @return array
     */
    public function sanitize_settings( $input ) {
        $sanitized = array();

        // Handle checkbox - false when not checked (not sent in form)
        $auto_generate = isset( $input['auto_generate'] ) ? (bool) $input['auto_generate'] : false;
        $sanitized['auto_generate'] = $auto_generate;

        if ( isset( $input['append_position'] ) ) {
            $allowed_positions = array( 'before', 'after', 'manual' );
            $sanitized['append_position'] = in_array( $input['append_position'], $allowed_positions, true ) 
                ? $input['append_position'] 
                : 'after';
        }

        if ( isset( $input['model_name'] ) ) {
            $sanitized['model_name'] = sanitize_text_field( $input['model_name'] );
        }

        if ( isset( $input['max_tokens'] ) ) {
            $sanitized['max_tokens'] = intval( $input['max_tokens'] );
        }

        if ( isset( $input['prompt_style'] ) ) {
            $allowed_styles = array( 'narrative', 'structured', 'executive' );
            $prompt_style = in_array( $input['prompt_style'], $allowed_styles, true )
                ? $input['prompt_style']
                : 'narrative';
            $sanitized['prompt_style'] = $prompt_style;
        }

        if ( isset( $input['summary_title'] ) ) {
            $summary_title = trim( sanitize_text_field( $input['summary_title'] ) );
            $summary_title = ! empty( $summary_title ) ? $summary_title : 'Summary';
            $sanitized['summary_title'] = $summary_title;
        }

        do_action( 'hdsoft_ai_summary_settings_updated', $sanitized );

        return $sanitized;
    }

    /**
     * Settings page
     */
    public function settings_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'hd-soft-ai-summary' ) );
        }

        include HDSOFT_AI_SUMMARY_PLUGIN_DIR . 'admin/partials/settings-page.php';
    }

    /**
     * API section callback
     */
    public function api_section_callback() {
        echo '<p>' . esc_html__( 'Configure your OpenRouter API settings to enable AI summary generation.', 'hd-soft-ai-summary' ) . '</p>';
        echo '<p><a href="https://openrouter.ai/" target="_blank">' . esc_html__( 'Get your OpenRouter API key here', 'hd-soft-ai-summary' ) . '</a></p>';
    }

    /**
     * API key field callback
     */
    public function api_key_field_callback() {
        $api_key = get_option( 'hdsoft_ai_summary_openrouter_api_key', '' );
        
        // Safe API key masking with bounds checking
        $masked_key = '';
        if ( ! empty( $api_key ) ) {
            $key_length = strlen( $api_key );
            if ( $key_length > 8 ) {
                $repeat_count = max( 0, $key_length - 8 );
                $masked_key = substr( $api_key, 0, 8 ) . str_repeat( '*', $repeat_count );
            } elseif ( $key_length > 4 ) {
                $repeat_count = max( 0, $key_length - 4 );
                $masked_key = substr( $api_key, 0, 4 ) . str_repeat( '*', $repeat_count );
            } else {
                $masked_key = str_repeat( '*', max( 0, $key_length ) );
            }
        }
        
        echo '<input type="password" id="openrouter_api_key" name="hdsoft_ai_summary_openrouter_api_key" value="' . esc_attr( $api_key ) . '" class="regular-text" />';
        
        if ( ! empty( $masked_key ) ) {
            /* translators: %s: masked API key prefix */
            echo '<p class="description">' . sprintf( esc_html__( 'Current key: %s', 'hd-soft-ai-summary' ), esc_html( $masked_key ) ) . '</p>';
        }
        
        echo '<p class="description">' . esc_html__( 'Your OpenRouter API key. This is stored securely and never transmitted to plugin developers.', 'hd-soft-ai-summary' ) . '</p>';
        echo '<button type="button" id="test-connection" class="button button-secondary" style="margin-top: 10px;">' . esc_html__( 'Test Connection', 'hd-soft-ai-summary' ) . '</button>';
        echo '<div id="connection-result" style="margin-top: 10px;"></div>';
    }

    /**
     * Model field callback
     */
    public function model_field_callback() {
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $current_model = isset( $settings['model_name'] ) ? $settings['model_name'] : 'anthropic/claude-3.5-sonnet';
        
        // Get saved models from transient/option
        $saved_models = get_transient( 'hdsoft_ai_summary_models' );
        
        echo '<div>';
        
        // Simple select dropdown
        echo '<select id="model_name" name="hdsoft_ai_summary_settings[model_name]" class="regular-text">';
        
        // Default/current model option
        echo '<option value="' . esc_attr( $current_model ) . '" selected>' . esc_html( $current_model ) . '</option>';
        
        // Add saved models if available
        if ( $saved_models && is_array( $saved_models ) ) {
            foreach ( $saved_models as $model_id => $model_data ) {
                if ( $model_id !== $current_model ) {
                    $model_name = isset( $model_data['name'] ) ? $model_data['name'] : $model_id;
                    echo '<option value="' . esc_attr( $model_id ) . '">' . esc_html( $model_name . ' (' . $model_id . ')' ) . '</option>';
                }
            }
        }
        
        echo '</select>';
        
        echo '<p>';
        echo '<button type="button" id="load-models" class="button button-secondary">' . esc_html__( 'Load Available Models', 'hd-soft-ai-summary' ) . '</button>';
        echo '</p>';
        
        echo '<p class="description">' . esc_html__( 'Select an AI model for summary generation. Click "Load Available Models" to refresh the list from OpenRouter.', 'hd-soft-ai-summary' ) . '</p>';
        
        echo '</div>';
    }

    /**
     * Max tokens field callback
     */
    public function max_tokens_field_callback() {
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $max_tokens = isset( $settings['max_tokens'] ) ? $settings['max_tokens'] : 300;
        
        echo '<input type="number" id="max_tokens" name="hdsoft_ai_summary_settings[max_tokens]" value="' . esc_attr( $max_tokens ) . '" class="small-text" />';
        echo '<p class="description">' . esc_html__( 'Maximum number of tokens for the generated summary. Estimated words: ', 'hd-soft-ai-summary' ) . '<span id="word-estimate">' . intval( min( 80, max( 30, $max_tokens * 0.3 ) ) ) . '</span></p>';
    }

    /**
     * Prompt style field callback
     */
    public function prompt_style_field_callback() {
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $prompt_style = isset( $settings['prompt_style'] ) ? $settings['prompt_style'] : 'narrative';
        $is_pro = defined( 'HDSUM_PRO' ) && HDSUM_PRO;
        
        echo '<select id="prompt_style" name="hdsoft_ai_summary_settings[prompt_style]">';
        echo '<option value="narrative"' . selected( $prompt_style, 'narrative', false ) . '>' . esc_html__( 'Narrative Summary', 'hd-soft-ai-summary' ) . '</option>';
        
        if ( $is_pro ) {
            echo '<option value="structured"' . selected( $prompt_style, 'structured', false ) . '>' . esc_html__( 'Structured Bullets', 'hd-soft-ai-summary' ) . '</option>';
            echo '<option value="executive"' . selected( $prompt_style, 'executive', false ) . '>' . esc_html__( 'Executive Brief', 'hd-soft-ai-summary' ) . '</option>';
        }
        
        echo '</select>';
        
        echo '<p class="description">' . esc_html__( 'Choose the style of AI-generated summaries.', 'hd-soft-ai-summary' ) . '</p>';
    }

    /**
     * Generation section callback
     */
    public function generation_section_callback() {
        echo '<p>' . esc_html__( 'Configure when and how summaries are generated.', 'hd-soft-ai-summary' ) . '</p>';
    }

    /**
     * Auto generate field callback
     */
    public function auto_generate_field_callback() {
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $auto_generate = isset( $settings['auto_generate'] ) ? $settings['auto_generate'] : true;
        
        echo '<label for="auto_generate">';
        echo '<input type="checkbox" id="auto_generate" name="hdsoft_ai_summary_settings[auto_generate]" value="1"' . checked( $auto_generate, true, false ) . ' />';
        echo ' ' . esc_html__( 'Automatically generate summaries when posts are saved', 'hd-soft-ai-summary' );
        echo '</label>';
        
        echo '<p class="description">' . esc_html__( 'When enabled, summaries will be generated automatically when you publish or update posts.', 'hd-soft-ai-summary' ) . '</p>';
    }

    /**
     * Display section callback
     */
    public function display_section_callback() {
        echo '<p>' . esc_html__( 'Configure how summaries are displayed on your website.', 'hd-soft-ai-summary' ) . '</p>';
    }


    /**
     * Append position field callback
     */
    public function append_position_field_callback() {
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $append_position = isset( $settings['append_position'] ) ? $settings['append_position'] : 'after';
        
        echo '<select id="append_position" name="hdsoft_ai_summary_settings[append_position]">';
        echo '<option value="before"' . selected( $append_position, 'before', false ) . '>' . esc_html__( 'Before content', 'hd-soft-ai-summary' ) . '</option>';
        echo '<option value="after"' . selected( $append_position, 'after', false ) . '>' . esc_html__( 'After content', 'hd-soft-ai-summary' ) . '</option>';
        echo '<option value="manual"' . selected( $append_position, 'manual', false ) . '>' . esc_html__( 'Manual only (shortcode)', 'hd-soft-ai-summary' ) . '</option>';
        echo '</select>';
        echo '<p class="description">' . esc_html__( 'Choose where to automatically display summaries, or select manual to use only the [hdsoft_ai_summary] shortcode.', 'hd-soft-ai-summary' ) . '</p>';
    }

    /**
     * Summary title field callback
     */
    public function summary_title_field_callback() {
        $settings = get_option( 'hdsoft_ai_summary_settings', array() );
        $summary_title = isset( $settings['summary_title'] ) ? $settings['summary_title'] : 'Summary';
        
        echo '<input type="text" id="summary_title" name="hdsoft_ai_summary_settings[summary_title]" value="' . esc_attr( $summary_title ) . '" class="regular-text" placeholder="' . esc_attr__( 'Summary', 'hd-soft-ai-summary' ) . '" />';
        
        echo '<p class="description">' . esc_html__( 'Default title for the summary (used in AI prompt). Value must not be empty.', 'hd-soft-ai-summary' ) . '</p>';
    }

    /**
     * Enqueue admin scripts
     *
     * @param string $hook Current admin page hook.
     */
    public function enqueue_admin_scripts( $hook ) {
        if ( 'settings_page_hd-soft-ai-summary' !== $hook ) {
            return;
        }

        wp_enqueue_script(
            'hdsoft-ai-summary-admin',
            HDSOFT_AI_SUMMARY_PLUGIN_URL . 'admin/js/admin.js',
            array( 'jquery' ),
            HDSOFT_AI_SUMMARY_VERSION,
            true
        );

        wp_localize_script(
            'hdsoft-ai-summary-admin',
            'hdsoft_ai_summary_admin',
            array(
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce'    => wp_create_nonce( 'hdsoft_ai_summary_admin_nonce' ),
                'strings'  => array(
                    'testing'    => __( 'Testing connection...', 'hd-soft-ai-summary' ),
                    'success'    => __( 'Connection successful!', 'hd-soft-ai-summary' ),
                    'error'      => __( 'Connection failed:', 'hd-soft-ai-summary' ),
                ),
            )
        );

        wp_enqueue_style(
            'hdsoft-ai-summary-admin',
            HDSOFT_AI_SUMMARY_PLUGIN_URL . 'admin/css/admin.css',
            array(),
            HDSOFT_AI_SUMMARY_VERSION
        );
    }

    /**
     * AJAX test connection
     */
    public function ajax_test_connection() {
        check_ajax_referer( 'hdsoft_ai_summary_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions.', 'hd-soft-ai-summary' ) );
        }

        // Get API key from POST data (form field) or fallback to saved option
        $api_key = '';
        if ( isset( $_POST['api_key'] ) && ! empty( $_POST['api_key'] ) ) {
            $api_key = sanitize_text_field( wp_unslash( $_POST['api_key'] ) );
        } else {
            $api_key = get_option( 'hdsoft_ai_summary_openrouter_api_key', '' );
        }

        if ( empty( $api_key ) ) {
            wp_send_json_error( array(
                'message' => __( 'OpenRouter API key is not configured.', 'hd-soft-ai-summary' ),
            ) );
        }

        // Temporarily override the API key for testing
        $plugin = Plugin::get_instance();
        
        // Create a temporary OpenRouter instance with the test API key
        $temp_openrouter = new OpenRouter();
        
        // We need to test the connection with the provided key
        // Since the OpenRouter class uses get_option(), we'll need to modify the test
        $result = $this->test_api_key( $api_key );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array(
                'message' => $result->get_error_message(),
            ) );
        }

        wp_send_json_success( $result );
    }


    /**
     * AJAX get models
     */
    public function ajax_get_models() {
        check_ajax_referer( 'hdsoft_ai_summary_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have sufficient permissions.', 'hd-soft-ai-summary' ) );
        }

        // Get API key from POST data (form field) or fallback to saved option
        $api_key = '';
        if ( isset( $_POST['api_key'] ) && ! empty( $_POST['api_key'] ) ) {
            $api_key = sanitize_text_field( wp_unslash( $_POST['api_key'] ) );
        } else {
            $api_key = get_option( 'hdsoft_ai_summary_openrouter_api_key', '' );
        }

        if ( empty( $api_key ) ) {
            wp_send_json_error( array(
                'message' => __( 'OpenRouter API key is not configured.', 'hd-soft-ai-summary' ),
            ) );
        }

        // Get models using the provided API key
        $models = $this->get_models_with_key( $api_key );

        if ( is_wp_error( $models ) ) {
            wp_send_json_error( array(
                'message' => $models->get_error_message(),
            ) );
        }

        // Add recommended models and format for frontend
        $formatted_models = array();
        $recommended_models = array(
            'anthropic/claude-3.5-sonnet' => true,
            'google/gemini-1.5-flash' => true,
            'meta-llama/llama-3.1-70b-instruct' => true,
        );

        foreach ( $models as $model_id => $model_data ) {
            $formatted_models[] = array(
                'id'          => $model_id,
                'name'        => $model_data['name'],
                'description' => $model_data['description'],
                'recommended' => isset( $recommended_models[ $model_id ] ),
                'pricing'     => $model_data['pricing'],
            );
        }

        // Sort: recommended first, then alphabetically
        usort( $formatted_models, function( $a, $b ) {
            if ( $a['recommended'] && ! $b['recommended'] ) {
                return -1;
            }
            if ( ! $a['recommended'] && $b['recommended'] ) {
                return 1;
            }
            return strcmp( $a['name'], $b['name'] );
        });

        wp_send_json_success( array(
            'models' => $formatted_models,
            'total'  => count( $formatted_models ),
        ) );
    }

    /**
     * Get models with specific API key
     *
     * @param string $api_key API key to use.
     * @return array|WP_Error
     */
    private function get_models_with_key( $api_key ) {
        if ( empty( $api_key ) ) {
            return new \WP_Error( 'no_api_key', __( 'OpenRouter API key is required.', 'hd-soft-ai-summary' ) );
        }

        // Make direct API request
        $url = 'https://openrouter.ai/api/v1/models';
        
        $headers = array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
            'HTTP-Referer'  => home_url(),
            'X-Title'       => get_bloginfo( 'name' ) . ' - HD SofT AI Summary',
        );

        $args = array(
            'method'  => 'GET',
            'headers' => $headers,
            'timeout' => 30,
        );

        $response = wp_remote_request( $url, $args );

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );

        // Check HTTP status codes
        if ( $response_code < 200 || $response_code >= 300 ) {
            $error_message = __( 'API request failed: ', 'hd-soft-ai-summary' ) . $response_code;
            
            if ( $data && isset( $data['error']['message'] ) ) {
                $error_message = $data['error']['message'];
            }
            
            return new \WP_Error( 'api_error', $error_message );
        }

        // Check for API-level errors in response body
        if ( isset( $data['error'] ) ) {
            $error_message = isset( $data['error']['message'] ) ? $data['error']['message'] : __( 'API error occurred.', 'hd-soft-ai-summary' );
            return new \WP_Error( 'api_error', $error_message );
        }

        // Check if we got models data
        if ( ! isset( $data['data'] ) || ! is_array( $data['data'] ) || empty( $data['data'] ) ) {
            return new \WP_Error( 'no_models', __( 'No models returned from API. Check your API key.', 'hd-soft-ai-summary' ) );
        }

        // Filter and format models for dropdown
        $models = array();
        foreach ( $data['data'] as $model ) {
            // Skip models that don't support chat completions
            if ( ! isset( $model['id'] ) ) {
                continue;
            }

            $models[ $model['id'] ] = array(
                'name'        => $model['name'] ?? $model['id'],
                'description' => $model['description'] ?? '',
                'pricing'     => $model['pricing'] ?? array(),
            );
        }

        return $models;
    }
}
