<?php
/**
 * Admin - Settings page and chat history
 *
 * @package ContentReply_AI
 */

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

class WPSC_Admin {

    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_assets' ) );
        add_action( 'wp_ajax_wpsc_reindex', array( $this, 'ajax_reindex' ) );
        add_action( 'wp_ajax_wpsc_clear_history', array( $this, 'ajax_clear_history' ) );
    }

    /**
     * Add menu pages
     */
    public function add_admin_menu() {
        add_menu_page(
            __( 'ContentReply AI', 'contentreply-ai' ),
            __( 'ContentReply AI', 'contentreply-ai' ),
            'manage_options',
            'contentreply-ai',
            array( $this, 'render_settings_page' ),
            WPSC_PLUGIN_URL . 'assets/menu-icon.png',
            80
        );

        add_submenu_page(
            'contentreply-ai',
            __( 'Settings', 'contentreply-ai' ),
            __( 'Settings', 'contentreply-ai' ),
            'manage_options',
            'contentreply-ai',
            array( $this, 'render_settings_page' )
        );

        add_submenu_page(
            'contentreply-ai',
            __( 'Chat History', 'contentreply-ai' ),
            __( 'Chat History', 'contentreply-ai' ),
            'manage_options',
            'contentreply-ai-history',
            array( $this, 'render_history_page' )
        );
    }

    /**
     * Register plugin settings
     */
    public function register_settings() {
        register_setting( 'wpsc_settings', 'wpsc_api_key', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_ai_provider', array(
            'type'              => 'string',
            'sanitize_callback' => array( $this, 'sanitize_provider' ),
        ) );
        register_setting( 'wpsc_settings', 'wpsc_ai_model', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_widget_position', array(
            'type'              => 'string',
            'sanitize_callback' => array( $this, 'sanitize_position' ),
        ) );
        register_setting( 'wpsc_settings', 'wpsc_primary_color', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_welcome_message', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_bot_name', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_fallback_message', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_contact_url', array(
            'type'              => 'string',
            'sanitize_callback' => 'esc_url_raw',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_post_types', array(
            'type'              => 'array',
            'sanitize_callback' => array( $this, 'sanitize_post_types' ),
        ) );
        register_setting( 'wpsc_settings', 'wpsc_max_tokens', array(
            'type'              => 'integer',
            'sanitize_callback' => 'absint',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_show_on_mobile', array(
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_auto_index', array(
            'type'              => 'string',
            'sanitize_callback' => array( $this, 'sanitize_auto_index' ),
        ) );
        register_setting( 'wpsc_settings', 'wpsc_enabled', array(
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
        ) );
        register_setting( 'wpsc_settings', 'wpsc_demo_mode', array(
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
        ) );
    }

    /**
     * Sanitize provider option
     */
    public function sanitize_provider( $value ) {
        $allowed = array( 'openai', 'gemini', 'groq' );
        return in_array( $value, $allowed, true ) ? $value : 'groq';
    }

    /**
     * Sanitize position option
     */
    public function sanitize_position( $value ) {
        $allowed = array( 'bottom-right', 'bottom-left' );
        return in_array( $value, $allowed, true ) ? $value : 'bottom-right';
    }

    /**
     * Sanitize post types array
     */
    public function sanitize_post_types( $value ) {
        if ( ! is_array( $value ) ) {
            return array( 'page', 'post' );
        }
        return array_map( 'sanitize_key', $value );
    }

    /**
     * Sanitize auto index option
     */
    public function sanitize_auto_index( $value ) {
        $allowed = array( 'disabled', 'daily', 'weekly' );
        $value = in_array( $value, $allowed, true ) ? $value : 'disabled';

        // Update cron schedule based on selection
        wp_clear_scheduled_hook( 'wpsc_auto_index_content' );

        if ( $value !== 'disabled' ) {
            $schedule = ( $value === 'daily' ) ? 'daily' : 'weekly';
            wp_schedule_event( time(), $schedule, 'wpsc_auto_index_content' );
        }

        return $value;
    }

    /**
     * Enqueue admin CSS/JS
     */
    public function enqueue_admin_assets( $hook ) {
        if ( strpos( $hook, 'contentreply-ai' ) === false ) {
            return;
        }
        wp_enqueue_style( 'wpsc-admin', WPSC_PLUGIN_URL . 'admin/admin.css', array(), WPSC_VERSION );
        wp_enqueue_script( 'wpsc-admin', WPSC_PLUGIN_URL . 'admin/admin.js', array( 'jquery' ), WPSC_VERSION, true );
        wp_localize_script( 'wpsc-admin', 'wpscAdmin', array(
            'ajaxUrl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'wpsc_admin_nonce' ),
        ) );
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        include WPSC_PLUGIN_DIR . 'admin/admin-page.php';
    }

    /**
     * Render chat history page
     */
    public function render_history_page() {
        global $wpdb;

        $per_page = 20;
        $current_page = isset( $_GET['paged'] ) ? max( 1, absint( $_GET['paged'] ) ) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $offset = ( $current_page - 1 ) * $per_page;

        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $total = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM `" . $wpdb->prefix . "wpsc_conversations`"
        );
        $conversations = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT * FROM `" . $wpdb->prefix . "wpsc_conversations` ORDER BY created_at DESC LIMIT %d OFFSET %d",
                $per_page,
                $offset
            )
        );
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare

        $total_pages = ceil( $total / $per_page );
        ?>
        <div class="wrap wpsc-wrap">
            <h1><?php esc_html_e( 'Chat History', 'contentreply-ai' ); ?></h1>
            <p class="description">
                <?php
                /* translators: %d: total number of conversations */
                printf( esc_html__( 'Total conversations: %d', 'contentreply-ai' ), (int) $total );
                ?>
            </p>

            <?php if ( $total > 0 ) : ?>
            <button id="wpsc-clear-history" class="button button-secondary" style="margin-bottom:16px;">
                <?php esc_html_e( 'Clear All History', 'contentreply-ai' ); ?>
            </button>

            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width:140px;"><?php esc_html_e( 'Date', 'contentreply-ai' ); ?></th>
                        <th style="width:100px;"><?php esc_html_e( 'Session', 'contentreply-ai' ); ?></th>
                        <th><?php esc_html_e( 'User Message', 'contentreply-ai' ); ?></th>
                        <th><?php esc_html_e( 'Bot Response', 'contentreply-ai' ); ?></th>
                        <th style="width:180px;"><?php esc_html_e( 'Page', 'contentreply-ai' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $conversations as $chat ) : ?>
                    <tr>
                        <td><?php echo esc_html( $chat->created_at ); ?></td>
                        <td><code><?php echo esc_html( substr( $chat->session_id, 0, 8 ) ); ?></code></td>
                        <td><?php echo esc_html( wp_trim_words( $chat->user_message, 15 ) ); ?></td>
                        <td><?php echo esc_html( wp_trim_words( $chat->bot_response, 20 ) ); ?></td>
                        <td>
                            <?php if ( $chat->page_url ) : ?>
                                <a href="<?php echo esc_url( $chat->page_url ); ?>" target="_blank"><?php esc_html_e( 'View', 'contentreply-ai' ); ?></a>
                            <?php else : ?>
                                &mdash;
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ( $total_pages > 1 ) : ?>
            <div class="tablenav bottom">
                <div class="tablenav-pages">
                    <?php
                    echo wp_kses_post( paginate_links( array(
                        'base'    => add_query_arg( 'paged', '%#%' ),
                        'format'  => '',
                        'current' => $current_page,
                        'total'   => $total_pages,
                    ) ) );
                    ?>
                </div>
            </div>
            <?php endif; ?>

            <?php else : ?>
            <p><?php esc_html_e( 'No conversations yet.', 'contentreply-ai' ); ?></p>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * AJAX: Reindex content
     */
    public function ajax_reindex() {
        check_ajax_referer( 'wpsc_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Unauthorized' );
        }

        $indexer = new WPSC_Indexer();
        $indexer->index_all_content();
        $count = $indexer->get_index_count();

        wp_send_json_success( array(
            'message' => sprintf( 'Indexing complete. %d content chunks indexed.', $count ),
            'count'   => $count,
        ) );
    }

    /**
     * AJAX: Clear chat history
     */
    public function ajax_clear_history() {
        check_ajax_referer( 'wpsc_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Unauthorized' );
        }

        global $wpdb;
        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $wpdb->query( "TRUNCATE TABLE `" . $wpdb->prefix . "wpsc_conversations`" );
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        wp_send_json_success( array( 'message' => 'Chat history cleared.' ) );
    }
}
