<?php
/**
 * Shois Chat Button — Widget Renderer
 *
 * Handles all frontend output: enqueuing widget JS/CSS,
 * generating the shcb_config JSON, and outputting design tokens.
 *
 * @package ShoisChatButton
 */

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

/**
 * Class SHCB_Widget_Renderer
 *
 * Manages frontend widget rendering and asset loading.
 */
class SHCB_Widget_Renderer {

	/**
	 * Initialize hooks.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
	}

	/**
	 * Enqueue frontend widget scripts and styles.
	 *
	 * @return void
	 */
	public static function enqueue_assets() {
		$settings = get_option( 'shcb_global_settings', array() );

		// Don't load if widget is disabled.
		if ( empty( $settings['active'] ) ) {
			return;
		}

		// Don't load for admins if "hide for admins" is enabled.
		$perf = isset( $settings['performance'] ) ? $settings['performance'] : array();
		if ( ! empty( $perf['hide_for_admins'] ) && current_user_can( 'manage_options' ) ) {
			return;
		}

		// Check display rules.
		if ( class_exists( 'SHCB_Display_Rules' ) && ! SHCB_Display_Rules::should_display() ) {
			return;
		}

		// Enqueue base widget CSS (structural layout shared by all templates).
		wp_enqueue_style(
			'shcb-widget-base-css',
			SHCB_PLUGIN_URL . 'widget/css/widget-base.css',
			array(),
			SHCB_VERSION
		);

		// Enqueue template CSS (design token overrides).
		$template_slug = self::get_current_template_slug();
		$css_file      = SHCB_PLUGIN_DIR . 'widget/templates/' . $template_slug . '.css';
		$css_url       = SHCB_PLUGIN_URL . 'widget/templates/' . $template_slug . '.css';

		if ( file_exists( $css_file ) ) {
			wp_enqueue_style(
				'shcb-template-css',
				$css_url,
				array( 'shcb-widget-base-css' ),
				SHCB_VERSION
			);
		}

		// Enqueue platform-links.js.
		wp_enqueue_script(
			'shcb-platform-links',
			SHCB_PLUGIN_URL . 'widget/src/platform-links.js',
			array(),
			SHCB_VERSION,
			true
		);

		// Enqueue tracker.js.
		wp_enqueue_script(
			'shcb-tracker',
			SHCB_PLUGIN_URL . 'widget/src/tracker.js',
			array(),
			SHCB_VERSION,
			true
		);

		// Enqueue main widget.js with filetime versioning for cache busting.
		$widget_js_path = SHCB_PLUGIN_DIR . 'widget/src/widget.js';
		$widget_js_ver  = file_exists( $widget_js_path ) ? filemtime( $widget_js_path ) : SHCB_VERSION;

		wp_enqueue_script(
			'shcb-widget-js',
			SHCB_PLUGIN_URL . 'widget/src/widget.js',
			array( 'shcb-platform-links', 'shcb-tracker' ),
			$widget_js_ver,
			true
		);

		// Enqueue animation engine CSS + JS.
		if ( class_exists( 'SHCB_Animation_Engine' ) ) {
			SHCB_Animation_Engine::enqueue_animation_css();

			wp_enqueue_script(
				'shcb-animation-engine',
				SHCB_PLUGIN_URL . 'widget/src/animation-engine.js',
				array( 'shcb-widget-js' ),
				SHCB_VERSION,
				true
			);
		}

		// Build and localize the config.
		$config = self::build_config();

		wp_localize_script( 'shcb-widget-js', 'shcb_config', $config );

		// Output design token inline CSS.
		$inline_css = self::build_inline_css( $config );
		wp_add_inline_style( 'shcb-template-css', wp_strip_all_tags( $inline_css ) );
	}

	/**
	 * Get the current template slug.
	 *
	 * @return string Template slug for CSS file.
	 */
	private static function get_current_template_slug() {
		$settings = get_option( 'shcb_global_settings', array() );

		// Direct slug from settings (built-in templates).
		if ( ! empty( $settings['active_template_slug'] ) ) {
			return sanitize_key( $settings['active_template_slug'] );
		}

		// Fallback: CPT-based template via post ID.
		$template_id = isset( $settings['default_template_id'] ) ? absint( $settings['default_template_id'] ) : 0;

		if ( $template_id > 0 ) {
			$template = get_post( $template_id );

			if ( $template && 'shcb_template' === $template->post_type ) {
				$config = json_decode( $template->post_content, true );

				if ( ! empty( $config['template_slug'] ) ) {
					return sanitize_key( $config['template_slug'] );
				}
			}
		}

		// Default to classic green.
		return 'classic-green';
	}

	/**
	 * Build the shcb_config array for wp_localize_script.
	 *
	 * @return array Configuration array.
	 */
	private static function build_config() {
		$settings    = get_option( 'shcb_global_settings', array() );
		$agents      = get_option( 'shcb_agents', array() );
		$template_id = isset( $settings['default_template_id'] ) ? absint( $settings['default_template_id'] ) : 0;

		// Load template config — prefer settings-based config, fallback to CPT.
		$template_config = isset( $settings['template_config'] ) && is_array( $settings['template_config'] )
			? $settings['template_config']
			: array();
		$template_slug   = self::get_current_template_slug();

		// If no config in settings, try CPT-based template.
		if ( empty( $template_config ) && $template_id > 0 ) {
			$template = get_post( $template_id );

			if ( $template && 'shcb_template' === $template->post_type ) {
				$decoded = json_decode( $template->post_content, true );

				if ( is_array( $decoded ) ) {
					$template_config = $decoded;
				}
			}
		}

		// Build platform definitions with SVG icons.
		$platform_defs = array();
		$all_platforms = SHCB_Platform_Handler::get_platforms();

		foreach ( $all_platforms as $key => $platform ) {
			// link_format and mobile_deep_link contain {value} and {message}
			// placeholder tokens that must be preserved for JS replacement.
			// These are hardcoded trusted strings from get_platforms(), NOT user input.
			// Using esc_url_raw() would strip the curly braces, breaking all links.
			$link_fmt  = isset( $platform['link_format'] ) ? $platform['link_format'] : '';
			$deep_link = isset( $platform['mobile_deep_link'] ) ? $platform['mobile_deep_link'] : '';

			$platform_defs[ $key ] = array(
				'id'                   => esc_attr( $platform['id'] ),
				'name'                 => esc_html( $platform['name'] ),
				'color'                => sanitize_hex_color( $platform['color'] ) ? sanitize_hex_color( $platform['color'] ) : esc_attr( $platform['color'] ),
				'input_type'           => esc_attr( $platform['input_type'] ),
				'link_format'          => $link_fmt,
				'mobile_deep_link'     => $deep_link,
				'web_fallback'         => esc_url( isset( $platform['web_fallback'] ) ? $platform['web_fallback'] : '' ),
				'supports_pre_message' => (bool) $platform['supports_pre_message'],
				'icon_svg'             => SHCB_Platform_Handler::get_icon_svg( $key ),
			);
		}

		// Process agents — compute availability, sanitize for output.
		$processed_agents = array();

		foreach ( $agents as $agent ) {
			if ( empty( $agent['enabled'] ) ) {
				continue;
			}

			$processed_agents[] = array(
				'id'               => esc_attr( isset( $agent['id'] ) ? $agent['id'] : '' ),
				'name'             => esc_html( isset( $agent['name'] ) ? $agent['name'] : '' ),
				'title'            => esc_html( isset( $agent['title'] ) ? $agent['title'] : '' ),
				'avatar_type'      => esc_attr( isset( $agent['avatar_type'] ) ? $agent['avatar_type'] : 'initials' ),
				'avatar_url'       => esc_url( isset( $agent['avatar_url'] ) ? $agent['avatar_url'] : '' ),
				'avatar_initials'  => esc_html( isset( $agent['avatar_initials'] ) ? $agent['avatar_initials'] : '' ),
				'avatar_bg_color'  => esc_attr( isset( $agent['avatar_bg_color'] ) ? $agent['avatar_bg_color'] : '#25D366' ),
				'status_message'   => esc_html( isset( $agent['status_message'] ) ? $agent['status_message'] : '' ),
				'available'        => true, // Will be computed by availability class later.
				'platforms'        => self::sanitize_agent_platforms( isset( $agent['platforms'] ) ? $agent['platforms'] : array() ),
			);
		}

		// Build content from template config.
		$content = array(
			'header_title'    => esc_html( isset( $template_config['header_title'] ) ? $template_config['header_title'] : 'Chat with us! 👋' ),
			'header_subtitle' => esc_html( isset( $template_config['header_subtitle'] ) ? $template_config['header_subtitle'] : 'We reply within minutes' ),
			'welcome_message' => esc_html( isset( $template_config['welcome_message'] ) ? $template_config['welcome_message'] : 'Hi! How can we help you today?' ),
			'offline_message' => esc_html( isset( $template_config['offline_message'] ) ? $template_config['offline_message'] : "We're currently offline." ),
			'tooltip_text'    => esc_html( isset( $template_config['tooltip_text'] ) ? $template_config['tooltip_text'] : 'Need help?' ),
			'brand_logo'      => esc_url( isset( $template_config['brand_logo'] ) ? $template_config['brand_logo'] : '' ),
			'show_label'      => ! empty( $template_config['show_label'] ),
			'label_text'      => esc_html( isset( $template_config['label_text'] ) ? $template_config['label_text'] : 'Chat Now' ),
			'footer_text'     => esc_html( isset( $template_config['footer_text'] ) ? $template_config['footer_text'] : 'Powered by Shois Chat Button' ),
			'aria_label'      => esc_attr__( 'Chat widget', 'shois-chat-button' ),
			'trigger_aria'    => esc_attr__( 'Open chat', 'shois-chat-button' ),
			'popup_aria'      => esc_attr__( 'Chat options', 'shois-chat-button' ),
		);

		// Build behavior.
		$behavior = array(
			'open_in'                => esc_attr( isset( $template_config['open_in'] ) ? $template_config['open_in'] : 'new_tab' ),
			'auto_open'              => ! empty( $template_config['auto_open'] ),
			'auto_open_delay'        => absint( isset( $template_config['auto_open_delay'] ) ? $template_config['auto_open_delay'] : 0 ),
			'close_on_outside_click' => isset( $template_config['close_on_outside_click'] ) ? (bool) $template_config['close_on_outside_click'] : true,
			'remember_closed'        => ! empty( $template_config['remember_closed'] ),
			'show_after_delay'       => ! empty( $template_config['show_after_delay'] ),
			'delay_seconds'          => absint( isset( $template_config['delay_seconds'] ) ? $template_config['delay_seconds'] : 0 ),
			'show_after_scroll'      => ! empty( $template_config['show_after_scroll'] ),
			'scroll_percentage'      => absint( isset( $template_config['scroll_percentage'] ) ? $template_config['scroll_percentage'] : 25 ),
		);

		// Badge.
		$badge = array(
			'enabled' => ! empty( $template_config['badge_enabled'] ),
			'value'   => esc_html( isset( $template_config['badge_value'] ) ? $template_config['badge_value'] : '1' ),
		);

		// Chips (quick replies).
		$chips = array();
		if ( ! empty( $template_config['chips'] ) && is_array( $template_config['chips'] ) ) {
			foreach ( $template_config['chips'] as $chip ) {
				$chips[] = array(
					'label'   => esc_html( isset( $chip['label'] ) ? $chip['label'] : '' ),
					'emoji'   => esc_html( isset( $chip['emoji'] ) ? $chip['emoji'] : '' ),
					'message' => esc_html( isset( $chip['message'] ) ? $chip['message'] : '' ),
				);
			}
		}

		// Dynamic variables.
		$variables = self::get_dynamic_variables();

		// Schedule.
		$schedule = isset( $settings['availability'] ) ? $settings['availability'] : array();
		$schedule_config = array(
			'enabled'  => ! empty( $schedule['global_schedule']['enabled'] ),
			'timezone' => esc_attr( isset( $schedule['timezone'] ) ? $schedule['timezone'] : 'UTC' ),
			'hours'    => isset( $schedule['global_schedule']['hours'] ) ? $schedule['global_schedule']['hours'] : array(),
		);

		// Trigger icon SVG — use saved icon setting or default to WhatsApp.
		$trigger_icon_id = ! empty( $template_config['trigger_icon'] ) ? sanitize_key( $template_config['trigger_icon'] ) : 'whatsapp';
		$trigger_icon    = self::get_trigger_icon_svg( $trigger_icon_id );

		// Build animation config.
		$animations = class_exists( 'SHCB_Animation_Engine' ) ? SHCB_Animation_Engine::build_animation_config( $template_config ) : array();

		// Build integrations flags.
		$integrations = isset( $settings['integrations'] ) ? $settings['integrations'] : array();

		return array(
			'disabled'        => false,
			'template_id'     => $template_id,
			'template_slug'   => esc_attr( $template_slug ),
			'position'        => esc_attr( isset( $template_config['position'] ) ? $template_config['position'] : 'bottom-right' ),
			'trigger_icon_svg' => $trigger_icon,
			'content'         => $content,
			'behavior'        => $behavior,
			'badge'           => $badge,
			'chips'           => $chips,
			'agents'          => $processed_agents,
			'platforms'       => array(),
			'platform_defs'   => $platform_defs,
			'variables'       => $variables,
			'schedule'        => $schedule_config,
			'animations'      => $animations,
			'integrations'    => array(
				'ga4'      => ! empty( $integrations['ga4'] ),
				'fb_pixel' => ! empty( $integrations['fb_pixel'] ),
				'gtm'      => ! empty( $integrations['gtm'] ),
			),
			'rest_url'        => esc_url_raw( rest_url( SHCB_REST_NAMESPACE ) ),
			'nonce'           => wp_create_nonce( 'wp_rest' ),
		);
	}

	/**
	 * Sanitize agent platforms for frontend output.
	 *
	 * @param array $platforms Raw platforms array.
	 * @return array Sanitized platforms.
	 */
	private static function sanitize_agent_platforms( $platforms ) {
		$result = array();

		foreach ( $platforms as $plat ) {
			if ( empty( $plat['enabled'] ) ) {
				continue;
			}

			// Ensure we have a valid slug ID. 
			// If it's numeric (e.g. "0"), we'll try to resolve it or default it.
			$plat_id = isset( $plat['platform_id'] ) ? (string) $plat['platform_id'] : '';
			if ( is_numeric( $plat_id ) || empty( $plat_id ) ) {
				// Most common case is WhatsApp being the first (index 0)
				$plat_id = 'whatsapp';
			}

			$result[] = array(
				'platform_id'  => esc_attr( $plat_id ),
				'value'        => esc_attr( isset( $plat['value'] ) ? $plat['value'] : '' ),
				'label'        => esc_html( isset( $plat['label'] ) ? $plat['label'] : '' ),
				'pre_message'  => esc_html( isset( $plat['pre_message'] ) ? $plat['pre_message'] : '' ),
				'enabled'      => true,
				'is_primary'   => ! empty( $plat['is_primary'] ),
			);
		}

		return $result;
	}

	/**
	 * Get dynamic variables for message templates.
	 *
	 * @return array Variable name => value pairs.
	 */
	private static function get_dynamic_variables() {
		$vars = array(
			'site_name'  => esc_html( get_bloginfo( 'name' ) ),
			'page_title' => esc_html( wp_title( '', false ) ),
			'current_url' => esc_url( home_url( add_query_arg( null, null ) ) ),
			'date'       => esc_html( gmdate( 'Y-m-d' ) ),
			'time'       => esc_html( gmdate( 'H:i' ) ),
			'day_of_week' => esc_html( gmdate( 'l' ) ),
		);

		// WooCommerce variables.
		if ( class_exists( 'WooCommerce' ) ) {
			if ( is_product() ) {
				global $product;

				if ( $product ) {
					$vars['product_name']  = esc_html( $product->get_name() );
					$vars['product_price'] = esc_html( wp_strip_all_tags( wc_price( $product->get_price() ) ) );
					$vars['product_sku']   = esc_html( $product->get_sku() );
					$vars['product_url']   = esc_url( get_permalink( $product->get_id() ) );
				}
			}

			if ( function_exists( 'WC' ) && WC()->cart ) {
				$vars['cart_total']      = esc_html( wp_strip_all_tags( WC()->cart->get_cart_total() ) );
				$vars['cart_item_count'] = esc_html( WC()->cart->get_cart_contents_count() );
			}
		}

		return $vars;
	}

	/**
	 * Get SVG markup for a trigger icon ID.
	 *
	 * Supports platform icons and generic icons (chat, headset, help, phone, mail).
	 *
	 * @param string $icon_id Icon identifier.
	 * @return string SVG markup.
	 */
	private static function get_trigger_icon_svg( $icon_id ) {
		$generic_icons = array(
			'chat'      => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',
			'chat_dots' => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><circle cx="8" cy="10" r="1"/><circle cx="12" cy="10" r="1"/><circle cx="16" cy="10" r="1"/></svg>',
			'headset'   => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 1a9 9 0 0 0-9 9v7c0 1.66 1.34 3 3 3h3v-8H5v-2a7 7 0 0 1 14 0v2h-4v8h3c1.66 0 3-1.34 3-3v-7a9 9 0 0 0-9-9z"/></svg>',
			'help'      => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/></svg>',
			'phone'     => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/></svg>',
			'mail'      => '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/></svg>',
		);

		if ( isset( $generic_icons[ $icon_id ] ) ) {
			return $generic_icons[ $icon_id ];
		}

		return SHCB_Platform_Handler::get_icon_svg( $icon_id );
	}

	/**
	 * Build inline CSS for design token overrides.
	 *
	 * @param array $config Widget config.
	 * @return string CSS string.
	 */
	private static function build_inline_css( $config ) {
		$settings   = get_option( 'shcb_global_settings', array() );
		$tpl_config = isset( $settings['template_config'] ) && is_array( $settings['template_config'] )
			? $settings['template_config']
			: array();

		if ( empty( $tpl_config ) ) {
			return '';
		}

		$css = '#shcb-widget {';

		// Color tokens — supports both hex and CSS gradients.
		$color_tokens = array(
			'primary_color'     => '--scb-primary',
			'bg_color'          => '--scb-bg',
			'header_bg_color'   => '--shcb-header-bg',
			'header_text_color' => '--shcb-header-text',
			'text_color'        => '--scb-text',
			'icon_color'        => '--scb-icon-color',
		);

		foreach ( $color_tokens as $key => $var ) {
			if ( ! empty( $tpl_config[ $key ] ) ) {
				$val = sanitize_text_field( $tpl_config[ $key ] );
				if ( $val ) {
					$css .= esc_attr( $var ) . ':' . esc_attr( $val ) . ';';
				}
			}
		}

		// Sizing.
		$size_tokens = array(
			'btn_size'    => '--shcb-btn-size',
			'popup_width' => '--shcb-popup-width',
			'offset_x'    => '--scb-offset-x',
			'offset_y'    => '--scb-offset-y',
			'icon_size'   => '--scb-icon-size',
		);

		foreach ( $size_tokens as $key => $var ) {
			if ( isset( $tpl_config[ $key ] ) ) {
				$val = absint( $tpl_config[ $key ] );
				$css .= esc_attr( $var ) . ':' . esc_attr( $val ) . 'px;';
			}
		}

		// Border radius.
		if ( isset( $tpl_config['radius_btn'] ) ) {
			$val = absint( $tpl_config['radius_btn'] );
			$css .= '--scb-radius-btn:' . esc_attr( $val ) . '%;';
		}

		if ( isset( $tpl_config['radius_popup'] ) ) {
			$val = absint( $tpl_config['radius_popup'] );
			$css .= '--scb-radius-popup:' . esc_attr( $val ) . 'px;';
		}

		$css .= '}';

		// Gradient-specific overrides (gradients need direct background property).
		$gradient_css = '';
		if ( ! empty( $tpl_config['primary_color'] ) && strpos( $tpl_config['primary_color'], 'gradient' ) !== false ) {
			$grad = sanitize_text_field( $tpl_config['primary_color'] );
			$gradient_css .= '#shcb-widget .shcb-trigger-btn{background:' . esc_attr( $grad ) . ';}';
			$gradient_css .= '#shcb-widget .shcb-trigger-btn:hover{box-shadow:0 6px 24px rgba(0,0,0,0.25);}';
		}
		if ( ! empty( $tpl_config['header_bg_color'] ) && strpos( $tpl_config['header_bg_color'], 'gradient' ) !== false ) {
			$grad = sanitize_text_field( $tpl_config['header_bg_color'] );
			$gradient_css .= '#shcb-widget .shcb-popup-header{background:' . esc_attr( $grad ) . ';}';
		}

		// Option logic
		if ( isset( $tpl_config['agent_bg_color'] ) ) {
			$val = sanitize_text_field( $tpl_config['agent_bg_color'] );
			$css .= '#shcb-widget .shcb-agent-card { background-color:' . esc_attr( $val ) . ' !important;} ';
		}

		if ( isset( $tpl_config['agent_text_color'] ) ) {
			$val = sanitize_text_field( $tpl_config['agent_text_color'] );
			$css .= '#shcb-widget .shcb-agent-name, #shcb-widget .shcb-agent-status, #shcb-widget .shcb-agent-status span, #shcb-widget .shcb-agent-title { color:' . esc_attr( $val ) . ' !important;} ';
		}

		// Platform icon layout overrides based on new settings
		$platform_css = '';
		if ( isset( $tpl_config['platform_radius'] ) ) {
			$platform_css .= '#shcb-widget .shcb-platform-btn {';
			$platform_css .= ' border-radius: ' . absint( $tpl_config['platform_radius'] ) . '% !important;';
			$platform_css .= '} ';
		}

		return $css . $gradient_css . $platform_css;
	}
}
