<?php
/**
 * MindWebConcierge Frontend Handler
 *
 * @package MindWebConcierge
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
require_once __DIR__ . '/mindweco_config.php';

add_action( 'wp_footer', 'mindweco_add_floating_icon' );

function mindweco_add_floating_icon() {
	global $wpdb;
	$plugin_url     = plugin_dir_url( dirname( __FILE__ ) );
	$img_url        = $plugin_url . 'assets/img/logo_notespace_smart.png';
	$site_icon_url  = get_site_icon_url();
	$poweredby_link = MINDWECO_POWER_BY;
	$service_links  = get_option( 'mindweco_service_links', array() );
	$services_count = (int) get_option( 'mindweco_services_count', 0 );

	if ( ! is_array( $service_links ) ) {
		$service_links = array();
	}

	$service_links = array_values(
		array_filter(
			$service_links,
			function ( $service ) {
				return ! empty( $service['url'] );
			}
		)
	);

	if ( $services_count > 0 && empty( $service_links ) ) {
		$legacy_url = get_option( 'mindweco_calendly_url', '' );
		if ( ! empty( $legacy_url ) ) {
			$service_links[] = array(
				'title'       => '',
				'description' => '',
				'url'         => $legacy_url,
			);
		}
	}

	$use_calendly = ! empty( $service_links );

	if ( empty( $site_icon_url ) ) {
		$site_icon_url = $img_url;
	}

	$greeting_title    = mindweco_get_locale_copy( 'need_a_hand' );
	$greeting_subtitle = mindweco_get_locale_copy( 'chat_online' );
	
	?>
		<div id="mindweco-btn-wrapper" class="mindweco-trigger-container">
			<button class="mindweco-trigger-btn" id="open-mindweco">
				<img src="<?php echo esc_url( $site_icon_url ); ?>" alt="<?php esc_attr_e( 'Site Icon', 'mind-web-concierge' ); ?>" class="rounded-circle">
			</button>
		</div>
		
		<div id="mindweco-greeting-bubble" style="display:none;">
			<button type="button" class="mindweco-greeting-close" aria-label="<?php esc_attr_e( 'Close', 'mind-web-concierge' ); ?>">
				<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
					<line x1="18" y1="6" x2="6" y2="18"></line>
					<line x1="6" y1="6" x2="18" y2="18"></line>
				</svg>
			</button>
			<div class="mindweco-greeting-icon">
				<img src="<?php echo esc_url( $site_icon_url ); ?>" alt="">
			</div>
			<div class="mindweco-greeting-text">
				<div class="mindweco-greeting-title"><?php echo esc_html( $greeting_title ); ?></div>
				<div class="mindweco-greeting-subtitle"><?php echo esc_html( $greeting_subtitle ); ?></div>
			</div>
		</div>

		<div id="mindweb-mindweco-root" class="<?php echo $use_calendly ? 'mindweco-has-services' : 'mindweco-no-services'; ?>">

			<div id="mindweco-container" class="mindweco-container" style="display: none;">
				<div class="mindweco-header">
					<div class="mindweco-header-content" style="display: flex; align-items: center;">
						<img src="<?php echo esc_url( $site_icon_url ); ?>" alt="<?php esc_attr_e( 'Site Icon', 'mind-web-concierge' ); ?>" class="rounded-circle" style="margin-right:10px;">
						<div class="header-status">
							<div class="web-assist-header" style="display: flex; align-items: baseline; gap: 5px;">
								<span style="font-size: 18px; font-weight: bold;"><?php esc_html_e( 'Mind Web', 'mind-web-concierge' ); ?></span>
								<i style="margin-top: 4px;"><?php esc_html_e( 'Concierge', 'mind-web-concierge' ); ?></i>
							</div>
							<div class="status-indicator" style="margin-left: 8px;">
								<span class="status-dot"></span>
							</div>
						</div>
					</div>
					<div class="mindweco-header-actions d-flex align-items-center" style="gap:5px;">
						<button id="mindweco-theme-toggle" class="mindweco-theme-toggle" title="<?php esc_attr_e( 'Toggle dark/light mode', 'mind-web-concierge' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 16 16">
								<path d="M8 4.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7zM8 0a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-1 0v-1A.5.5 0 0 1 8 0zm0 14a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-1 0v-1a.5.5 0 0 1 .5-.5zm8-6a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1 0-1h1a.5.5 0 0 1 .5.5zm-14 0a.5.5 0 0 1-.5.5h-1a.5.5 0 0 1 0-1h1a.5.5 0 0 1 .5.5zm10.657-5.657a.5.5 0 0 1 0 .707l-.708.708a.5.5 0 1 1-.707-.707l.708-.708a.5.5 0 0 1 .707 0zm-9.9 9.9a.5.5 0 0 1 0 .707l-.708.708a.5.5 0 0 1-.707-.707l.708-.708a.5.5 0 0 1 .707 0zm9.9 0a.5.5 0 0 1 .707 0l.708.708a.5.5 0 0 1-.707.707l-.708-.708a.5.5 0 0 1 0-.707zm-9.9-9.9a.5.5 0 0 1 .707 0l.708.708a.5.5 0 0 1-.707.707l-.708-.708a.5.5 0 0 1 0-.707z"/>
							</svg>
						</button>
						<button id="clear-chat-history" class="clear-chat-history" title="<?php esc_attr_e( 'Start new conversation', 'mind-web-concierge' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 16 16">
								<path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/>
							</svg>
						</button>
						<button id="resize-mindweco" class="mindweco-resize" style="<?php echo $use_calendly ? 'display:none;' : ''; ?>" title="<?php esc_attr_e( 'Resize window', 'mind-web-concierge' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="64px" height="64px" viewBox="-16 -16 64.00 64.00" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
								<path d="M7.539,26.475l6.849,-6.971c0.58,-0.591 0.572,-1.541 -0.019,-2.121c-0.591,-0.58 -1.541,-0.572 -2.121,0.019l-6.737,6.856c-0.007,-0.079 -0.011,-0.159 -0.011,-0.24c0,-0 -0,-7.018 -0,-7.018c-0,-0.828 -0.672,-1.5 -1.5,-1.5c-0.828,0 -1.5,0.672 -1.5,1.5l0,7.018c0,3.037 2.462,5.5 5.5,5.5c3.112,-0 6.905,-0 6.905,-0c0.828,-0 1.5,-0.673 1.5,-1.5c0,-0.828 -0.672,-1.5 -1.5,-1.5l-6.905,-0c-0.157,-0 -0.311,-0.015 -0.461,-0.043Z"/>
								<path d="M24.267,5.51l-7.056,7.181c-0.58,0.591 -0.571,1.541 0.019,2.122c0.591,0.58 1.541,0.571 2.121,-0.019l7.149,-7.277c0.031,0.156 0.047,0.318 0.047,0.483c-0,0 -0,6.977 -0,6.977c-0,0.828 0.672,1.5 1.5,1.5c0.828,0 1.5,-0.672 1.5,-1.5l-0,-6.977c-0,-3.038 -2.463,-5.5 -5.5,-5.5c-3.162,0 -7.047,0 -7.047,0c-0.828,0 -1.5,0.672 -1.5,1.5c0,0.828 0.672,1.5 1.5,1.5c0,0 3.885,0 7.047,0c0.074,-0 0.147,0.003 0.22,0.01Z"/>
							</svg>
						</button>
						<button id="mindweco-swap-content" class="mindweco-swap-content" title="<?php esc_attr_e( 'Swap content', 'mind-web-concierge' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<rect x="3" y="4" width="7" height="7" rx="1"></rect>
								<rect x="14" y="13" width="7" height="7" rx="1"></rect>
								<path d="M10 7h7"></path>
								<path d="M15 4l3 3-3 3"></path>
								<path d="M14 17H7"></path>
								<path d="M9 14l-3 3 3 3"></path>
							</svg>
						</button>

						<?php if ( $use_calendly ) : ?>
							<button id="mindweco-calendly-btn" class="mindweco-calendly-btn" title="<?php esc_attr_e( 'Services & Options', 'mind-web-concierge' ); ?>">
								<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
									<line x1="8" y1="6" x2="21" y2="6"></line>
									<line x1="8" y1="12" x2="21" y2="12"></line>
									<line x1="8" y1="18" x2="21" y2="18"></line>
									<circle cx="4" cy="6" r="1"></circle>
									<circle cx="4" cy="12" r="1"></circle>
									<circle cx="4" cy="18" r="1"></circle>
								</svg>
							</button>
						<?php endif; ?>

						<button class="mindweco-close" id="close-mindweco" title="<?php esc_attr_e( 'Close chat', 'mind-web-concierge' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 16 16">
								<path d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8z"/>
							</svg>
						</button>
					</div>
				</div>

				<div id="mindweco-history-bar" style="display:none;">
					<div id="mindweco-history-bar-inner"></div>
				</div>
				<div class="mindweco-messages" id="mindweco-messages"></div>
				<div class="mindweco-typing" id="mindweco-typing" style="display: none;">
					<div class="pipeline-steps"></div>
					<div class="typing-indicator">
						<span></span>
						<span></span>
						<span></span>
					</div>
				</div>
				<div class="mindweco-input-container">
					<div class="mindweco-checkbox-wrapper">
						<label>
							<input type="checkbox" id="mindweco-context-toggle">
							<span class="ask-label-name"><?php esc_html_e( 'Local Thinking', 'mind-web-concierge' ); ?></span>
							<span class="tooltip-container">
								<button type="button" aria-label="<?php esc_attr_e( 'more info', 'mind-web-concierge' ); ?>">?</button>
								<span role="status"><?php esc_html_e( 'Mind Web will focus only on information available on this page to provide contextual answers.', 'mind-web-concierge' ); ?></span>
							</span>
						</label>
					</div>
					<div class="mindweco-input-wrapper">
						<textarea id="mindweco-input" class="mindweco-input mindweco-textarea" placeholder="<?php esc_attr_e( 'Ask Mind Web Concierge here...', 'mind-web-concierge' ); ?>" rows="1"></textarea>
						<button class="mindweco-send-btn" id="mindweco-send" title="<?php esc_attr_e( 'Send message', 'mind-web-concierge' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
								<path d="M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"></path>
								<path d="m21.854 2.147-10.94 10.939"></path>
							</svg>
						</button>
					</div>
				</div>

				<?php if ( get_option( 'mindweco_show_powered_by', 0 ) ) : ?>
					<div class="mindweco-footer gap-2" id="mindweco-footer">
						<span class="powered-by"><?php esc_html_e( 'Powered by:', 'mind-web-concierge' ); ?></span>
						<a href="<?php echo esc_url( $poweredby_link ); ?>" target="_blank" rel="noopener noreferrer" class="powered-link">
							<?php esc_html_e( 'SmartMind.it', 'mind-web-concierge' ); ?>
						</a>
					</div>
				<?php endif; ?>

				<div class="modal fade" id="startNewChatModal" tabindex="-1" aria-labelledby="startNewChatModalLabel" aria-hidden="true">
					<div class="modal-dialog modal-dialog-centered">
						<div class="modal-content">
							<div class="modal-header border-0 pb-0">
								<h5 class="modal-title fw-semibold" id="startNewChatModalLabel">
									<?php esc_html_e( 'Start a New Chat', 'mind-web-concierge' ); ?>
								</h5>
								<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="<?php esc_attr_e( 'Close', 'mind-web-concierge' ); ?>">
									<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 16 16">
										<path d="M.293.293a1 1 0 0 1 1.414 0L8 6.586 14.293.293a1 1 0 1 1 1.414 1.414L9.414 8l6.293 6.293a1 1 0 0 1-1.414 1.414L8 9.414l-6.293 6.293a1 1 0 0 1-1.414-1.414L6.586 8 .293 1.707a1 1 0 0 1 0-1.414z"/>
									</svg>
								</button>
							</div>
							<div class="modal-body pt-2">
								<p class="text-muted mb-0">
									<?php esc_html_e( 'Starting a new conversation will clear your current chat history. This action cannot be undone.', 'mind-web-concierge' ); ?>
								</p>
							</div>
							<div class="modal-footer border-0 pt-0">
								<button type="button" id="confirmNewChatBtn" class="btn" style="min-width: 100px !important;">
									<?php esc_html_e( 'Start New Chat', 'mind-web-concierge' ); ?>
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div id="mindweco-calendly-panel" role="dialog" aria-label="<?php echo $use_calendly ? esc_attr__( 'Services & Options', 'mind-web-concierge' ) : esc_attr__( 'Sources', 'mind-web-concierge' ); ?>" aria-modal="true" style="display:none;">
				<div class="mindweco-calendly-panel-header">
					<div class="mindweco-calendly-panel-header-left">
						<img src="<?php echo esc_url( $site_icon_url ); ?>" alt="" class="rounded-circle">
						<div class="mindweco-calendly-header-text">
							<span class="mwc-cal-title"><?php echo $use_calendly ? esc_html__( 'Services & Options', 'mind-web-concierge' ) : esc_html__( 'Sources', 'mind-web-concierge' ); ?></span>
							<span class="mwc-cal-sub"><?php echo $use_calendly ? esc_html__( 'Choose what suits you best', 'mind-web-concierge' ) : esc_html__( 'Referenced pages', 'mind-web-concierge' ); ?></span>
						</div>
					</div>
					<div class="mindweco-calendly-panel-header-right">

						<?php if ( $use_calendly ) : ?>
							<button id="mwc-panel-mode-services" type="button"
								aria-label="Show services"
								title="Services">

								<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
									<line x1="8" y1="6" x2="21" y2="6"></line>
									<line x1="8" y1="12" x2="21" y2="12"></line>
									<line x1="8" y1="18" x2="21" y2="18"></line>
									<circle cx="4" cy="6" r="1"></circle>
									<circle cx="4" cy="12" r="1"></circle>
									<circle cx="4" cy="18" r="1"></circle>
								</svg>
							</button>

							<button id="mwc-panel-mode-sources" type="button"
								aria-label="<?php esc_attr_e( 'Show sources', 'mind-web-concierge' ); ?>"
								title="<?php esc_attr_e( 'Show sources', 'mind-web-concierge' ); ?>">

								<svg class="mwc-panel-mode-sources-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
									<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>
									<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>
								</svg>
							</button>
						<?php endif; ?>
						
						<button id="resize-panel-services-sources" type="button" aria-label="<?php esc_attr_e( 'Expand panel', 'mind-web-concierge' ); ?>" title="<?php esc_attr_e( 'Expand panel', 'mind-web-concierge' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="3" width="18" height="18" rx="2" stroke-linecap="round" stroke-linejoin="round"/><path stroke-linecap="round" stroke-linejoin="round" d="M9 3v18M14 9l3 3-3 3"/></svg>
						</button>
						<button id="mindweco-calendly-close" type="button" aria-label="<?php esc_attr_e( 'Close', 'mind-web-concierge' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" viewBox="0 0 16 16">
								<path d="M4 8a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7A.5.5 0 0 1 4 8z"/>
							</svg>
						</button>

					</div>
				</div>

				<div class="mwc-cal-iframe-wrapper">
					<div class="mwc-cal-loading" id="mwc-cal-loading">
						<div class="mwc-cal-spinner"></div>
						<span class="mwc-cal-loading-text"><?php esc_html_e( 'Loading', 'mind-web-concierge' ); ?></span>
					</div>
					<iframe id="mindweco-calendly-iframe" src="" title="<?php esc_attr_e( 'Calendly Booking', 'mind-web-concierge' ); ?>" allow="fullscreen"></iframe>
				</div>
			</div>

		</div>

		<div id="citation-popup">
			<div id="citation-popup-inner">
				<div class="source-close-container">
					<span id="citation-popup-label">📎 Sources</span>
					<span id="close-citation"><i class="fa-thin fa-x fa-2xs"></i></span>
				</div>
				<div id="citation-popup-content"></div>
			</div>
			<div id="citation-popup-arrow"></div>
		</div>
	<?php
}

/**
 * Register REST API route for Calendly webhook.
 */
add_action( 'rest_api_init', 'mindweco_register_calendly_webhook_route' );

function mindweco_register_calendly_webhook_route() {
	register_rest_route(
		'mindweco/v1',
		'/calendly-webhook',
		array(
			'methods'             => 'POST',
			'callback'            => 'mindweco_handle_calendly_webhook',
			'permission_callback' => '__return_true',
		)
	);
}

add_action( 'wp_enqueue_scripts', 'mindweco_enqueue_scripts' );

function mindweco_enqueue_scripts() {

	global $wpdb;

	$plugin_url = plugin_dir_url( __DIR__ );
	$ver        = defined( 'MIND_WEB_VERSION' ) ? MIND_WEB_VERSION : '1.3.0';
	$js_base    = $plugin_url . 'assets/js/mindweco/';

	wp_enqueue_script( 'jquery' );

	wp_enqueue_script(
		'mindweco-bootstrap-js',
		$plugin_url . 'assets/js/bootstrap.bundle.min.js',
		array( 'jquery' ),
		'5.3.8',
		true
	);

	wp_enqueue_script(
		'mindweco-ajax-safety',
		$plugin_url . 'assets/js/mindweco-ajax-safety.js',
		array(),
		$ver,
		true
	);

	wp_enqueue_script(
		'mindweco-nonce-refresh',
		$plugin_url . 'assets/js/mindweco-nonce-refresh.js',
		array( 'jquery' ),
		$ver,
		true
	);

	wp_enqueue_style(
		'mindweco-mind-web-style',
		$plugin_url . 'assets/css/mind_web.css',
		array(),
		$ver
	);

	
	wp_enqueue_style(
		'mindweco-font-awesome',
		$plugin_url . 'assets/css/all.min.css',
		array(),
		'6.5.1'
	);

	wp_enqueue_script(
		'mindweco-marked',
		$plugin_url . 'assets/js/marked.min.js',
		array(),
		'15.0.12',
		true
	);

	wp_enqueue_script( 'mindweco-helpers',       $js_base . 'utils/mindweco_helpers.js',       array( 'jquery' ),                                                                    $ver, true );
	wp_enqueue_script( 'mindweco-greetings',     $js_base . 'utils/mindweco_greetings.js',     array( 'jquery' ),                                                                    $ver, true );
	wp_enqueue_script( 'mindweco-theme',         $js_base . 'modules/mindweco_theme.js',       array( 'jquery' ),                                                                    $ver, true );
	wp_enqueue_script( 'mindweco-citations',     $js_base . 'modules/mindweco_citations.js',   array( 'jquery', 'mindweco-helpers' ),                                                $ver, true );
	wp_enqueue_script( 'mindweco-messages',      $js_base . 'modules/mindweco_messages.js',    array( 'jquery', 'mindweco-helpers', 'mindweco-greetings', 'mindweco-citations', 'mindweco-marked' ),    $ver, true );
	wp_enqueue_script( 'mindweco-history',       $js_base . 'modules/mindweco_history.js',     array( 'jquery', 'mindweco-helpers', 'mindweco-messages' ),                           $ver, true );
	wp_enqueue_script( 'mindweco-subscriptions', $js_base . 'modules/mindweco_subscriptions.js', array( 'jquery', 'mindweco-helpers' ),                                             $ver, true );
	wp_enqueue_script( 'mindweco-logs',          $js_base . 'modules/mindweco_logs.js',        array( 'jquery', 'mindweco-helpers' ),                                                $ver, true );
	wp_enqueue_script( 'mindweco-ui',            $js_base . 'modules/mindweco_ui.js',          array( 'jquery', 'mindweco-theme', 'mindweco-messages', 'mindweco-history' ),         $ver, true );
	
	wp_enqueue_script(
		'mindweco-main',
		$plugin_url . 'assets/js/mindweco-main.js',
		array(
			'jquery', 'mindweco-bootstrap-js', 'mindweco-ajax-safety', 'mindweco-nonce-refresh',
			'mindweco-helpers', 'mindweco-greetings', 'mindweco-theme', 'mindweco-citations',
			'mindweco-messages', 'mindweco-history', 'mindweco-subscriptions', 'mindweco-logs', 'mindweco-ui', 'mindweco-marked'
		),
		$ver,
		true
	);

	

	$plugin_url    = plugin_dir_url( dirname( __FILE__ ) );
	$img_url       = $plugin_url . 'assets/img/logo_notespace_smart.png';
	$site_icon_url = get_site_icon_url();

	if ( empty( $site_icon_url ) ) {
		$site_icon_url = $img_url;
	}

	$user_avatar = get_avatar_url( get_current_user_id(), array( 'size' => 64 ) );
	$summary     = get_option( 'mindweco_summary' );
	$language    = mindweco_get_locale_code();

	wp_localize_script(
		'mindweco-main',
		'mindwecoFrontend',
		array(
			'ajax_url'       => admin_url( 'admin-ajax.php' ),
			'nonce'          => wp_create_nonce( 'mindweco_frontend_nonce' ),
			'post_id'        => get_the_ID(),
			'initialHistory' => array(),
			'bot_avatar'     => $site_icon_url,
			'user_avatar'    => $user_avatar,
			'summary'        => $summary,
			'language'       => $language,
		)
	);

	$trial_response  = get_option( 'mindweco_trial_response', array() );
	$end_date        = isset( $trial_response['currentPeriodEnd'] ) ? $trial_response['currentPeriodEnd'] : '';
	$status          = isset( $trial_response['status'] )           ? $trial_response['status']           : null;
	$type            = isset( $trial_response['type'] )             ? $trial_response['type']             : '';
	$stripe_base_url = mindweco_get_stripe_base_url();
	$app_guid        = get_option( 'mindweco_plugin_guid', '' );
	$product_id      = get_option( 'mindweco_stripe_product_id', '' );
	$user_email      = wp_get_current_user()->user_email;

	$items_count    = 0;
	$products_count = 0;

	$items_table        = $wpdb->prefix . 'mindweco_indexed_items';
	$items_table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $items_table ) );
	if ( $items_table_exists === $items_table ) {
		$items_count = (int) $wpdb->get_var(
			$wpdb->prepare( "SELECT COUNT(*) FROM `{$items_table}` WHERE status = %s", 'indexed' )
		);
	}

	$products_table        = $wpdb->prefix . 'mindweco_indexed_products';
	$products_table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $products_table ) );
	if ( $products_table_exists === $products_table ) {
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$products_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$products_table}`" );
	}
	
	$service_links = get_option( 'mindweco_service_links', array() );
	$services_count = (int) get_option( 'mindweco_services_count', 0 );

	if ( ! is_array( $service_links ) ) {
		$service_links = array();
	}

	$service_links = array_values(
		array_filter(
			$service_links,
			function ( $service ) {
				return ! empty( $service['url'] );
			}
		)
	);

	if ( $services_count > 0 && empty( $service_links ) ) {
		$legacy_url = get_option( 'mindweco_calendly_url', '' );
		if ( ! empty( $legacy_url ) ) {
			$service_links[] = array(
				'title'       => '',
				'description' => '',
				'url'         => $legacy_url,
			);
		}
	}

	$cal_url = ! empty( $service_links[0]['url'] ) ? $service_links[0]['url'] : '';
	$iframe_css = trim( (string) get_option( 'mindweco_iframe_css', get_option( 'mindweco_custom_css', '' ) ) );

	wp_localize_script(
		'mindweco-main',
		'mindwecoData',
		array(
			'ajaxurl'               => admin_url( 'admin-ajax.php' ),
			'nonce'                 => wp_create_nonce( 'mindweco_trial_nonce' ),
			'trialEndDate'          => $end_date,
			'stripe_base_url'       => $stripe_base_url,
			'app_guid'              => $app_guid,
			'product_id'            => $product_id,
			'trial_status'          => $status,
			'trial_type'            => $type,
			'user_email'            => $user_email,
			'title'                 => esc_url( get_option( 'siteurl' ) ),
			'should_show_initially' => true,
			'has_items'             => ( $items_count > 0 ),
			'has_products'          => ( $products_count > 0 ),
			'calendly_url'          => $cal_url,
			'service_links'         => $service_links,
			'show_calendly' 		=> ! empty( $service_links ),
		)
	);

	wp_localize_script(
		'mindweco-main',
		'mindwecoConfig',
		array(
			'iframeCss' => $iframe_css,
		)
	);
}

add_action('wp_enqueue_scripts', function () {
    if (class_exists('WooCommerce')) {
        wp_enqueue_script('wc-add-to-cart');
        wp_enqueue_script('wc-cart-fragments');
        wp_enqueue_script('wc-checkout');
    }
});


add_action( 'transition_post_status', 'mindweco_clear_items_cache', 10, 3 );
/**
 * @param string  $new_status New post status.
 * @param string  $old_status Old post status.
 * @param WP_Post $post       Post object.
 */
function mindweco_clear_items_cache( $new_status, $old_status, $post ) {
	if ( ! in_array( $post->post_type, array( 'post', 'page' ), true ) ) {
		return;
	}
	$cache_key = 'mindweco_has_items_' . get_current_blog_id();
	wp_cache_delete( $cache_key, 'mindweco' );
}


add_action( 'before_delete_post', 'mindweco_clear_cache_on_delete' );
/**
 *
 * @param int $post_id Post ID.
 */
function mindweco_clear_cache_on_delete( $post_id ) {
	$post = get_post( $post_id );
	if ( ! $post || ! in_array( $post->post_type, array( 'post', 'page' ), true ) ) {
		return;
	}
	$cache_key = 'mindweco_has_items_' . get_current_blog_id();
	wp_cache_delete( $cache_key, 'mindweco' );
}


add_action( 'transition_post_status', 'mindweco_handle_status_change', 10, 3 );
/**
 * Re-indexes a post when it is published.
 *
 * @param string  $new_status New post status.
 * @param string  $old_status Old post status.
 * @param WP_Post $post       Post object.
 */
function mindweco_handle_status_change( $new_status, $old_status, $post ) {
	if ( ! in_array( $post->post_type, array( 'post', 'page' ), true ) ) {
		return;
	}

	if ( 'publish' !== $new_status ) {
		return;
	}

	global $wpdb;
	$post_id = $post->ID;

	$options     = get_option( 'mindweco_plugin_options', array() );
	$base_url    = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );
	$category    = get_option( 'mindweco_plugin_category', array() );
	$category_id = isset( $category['id'] ) ? intval( $category['id'] ) : null;

	if ( ! $base_url || ! $token || ! $category_id ) {
		return;
	}

	$fresh_token = mindweco_plugin_refresh_token();
	if ( $fresh_token ) {
		$token = $fresh_token;
	}

	$existing = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT item_id FROM {$wpdb->prefix}mindweco_indexed_items WHERE post_id = %d LIMIT 1",
			$post_id
		)
	);

	$local_item_id = $existing ? $existing->item_id : '';

	$rest_url = rest_url( 'wp/v2/' . $post->post_type . 's/' . $post_id );
	$response = wp_remote_get( $rest_url );
	$wp_json  = is_wp_error( $response ) ? array() : json_decode( wp_remote_retrieve_body( $response ), true );

	$meta = array(
		'categories' => wp_get_post_categories( $post_id, array( 'fields' => 'names' ) ),
		'tags'       => wp_get_post_tags( $post_id, array( 'fields' => 'names' ) ),
	);

	$chunk_size    = get_option( 'mindweco_chunk_size', 300 );
	$chunk_overlap = get_option( 'mindweco_chunk_overlap', 60 );
	$header_levels = get_option( 'mindweco_header_levels', 'h2,h3,h4' );

	$api_response = mindweco_plugin_api_index_items(
		$base_url,
		$token,
		$category_id,
		$chunk_size,
		$chunk_overlap,
		get_permalink( $post_id ),
		$wp_json,
		$header_levels,
		$meta,
		$local_item_id
	);

	$new_item_id = isset( $api_response['item_id'] ) ? $api_response['item_id'] : null;

	if ( ! $new_item_id ) {
		return;
	}

	if ( $existing ) {
		$wpdb->update(
			$wpdb->prefix . 'mindweco_indexed_items',
			array(
				'item_id'     => $new_item_id,
				'category_id' => $category_id,
				'created_at'  => current_time( 'mysql' ),
			),
			array( 'post_id' => $post_id ),
			array( '%s', '%d', '%s' ),
			array( '%d' )
		);
	} else {
		$wpdb->insert(
			$wpdb->prefix . 'mindweco_indexed_items',
			array(
				'post_id'     => $post_id,
				'item_id'     => $new_item_id,
				'category_id' => $category_id,
				'created_at'  => current_time( 'mysql' ),
			),
			array( '%d', '%s', '%d', '%s' )
		);
	}

	wp_cache_delete( 'mindweco_has_items_' . get_current_blog_id(), 'mindweco' );
}


add_action( 'before_delete_post', 'mindweco_handle_post_delete', 10, 1 );
/**
 * Removes a post from the index when it is permanently deleted.
 *
 * @param int $post_id Post ID.
 */
function mindweco_handle_post_delete( $post_id ) {
	$post = get_post( $post_id );
	if ( ! $post || ! in_array( $post->post_type, array( 'post', 'page' ), true ) ) {
		return;
	}

	if ( 'trash' === $post->post_status ) {
		return;
	}

	global $wpdb;

	$indexed_item = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT item_id, category_id FROM {$wpdb->prefix}mindweco_indexed_items WHERE post_id = %d LIMIT 1",
			$post_id
		)
	);

	if ( ! $indexed_item ) {
		return;
	}

	$options  = get_option( 'mindweco_plugin_options', array() );
	$base_url = isset( $options['base_url'] ) ? $options['base_url'] : '';
	$token = mindweco_decrypt_api_key( get_option( 'mindweco_plugin_access_token', '' ) );

	if ( $base_url && $token && $indexed_item->item_id && $indexed_item->category_id ) {
		$fresh_token = mindweco_plugin_refresh_token();
		if ( $fresh_token ) {
			$token = $fresh_token;
		}

		$api_response = mindweco_plugin_api_delete_indexed_items(
			$base_url,
			$token,
			$indexed_item->category_id,
			$indexed_item->item_id
		);

		if ( isset( $api_response['http_code'] ) && 401 === (int) $api_response['http_code'] ) {
			$new_token = mindweco_plugin_refresh_token();
			if ( $new_token ) {
				mindweco_plugin_api_delete_indexed_items(
					$base_url,
					$new_token,
					$indexed_item->category_id,
					$indexed_item->item_id
				);
			}
		}
	}

	$deleted = $wpdb->delete(
		$wpdb->prefix . 'mindweco_indexed_items',
		array( 'post_id' => $post_id ),
		array( '%d' )
	);

	if ( $deleted ) {
		wp_cache_delete( 'mindweco_has_items_' . get_current_blog_id(), 'mindweco' );
	}
}


add_action( 'wp_trash_post', 'mindweco_handle_post_trash', 10, 1 );
/**
 * Removes a post from the index when it is moved to trash.
 *
 * @param int $post_id Post ID.
 */
function mindweco_handle_post_trash( $post_id ) {
	$post = get_post( $post_id );
	if ( ! $post || ! in_array( $post->post_type, array( 'post', 'page' ), true ) ) {
		return;
	}
	mindweco_handle_post_delete( $post_id );
}


add_action('wp_ajax_mindweco_get_citation_data', 'mindweco_get_citation_data');
add_action('wp_ajax_nopriv_mindweco_get_citation_data', 'mindweco_get_citation_data');

function mindweco_get_citation_data() {

    check_ajax_referer('mindweco_frontend_nonce', 'nonce');

    $url = isset($_POST['url']) ? esc_url_raw(wp_unslash($_POST['url'])) : '';
    if (empty($url)) {
        wp_send_json_error('No URL provided');
    }

    $path = rtrim(parse_url($url, PHP_URL_PATH), '/');
    $slug = basename($path);

    $result = null;

    if (class_exists('WooCommerce')) {

        $product_query = new WP_Query([
            'name'           => $slug,
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => 1,
        ]);

        if ($product_query->have_posts()) {

            $post    = $product_query->posts[0];
            $product = wc_get_product($post->ID);

            $image = has_post_thumbnail($post->ID)
                ? get_the_post_thumbnail_url($post->ID, 'medium')
                : null;

            $excerpt = !empty($post->post_excerpt)
                ? wp_strip_all_tags($post->post_excerpt)
                : wp_trim_words(wp_strip_all_tags($post->post_content), 30, '…');

            wp_send_json_success([
                'type'        => 'product',
                'product_id'  => $product->get_id(),
                'title'       => get_the_title($post->ID),
                'price'       => wp_strip_all_tags($product->get_price_html()),
                'excerpt'     => $excerpt,
                'image'       => $image,
                'url'         => get_permalink($post->ID),
                'in_stock'    => $product->is_in_stock(),
            ]);
        }

        $cart_page_id = wc_get_page_id('cart');

        if ($cart_page_id && trailingslashit($url) === trailingslashit(get_permalink($cart_page_id))) {

            $items = [];

            foreach (WC()->cart->get_cart() as $cart_item) {

                $product = $cart_item['data'];
                $post_id = $product->get_id();

                $items[] = [
                    'product_id' => $post_id,
                    'title'      => $product->get_name(),
                    'price'      => wp_strip_all_tags($product->get_price_html()),
                    'image'      => has_post_thumbnail($post_id)
                        ? get_the_post_thumbnail_url($post_id, 'medium')
                        : null,
                    'url'        => get_permalink($post_id),
                    'in_stock'   => $product->is_in_stock(),
                    'quantity'   => $cart_item['quantity'],
                ];
            }

            wp_send_json_success([
                'type'       => 'wc_cart',
                'title'      => 'Your Cart',
                'item_count' => WC()->cart->get_cart_contents_count(),
                'total'      => wp_strip_all_tags(WC()->cart->get_cart_total()),
                'items'      => $items,
            ]);
        }

        $shop_page_id = wc_get_page_id('shop');

        if ($shop_page_id && trailingslashit($url) === trailingslashit(get_permalink($shop_page_id))) {

            $query = new WP_Query([
                'post_type'      => 'product',
                'post_status'    => 'publish',
                'posts_per_page' => -1,
            ]);

            $products = [];

            foreach ($query->posts as $post) {

                $product = wc_get_product($post->ID);

                $products[] = [
                    'product_id' => $post->ID,
                    'title'      => get_the_title($post->ID),
                    'price'      => wp_strip_all_tags($product->get_price_html()),
                    'image'      => has_post_thumbnail($post->ID)
                        ? get_the_post_thumbnail_url($post->ID, 'medium')
                        : null,
                    'url'        => get_permalink($post->ID),
                    'in_stock'   => $product->is_in_stock(),
                ];
            }

            wp_send_json_success([
                'type'     => 'wc_shop',
                'title'    => 'Shop',
				'subtitle' => 'Explore our collection and find something perfect for you!',
                'products' => $products,
            ]);
        }

        $checkout_page_id = wc_get_page_id('checkout');

        if ($checkout_page_id && trailingslashit($url) === trailingslashit(get_permalink($checkout_page_id))) {

            wp_send_json_success([
                'type'  => 'wc_checkout',
                'title' => 'Checkout',
                'total' => wp_strip_all_tags(WC()->cart->get_cart_total()),
                'items' => WC()->cart->get_cart_contents_count(),
            ]);
        }
    }

    foreach (['post', 'page'] as $post_type) {

        $query = new WP_Query([
            'name'           => $slug,
            'post_type'      => $post_type,
            'post_status'    => 'publish',
            'posts_per_page' => 1,
        ]);

        if ($query->have_posts()) {

            $post = $query->posts[0];

            $excerpt = !empty($post->post_excerpt)
                ? wp_strip_all_tags($post->post_excerpt)
                : wp_trim_words(wp_strip_all_tags($post->post_content), 30, '…');

            wp_send_json_success([
                'type'    => 'post',
                'title'   => get_the_title($post->ID),
                'excerpt' => $excerpt,
                'image'   => has_post_thumbnail($post->ID)
                    ? get_the_post_thumbnail_url($post->ID, 'medium')
                    : null,
                'url'     => get_permalink($post->ID),
                'date'    => get_the_date('M j, Y', $post->ID),
            ]);
        }
    }

	$attachment_id = attachment_url_to_postid( $url );

	if ( $attachment_id ) {
		$attachment = get_post( $attachment_id );
		$mime       = get_post_mime_type( $attachment_id );
		$file_path  = get_attached_file( $attachment_id );

		$file_size = '';
		if ( $file_path && file_exists( $file_path ) ) {
			$bytes = filesize( $file_path );
			if ( $bytes >= 1048576 ) {
				$file_size = round( $bytes / 1048576, 2 ) . ' MB';
			} elseif ( $bytes >= 1024 ) {
				$file_size = round( $bytes / 1024, 2 ) . ' KB';
			} else {
				$file_size = $bytes . ' B';
			}
		}

		wp_send_json_success( array(
			'type'      => 'attachment',
			'title'     => $attachment->post_title,
			'url'       => $url,
			'mime_type' => $mime,
			'filesize'  => $file_size,
		) );
		return;
	}

	wp_send_json_error( 'Not found' );

}

add_action( 'wp_ajax_mindweco_add_to_cart',        'mindweco_ajax_add_to_cart' );
add_action( 'wp_ajax_nopriv_mindweco_add_to_cart', 'mindweco_ajax_add_to_cart' );
 
function mindweco_ajax_add_to_cart() {
 
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'mindweco_frontend_nonce' ) ) {
        wp_send_json_error( [ 'message' => 'Invalid nonce.' ] );
    }
 
    $product_id = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0;
    $quantity   = isset( $_POST['quantity'] )   ? absint( $_POST['quantity'] )   : 1;
 
    if ( ! $product_id ) {
        wp_send_json_error( [ 'message' => 'Invalid product.' ] );
    }
 
    if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
        wp_send_json_error( [ 'message' => 'WooCommerce not available.' ] );
    }
 
    $added = WC()->cart->add_to_cart( $product_id, $quantity );
 
    if ( $added ) {
        WC_AJAX::get_refreshed_fragments(); 
    } else {
        wp_send_json_error( [ 'message' => 'Could not add product to cart.' ] );
    }
}

