<?php
/**
 * Chat Handler - REST API endpoints for the chatbot
 *
 * @package ContentReply_AI
 */

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

class WPSC_Chat_Handler {

    public function __construct() {
        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
    }

    /**
     * Register REST API routes
     */
    public function register_routes() {
        register_rest_route( 'wpsc/v1', '/chat', array(
            'methods'             => 'POST',
            'callback'            => array( $this, 'handle_chat' ),
            'permission_callback' => '__return_true',
            'args'                => array(
                'message' => array(
                    'required'          => true,
                    'type'              => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                ),
                'session_id' => array(
                    'required'          => true,
                    'type'              => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                ),
                'page_url' => array(
                    'required'          => false,
                    'type'              => 'string',
                    'sanitize_callback' => 'esc_url_raw',
                ),
            ),
        ) );

        register_rest_route( 'wpsc/v1', '/status', array(
            'methods'             => 'GET',
            'callback'            => array( $this, 'get_status' ),
            'permission_callback' => '__return_true',
        ) );
    }

    /**
     * Handle incoming chat message
     *
     * @param WP_REST_Request $request The request object.
     * @return WP_REST_Response
     */
    public function handle_chat( $request ) {
        if ( ! get_option( 'wpsc_enabled', true ) ) {
            return new WP_REST_Response( array(
                'success' => false,
                'message' => 'Chat is currently unavailable.',
            ), 503 );
        }

        $message    = $request->get_param( 'message' );
        $session_id = $request->get_param( 'session_id' );
        $page_url   = $request->get_param( 'page_url' );

        if ( $this->is_rate_limited( $session_id ) ) {
            return new WP_REST_Response( array(
                'success' => false,
                'message' => 'Too many messages. Please try again later.',
            ), 429 );
        }

        if ( get_option( 'wpsc_demo_mode', false ) ) {
            $demo_response = $this->get_demo_response( $message );
            $this->save_conversation( $session_id, $message, $demo_response['message'], array(), $page_url );
            return new WP_REST_Response( $demo_response, 200 );
        }

        $indexer = new WPSC_Indexer();
        $relevant_chunks = $indexer->search_relevant_content( $message, 5 );

        $ai_provider = new WPSC_AI_Provider();
        $response = $ai_provider->get_response( $message, $relevant_chunks );

        $sources = array();
        if ( ! empty( $relevant_chunks ) ) {
            foreach ( $relevant_chunks as $chunk ) {
                $sources[ esc_url( $chunk->post_url ) ] = sanitize_text_field( $chunk->post_title );
            }
        }

        $this->save_conversation( $session_id, $message, $response['message'], $sources, $page_url );

        return new WP_REST_Response( array(
            'success' => $response['success'],
            'message' => $response['message'],
            'sources' => $sources,
        ), 200 );
    }

    /**
     * Get chatbot status
     *
     * @param WP_REST_Request $request The request object.
     * @return WP_REST_Response
     */
    public function get_status( $request ) {
        return new WP_REST_Response( array(
            'enabled'    => (bool) get_option( 'wpsc_enabled', true ),
            'configured' => ! empty( get_option( 'wpsc_api_key', '' ) ),
            'bot_name'   => sanitize_text_field( get_option( 'wpsc_bot_name', 'Support Bot' ) ),
            'welcome'    => sanitize_text_field( get_option( 'wpsc_welcome_message', 'Hi! How can I help you today?' ) ),
        ), 200 );
    }

    /**
     * Save conversation to database
     *
     * @param string $session_id  Session identifier.
     * @param string $user_message  User's message.
     * @param string $bot_response  Bot's response.
     * @param array  $sources  Source pages.
     * @param string $page_url  Page where chat occurred.
     */
    private function save_conversation( $session_id, $user_message, $bot_response, $sources, $page_url ) {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert(
            $wpdb->prefix . 'wpsc_conversations',
            array(
                'session_id'   => sanitize_text_field( $session_id ),
                'user_message' => sanitize_textarea_field( $user_message ),
                'bot_response' => sanitize_textarea_field( $bot_response ),
                'sources'      => wp_json_encode( $sources ),
                'created_at'   => current_time( 'mysql' ),
                'ip_address'   => sanitize_text_field( $this->get_client_ip() ),
                'page_url'     => esc_url_raw( $page_url ),
            ),
            array( '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
        );
    }

    /**
     * Check rate limiting
     *
     * @param string $session_id Session identifier.
     * @return bool Whether rate limited.
     */
    private function is_rate_limited( $session_id ) {
        global $wpdb;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $count = $wpdb->get_var(
            $wpdb->prepare(
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                "SELECT COUNT(*) FROM `" . $wpdb->prefix . "wpsc_conversations` WHERE session_id = %s AND created_at > DATE_SUB(NOW(), INTERVAL 1 HOUR)",
                $session_id
            )
        );

        return (int) $count >= 20;
    }

    /**
     * Get client IP address
     *
     * @return string Client IP.
     */
    private function get_client_ip() {
        $ip = '';
        if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
            $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) );
            $ip_parts = explode( ',', $ip );
            $ip = trim( $ip_parts[0] );
        } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
            $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
        }
        return $ip;
    }

    /**
     * Demo mode - returns test responses without API call
     *
     * @param string $message User message.
     * @return array Response array.
     */
    private function get_demo_response( $message ) {
        $message_lower = strtolower( $message );

        $responses = array(
            'hello'    => 'Hello! Welcome to our site. How can I help you today? (Demo Mode)',
            'hi'       => 'Hi there! What can I assist you with? (Demo Mode)',
            'price'    => 'Our pricing varies by product. Please check our pricing page for details. (Demo Mode)',
            'contact'  => 'You can reach us through our contact page or email us directly. (Demo Mode)',
            'hours'    => 'We are available Monday to Friday, 9am to 5pm. (Demo Mode)',
            'shipping' => 'We offer standard and express shipping options. Delivery times vary by location. (Demo Mode)',
            'return'   => 'We have a 30-day return policy for unused items. (Demo Mode)',
        );

        foreach ( $responses as $keyword => $response ) {
            if ( strpos( $message_lower, $keyword ) !== false ) {
                return array(
                    'success' => true,
                    'message' => $response,
                    'sources' => array(),
                );
            }
        }

        return array(
            'success' => true,
            'message' => sprintf(
                /* translators: %s: user's question */
                esc_html__( 'Thank you for your question about "%s". This is a demo response. Once you add your API key, the bot will answer using your actual site content. (Demo Mode)', 'contentreply-ai' ),
                esc_html( $message )
            ),
            'sources' => array(),
        );
    }
}
