<?php
/**
 * Helper functions for BoostBot.
 *
 * @package BoostBot
 * @since   1.0.0
 */

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

/**
 * Get the BoostBot plugin instance.
 *
 * @return BoostBot|null
 */
function boostbot() {
    return BoostBot::get_instance();
}

/**
 * Get a setting value.
 *
 * @param string $key     The setting key.
 * @param mixed  $default Optional. Default value if not found.
 * @return mixed The setting value.
 */
function boostbot_get_setting( $key, $default = null ) {
    return BoostBot_Settings::get( $key, $default );
}

/**
 * Update a setting value.
 *
 * @param string $key   The setting key.
 * @param mixed  $value The value to set.
 * @return bool True on success, false on failure.
 */
function boostbot_update_setting( $key, $value ) {
    return BoostBot_Settings::set( $key, $value );
}

/**
 * Check if the chatbot is active.
 *
 * @return bool
 */
function boostbot_is_active() {
    return (bool) BoostBot_Settings::get( 'is_active', false );
}

/**
 * Check if debug mode is enabled.
 *
 * @return bool
 */
function boostbot_is_debug() {
    return defined( 'WP_DEBUG' ) && WP_DEBUG && BoostBot_Settings::get( 'debug_mode', false );
}

/**
 * Log a debug message.
 *
 * @param string $message The message to log.
 * @param array  $context Optional. Additional context.
 * @return void
 */
function boostbot_log( $message, $context = array() ) {
    if ( class_exists( 'BoostBot_Logger' ) ) {
        BoostBot_Logger::debug( $message, $context );
    }
}

/**
 * Log an error message.
 *
 * @param string $message The message to log.
 * @param array  $context Optional. Additional context.
 * @return void
 */
function boostbot_error( $message, $context = array() ) {
    if ( class_exists( 'BoostBot_Logger' ) ) {
        BoostBot_Logger::error( $message, $context );
    }
}

/**
 * Generate a unique ID.
 *
 * @param string $prefix Optional. Prefix for the ID. Default 'bb_'.
 * @return string The unique ID.
 */
function boostbot_generate_id( $prefix = 'bb_' ) {
    return $prefix . wp_generate_uuid4();
}

/**
 * Generate a visitor ID.
 *
 * @return string The visitor ID.
 */
function boostbot_generate_visitor_id() {
    return boostbot_generate_id( 'visitor_' );
}

/**
 * Generate a conversation ID.
 *
 * @return string The conversation ID.
 */
function boostbot_generate_conversation_id() {
    return boostbot_generate_id( 'conv_' );
}

/**
 * Get the current page context.
 *
 * @return array Page context data.
 */
function boostbot_get_page_context() {
    global $post;

    $context = array(
        'url'       => '',
        'title'     => '',
        'type'      => 'unknown',
        'id'        => 0,
        'excerpt'   => '',
        'is_single' => false,
        'is_page'   => false,
        'is_home'   => false,
        'is_shop'   => false,
    );

    if ( is_admin() ) {
        $context['type'] = 'admin';
        return $context;
    }

    $context['url']       = home_url( add_query_arg( array() ) );
    $context['is_home']   = is_front_page() || is_home();
    $context['is_single'] = is_single();
    $context['is_page']   = is_page();

    if ( is_singular() && $post ) {
        $context['title']   = get_the_title( $post );
        $context['type']    = get_post_type( $post );
        $context['id']      = $post->ID;
        $context['excerpt'] = get_the_excerpt( $post );
    } elseif ( is_archive() ) {
        $context['type']  = 'archive';
        $context['title'] = get_the_archive_title();
    } elseif ( is_search() ) {
        $context['type']  = 'search';
        $context['title'] = get_search_query();
    } elseif ( is_404() ) {
        $context['type']  = '404';
        $context['title'] = __( 'Page Not Found', 'boostbot' );
    }

    // WooCommerce specific
    if ( function_exists( 'is_shop' ) && is_shop() ) {
        $context['is_shop'] = true;
        $context['type']    = 'shop';
    }

    if ( function_exists( 'is_product' ) && is_product() ) {
        $context['type'] = 'product';
    }

    return $context;
}

/**
 * Check if WooCommerce is active.
 *
 * @return bool
 */
function boostbot_is_woocommerce_active() {
    return class_exists( 'WooCommerce' );
}

/**
 * Get the plugin URL for a specific path.
 *
 * @param string $path Optional. Path relative to plugin root.
 * @return string The full URL.
 */
function boostbot_url( $path = '' ) {
    return BOOSTBOT_PLUGIN_URL . ltrim( $path, '/' );
}

/**
 * Get the plugin directory path for a specific path.
 *
 * @param string $path Optional. Path relative to plugin root.
 * @return string The full path.
 */
function boostbot_path( $path = '' ) {
    return BOOSTBOT_PLUGIN_DIR . ltrim( $path, '/' );
}

/**
 * Format a number for display.
 *
 * @param int|float $number    The number to format.
 * @param int       $decimals  Optional. Number of decimal places. Default 0.
 * @return string The formatted number.
 */
function boostbot_format_number( $number, $decimals = 0 ) {
    return number_format_i18n( $number, $decimals );
}

/**
 * Format a date for display.
 *
 * @param string $date   The date string.
 * @param string $format Optional. The format. Default uses WordPress settings.
 * @return string The formatted date.
 */
function boostbot_format_date( $date, $format = '' ) {
    if ( empty( $format ) ) {
        $format = get_option( 'date_format' );
    }

    $timestamp = strtotime( $date );
    if ( ! $timestamp ) {
        return $date;
    }

    return date_i18n( $format, $timestamp );
}

/**
 * Format a datetime for display.
 *
 * @param string $datetime The datetime string.
 * @param string $format   Optional. The format. Default uses WordPress settings.
 * @return string The formatted datetime.
 */
function boostbot_format_datetime( $datetime, $format = '' ) {
    if ( empty( $format ) ) {
        $format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );
    }

    $timestamp = strtotime( $datetime );
    if ( ! $timestamp ) {
        return $datetime;
    }

    return date_i18n( $format, $timestamp );
}

/**
 * Get time ago string.
 *
 * @param string $datetime The datetime string.
 * @return string Human-readable time difference.
 */
function boostbot_time_ago( $datetime ) {
    $timestamp = strtotime( $datetime );
    if ( ! $timestamp ) {
        return $datetime;
    }

    return human_time_diff( $timestamp, current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'boostbot' );
}

/**
 * Truncate text to a specific length.
 *
 * @param string $text   The text to truncate.
 * @param int    $length The maximum length.
 * @param string $more   Optional. String to append if truncated. Default '...'.
 * @return string The truncated text.
 */
function boostbot_truncate( $text, $length, $more = '...' ) {
    if ( mb_strlen( $text ) <= $length ) {
        return $text;
    }

    return mb_substr( $text, 0, $length ) . $more;
}

/**
 * Check if the current user can manage BoostBot.
 *
 * @return bool
 */
function boostbot_user_can_manage() {
    return current_user_can( 'manage_options' ) || current_user_can( 'manage_boostbot' );
}

/**
 * Get the REST API URL for BoostBot.
 *
 * @param string $endpoint Optional. The endpoint path.
 * @return string The full REST API URL.
 */
function boostbot_rest_url( $endpoint = '' ) {
    return rest_url( 'boostbot/v1/' . ltrim( $endpoint, '/' ) );
}

/**
 * Check if this is a REST API request to BoostBot.
 *
 * @return bool
 */
function boostbot_is_rest_request() {
    if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) {
        return false;
    }

    $rest_prefix = trailingslashit( rest_get_url_prefix() );
    $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';

    return strpos( $request_uri, $rest_prefix . 'boostbot/' ) !== false;
}

/**
 * Send a JSON response and exit.
 *
 * @param mixed $data    The data to send.
 * @param int   $status  Optional. HTTP status code. Default 200.
 * @return void
 */
function boostbot_json_response( $data, $status = 200 ) {
    wp_send_json( $data, $status );
}

/**
 * Send a JSON error response and exit.
 *
 * @param string $message The error message.
 * @param int    $status  Optional. HTTP status code. Default 400.
 * @param array  $data    Optional. Additional data.
 * @return void
 */
function boostbot_json_error( $message, $status = 400, $data = array() ) {
    wp_send_json_error(
        array_merge(
            array( 'message' => $message ),
            $data
        ),
        $status
    );
}

/**
 * Send a JSON success response and exit.
 *
 * @param mixed $data   Optional. The data to send.
 * @param int   $status Optional. HTTP status code. Default 200.
 * @return void
 */
function boostbot_json_success( $data = null, $status = 200 ) {
    wp_send_json_success( $data, $status );
}

/**
 * Check if the current request is an AJAX request.
 *
 * @return bool
 */
function boostbot_is_ajax() {
    return wp_doing_ajax();
}

/**
 * Get client IP address.
 *
 * @return string The IP address.
 */
function boostbot_get_client_ip() {
    $ip = '';

    if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
        $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CLIENT_IP'] ) );
    } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
        $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) );
    } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
        $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
    }

    // Handle comma-separated list (proxy chain)
    if ( strpos( $ip, ',' ) !== false ) {
        $ips = explode( ',', $ip );
        $ip  = trim( $ips[0] );
    }

    return filter_var( $ip, FILTER_VALIDATE_IP ) ? $ip : '';
}










