<?php
/**
 * Plugin Name:       Navi AI Product Chat Bot
 * Plugin URI:        https://naviwebsolutions.com/
 * Description:       Adds a smart floating chat assistant to WooCommerce for product search using natural language and price filters.
 * Version:           1.0.0
 * Author:            naviweb
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Requires at least: 5.4
 * Requires PHP:      7.4
 * Requires Plugins:  woocommerce
 *
 * @package NAVIAIPR
 */

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



define( 'NAVIAIPR_OPTION_KEY', 'naviaipr_options' );
define( 'NAVIAIPR_VERSION', '1.0.0' );

/**
 * Get default option values.
 */
function naviaipr_get_defaults() {

	return array(
		'max_results'          => 5,

		'bubble_color'         => '#1f7ae0',
		'bubble_text_color'    => '#ffffff',
		'bubble_image'         => plugin_dir_url( __FILE__ ) . 'assets/Chatbot.jpg',
		'bubble_hori_position' => 'right',
		'bubble_vert_position' => 'bottom',
		'bubble_bottom'        => 20,
		'bubble_side'          => 20,

		'header_color_from'    => '#1f7ae0',
		'header_color_to'      => '#3fb0ff',
		'header_text_color'    => '#ffffff',

		'user_msg_bg'          => '#3574d3',
		'bot_msg_bg'           => '#ffffff',
		'chat_bg'              => '#f7fbff',
		'bot_font_size'        => '17',
		'chat_layout'          => 'first',
		'greeting_msg'         => '
Product Name,

10,

Product at 60,

product under 60',

		'accent_color'         => '#ea1b25',
		'accent_text_color'    => '#ffffff',

		'panel_width'          => 360,
		'font_family'          => 'system-ui, Segoe UI, Roboto, Helvetica, Arial, sans-serif',

		'border_radius'        => 12,
	);
}

/**
 * Get merged plugin options.
 */
function naviaipr_get_opts() {
	$saved = get_option( NAVIAIPR_OPTION_KEY, array() );
	return array_merge( naviaipr_get_defaults(), $saved );
}

/**
 * Sanitize a color value into a safe rgba() or hex string.
 *
 * @param string $color         Raw color input.
 * @param string $default_param Fallback value if input is invalid.
 * @return string
 */
function naviaipr_sanitize_rgba_color( $color, $default_param = 'rgba(0,0,0,1)' ) {
	 // phpcs:ignore Universal.NamingConventions.NoReservedKeywordParameterNames
	if ( empty( $color ) ) {
		return $default_param;
	}
		$color = trim( $color );

	if ( strpos( $color, 'rgba' ) !== false ) {
		$color = str_replace( ' ', '', $color );
		if ( preg_match( '/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(0|0?\.\d+|1)\)$/', $color ) ) {
			return $color;
		}
	}

		$hex = sanitize_hex_color( $color );
	if ( $hex ) {
		$hex = str_replace( '#', '', $hex );
		if ( strlen( $hex ) === 3 ) {
			$r = hexdec( $hex[0] . $hex[0] );
			$g = hexdec( $hex[1] . $hex[1] );
			$b = hexdec( $hex[2] . $hex[2] );
		} else {
			$r = hexdec( substr( $hex, 0, 2 ) );
			$g = hexdec( substr( $hex, 2, 2 ) );
			$b = hexdec( substr( $hex, 4, 2 ) );
		}
		return "rgba($r,$g,$b,1)";
	}
		return $default_param;
}

/**
 * Only allow characters that are valid in a CSS font-family value
 * (letters, numbers, spaces, commas, hyphens, quotes). Blocks characters
 * used in CSS injection like ; { } ( ) : etc.
 *
 * @param string $font Font family string.
 * @param string $default_param Fallback if input is invalid.
 */
function naviaipr_sanitize_font_family( $font, $default_param = 'system-ui, Segoe UI, Roboto, Helvetica, Arial, sans-serif' ) {
	if ( empty( $font ) ) {
		return $default_param;
	}
	$font = trim( $font );
	if ( preg_match( '/^[a-zA-Z0-9\s,\'"\-]+$/', $font ) ) {
		return $font;
	}
	return $default_param;
}

/**
 * Generate dynamic CSS from plugin options.
 *
 * @param array $opts Plugin options.
 * @return string
 */
function naviaipr_generate_dynamic_css( $opts ) {
	$bubble_color              = naviaipr_sanitize_rgba_color( $opts['bubble_color'] );
	$bubble_text_color         = naviaipr_sanitize_rgba_color( $opts['bubble_text_color'] );
	$header_color_from_grad    = naviaipr_sanitize_rgba_color( $opts['header_color_from'] );
	$header_color_to_grad      = naviaipr_sanitize_rgba_color( $opts['header_color_to'] );
	$header_text_color         = naviaipr_sanitize_rgba_color( $opts['header_text_color'] );
	$accent_color              = naviaipr_sanitize_rgba_color( $opts['accent_color'] );
	$accent_text_color         = naviaipr_sanitize_rgba_color( $opts['accent_text_color'] );
	$panel_width               = absint( $opts['panel_width'] );
	$font_family               = naviaipr_sanitize_font_family( $opts['font_family'] );
	$user_msg_background_color = naviaipr_sanitize_rgba_color( $opts['user_msg_bg'] );
	$bot_msg_background_color  = naviaipr_sanitize_rgba_color( $opts['bot_msg_bg'] );
	$chat_background_color     = naviaipr_sanitize_rgba_color( $opts['chat_bg'] );
	$bot_font_size             = absint( $opts['bot_font_size'] );

	$border_radius        = absint( $opts['border_radius'] );
	$bubble_bottom        = absint( $opts['bubble_bottom'] );
	$bubble_side          = absint( $opts['bubble_side'] );
	$bubble_hori_position = in_array( $opts['bubble_hori_position'] ?? 'left', array( 'left', 'right' ), true ) ? $opts['bubble_hori_position'] : 'left';
	$bubble_vert_position = in_array( $opts['bubble_vert_position'] ?? 'bottom', array( 'bottom', 'top' ), true ) ? $opts['bubble_vert_position'] : 'bottom';
	$panel_bottom         = $bubble_bottom + 56;

	return "
        .pb-gpt-bubble{
            {$bubble_hori_position}: {$bubble_side}px;
            {$bubble_vert_position}: {$bubble_side}px;
            bottom: {$bubble_bottom}px;
            background: {$bubble_color};
            color: {$bubble_text_color};
        }

        .pb-gpt-panel{
            {$bubble_hori_position}: {$bubble_side}px;
            {$bubble_vert_position}: {$panel_bottom}px;
            width: {$panel_width}px;
            border-radius: {$border_radius}px;
            font-family: {$font_family};
        }
        
        .pb-gpt-header{
              background: linear-gradient(90deg, {$header_color_from_grad}, {$header_color_to_grad});
              color: {$header_text_color};
        }

        .pb-gpt-messages{
               background-color: {$bot_msg_background_color};
        }
       
        .pb-msg.user{
               background-color: {$user_msg_background_color};
               font-size: {$bot_font_size}px;
        }                   
       
        .pb-msg.bot{
               background-color: {$chat_background_color};
               font-size: {$bot_font_size}px;
        }
               
        .pb-send{
                background: {$accent_color};
                color: {$accent_text_color};
        }

        .pb-product:hover{
                 border-color: {$accent_color};
        }

        .pb-product .price{
                 color: {$accent_color};
        }

        .pb-buy{
                background: {$accent_color};
                color: {$accent_text_color};
                border: 1px solid {$accent_color};
        }

        .pb-buy:hover{
                background: {$accent_text_color};
                color: {$accent_color};
        }
    ";
}


add_action( 'plugins_loaded', 'naviaipr_init_plugin' );
/**
 * Initialize the plugin.
 */
function naviaipr_init_plugin() {
	if ( ! class_exists( 'WooCommerce' ) ) {
		return;
	}

	if ( is_admin() ) {
		require_once plugin_dir_path( __FILE__ ) . 'admin/class-navi-ai-product-chat-bot-admin.php';
		new NAVIAIPR_Admin( naviaipr_get_defaults(), naviaipr_get_opts() );
	}

	require_once plugin_dir_path( __FILE__ ) . 'public/class-navi-ai-product-chat-bot-public.php';
	new NAVIAIPR_Frontend( naviaipr_get_opts() );

	require_once plugin_dir_path( __FILE__ ) . 'includes/class-navi-ai-product-chat-bot-query-handler.php';
	new NAVIAIPR_Query_Handler( naviaipr_get_opts() );
}


/**
 * Add settings link on plugin list page.
 *
 * @param array $links Existing plugin action links.
 * @return array
 */
function naviaipr_add_settings_link( $links ) {
	$settings_url  = esc_url( admin_url( 'admin.php?page=naviaipr' ) );
	$settings_link = '<a href="' . $settings_url . '">' . esc_html( 'Settings' ) . '</a>';
	return array_merge( array( $settings_link ), $links );
}

$naviaipr_plugin = plugin_basename( __FILE__ );
add_filter( "plugin_action_links_{$naviaipr_plugin}", 'naviaipr_add_settings_link' );
