<?php
/**
 * AI Tool Token Trait
 *
 * @package SAAI\Traits
 */

namespace SAAI\Traits;

defined( 'ABSPATH' ) || exit;

/**
 * AI Tool Token Trait
 *
 * This trait provides methods for generating and managing AI tool tokens.
 *
 * @since 1.0.8
 */
trait AI_Tool_Token_Trait {

    /**
     * Generate a temporary token for AI tool access.
     *
     * @since 1.0.8
     * @return string Temporary token.
     */
    private function generate_temp_token() {
        $user_id = get_current_user_id();

        // Create session identifier for token lookup.
        $session_id = $this->get_session_identifier( $user_id );

        // Check if a valid token already exists for this session.
        $session_data = get_transient( "saai_session_$session_id" );
        if ( $session_data && isset( $session_data['token'] ) ) {
            return $session_data['token'];
        }

        // Generate new token.
        $token = wp_generate_password( 32, false );

        // Create session data for both logged-in users and guests.
        $session_data = array(
            'token'      => $token,
            'user_id'    => $user_id,
            'is_guest'   => 0 === $user_id,
            'ip_address' => $this->get_client_ip(),
            'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
            'created_at' => time(),
            'session_id' => $session_id,
        );

        // Store session data with 30-minute expiration.
        set_transient( "saai_session_$session_id", $session_data, 30 * MINUTE_IN_SECONDS );

        return $token;
    }

    /**
     * Get client IP address with support for various proxy configurations.
     *
     * @since 1.0.8
     * @return string Client IP address.
     */
    private function get_client_ip() {
        $ip_keys = array(
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_REAL_IP',
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR',
        );

        foreach ( $ip_keys as $key ) {
            if ( ! empty( $_SERVER[ $key ] ) ) {
                $ip = sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) );

                // Handle comma-separated IPs (from proxies).
                if ( strpos( $ip, ',' ) !== false ) {
                    $ip = trim( explode( ',', $ip )[0] );
                }

                // Validate IP address.
                if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) {
                    return $ip;
                }
            }
        }

        // Fallback to REMOTE_ADDR even if it's private/reserved.
        return isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '127.0.0.1';
    }

    /**
     * Get session identifier for token management.
     *
     * @since 1.0.8
     * @param int $user_id The user ID (0 for guests).
     * @return string Session identifier.
     */
    private function get_session_identifier( $user_id ) {
        if ( $user_id > 0 ) {
            // For logged-in users, use their user ID.
            return "user_$user_id";
        }

        // For guest users, create identifier based on IP and user agent.
        $ip         = $this->get_client_ip();
        $user_agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';

        return 'guest_' . md5( $ip . '|' . $user_agent );
    }

    /**
     * Generate the full AI tool token in the format required.
     *
     * @since 1.0.8
     * @return string AI tool token in format: session_id:::token.
     */
    protected function generate_ai_tool_token() {
        $user_id = get_current_user_id();
        return sprintf( '%s:::%s', $this->get_session_identifier( $user_id ), $this->generate_temp_token() );
    }
}
