<?php
defined('ABSPATH') || exit;

use AI_BotKit\Integration\API_Handler;

$nonce = wp_create_nonce('ai_botkit_chatbots');

$api_handler = new API_Handler();

$session_data = $api_handler->send_get_request('conversations/' . $chat_session_id);

if (isset($session_data['success']) && $session_data['success'] === false) {
	$bot_id = isset($_GET['bot_id']) ? intval($_GET['bot_id']) : 0;
	?>
	<div class="ai-botkit-knowledge-container">
		<div class="ai-botkit-knowledge-header">
			<div class="ai-botkit-knowledge-header-left">
				<a class="ai-botkit-btn-outline ai-botkit-btn-sm" href="<?php echo esc_url(admin_url('admin.php?page=ai-botkit&tab=chatbots&bot_id=' . $bot_id . '&nonce=' . $nonce)); ?>">
					<i class="ti ti-arrow-left"></i>
					<?php esc_html_e('Back to Conversations', 'ai-botkit-for-lead-generation'); ?>
				</a>
				<h1 class="ai-botkit-knowledge-title"><?php esc_html_e('Conversation not found', 'ai-botkit-for-lead-generation'); ?></h1>
			</div>
		</div>
	</div>
	<?php
	wp_die();
}

$session_data = $session_data['data'];
$messages = $session_data['messages'];
$total_messages = count($messages);
$date = gmdate('M j, Y', strtotime($session_data['createdAt']));
$time = gmdate('g:i A', strtotime($session_data['createdAt']));
$chatbot_name = $session_data['chatbotName'];
$user_name = isset($session_data['user']['userName']) ? $session_data['user']['userName'] : 'Guest #' . substr($session_data['sessionId'], -6);
$has_form_data = isset($session_data['dataCollectionSubmissions']) && !empty($session_data['dataCollectionSubmissions']);

?>

<div class="ai-botkit-knowledge-container">

	<!-- Page Heading -->
	<div class="ai-botkit-knowledge-header">
		<div class="ai-botkit-knowledge-header-left">
			<a class="ai-botkit-btn-outline ai-botkit-btn-sm" href="<?php echo esc_url(admin_url('admin.php?page=ai-botkit&tab=chatbots&bot_id=' . $session_data['chatbotId'] . '&nonce=' . $nonce)); ?>">
				<i class="ti ti-arrow-left"></i>
				<?php esc_html_e('Back to Conversations', 'ai-botkit-for-lead-generation'); ?>
			</a>
			<h1 class="ai-botkit-knowledge-title"><?php esc_html_e('Conversation', 'ai-botkit-for-lead-generation'); ?></h1>
		</div>
	</div>

	<div class="ai-botkit-chat-session-container">
		<!-- Left Sidebar: Session Details -->
		<div class="ai-botkit-chat-session-details">
			<div class="ai-botkit-chat-session-details-item">
				<h2><?php esc_html_e('Session Details', 'ai-botkit-for-lead-generation'); ?></h2>
			</div>
			<div class="ai-botkit-chat-session-details-item">
				<p><?php esc_html_e('User', 'ai-botkit-for-lead-generation'); ?></p>
				<p><i class="ti ti-user"></i> <?php echo esc_html($user_name); ?></p>
			</div>
			<div class="ai-botkit-chat-session-details-item">
				<p><?php esc_html_e('Chatbot', 'ai-botkit-for-lead-generation'); ?></p>
				<p><i class="ti ti-robot"></i> <?php echo esc_html($chatbot_name); ?></p>
			</div>
			<div class="ai-botkit-chat-session-details-item">
				<p><?php esc_html_e('Date', 'ai-botkit-for-lead-generation'); ?></p>
				<p><i class="ti ti-calendar"></i> <?php echo esc_html($date); ?></p>
			</div>
			<div class="ai-botkit-chat-session-details-item">
				<p><?php esc_html_e('Time', 'ai-botkit-for-lead-generation'); ?></p>
				<p><i class="ti ti-clock"></i> <?php echo esc_html($time); ?></p>
			</div>
			<div class="ai-botkit-chat-session-details-item">
				<p><?php esc_html_e('Messages', 'ai-botkit-for-lead-generation'); ?></p>
				<p><i class="ti ti-message"></i> <?php echo esc_html($total_messages); ?></p>
			</div>

			<?php if ($has_form_data) { ?>
				<div class="ai-botkit-chat-session-details-divider"></div>
				<div class="ai-botkit-chat-session-details-item">
					<h2><?php esc_html_e('Contact Form Data', 'ai-botkit-for-lead-generation'); ?></h2>
				</div>
				<?php if (isset($session_data['dataCollectionSubmissions'][0]['name'])) { ?>
				<div class="ai-botkit-chat-session-details-item">
					<p><?php esc_html_e('Name', 'ai-botkit-for-lead-generation'); ?></p>
					<p><i class="ti ti-user"></i> <?php echo esc_html($session_data['dataCollectionSubmissions'][0]['name']); ?></p>
				</div>
				<?php } ?>
				<?php if (isset($session_data['dataCollectionSubmissions'][0]['email'])) { ?>
				<div class="ai-botkit-chat-session-details-item">
					<p><?php esc_html_e('Email', 'ai-botkit-for-lead-generation'); ?></p>
					<p><i class="ti ti-mail"></i> <?php echo esc_html($session_data['dataCollectionSubmissions'][0]['email']); ?></p>
				</div>
				<?php } ?>
				<?php if (isset($session_data['dataCollectionSubmissions'][0]['phone'])) { ?>
				<div class="ai-botkit-chat-session-details-item">
					<p><?php esc_html_e('Phone', 'ai-botkit-for-lead-generation'); ?></p>
					<p><i class="ti ti-phone"></i> <?php echo esc_html($session_data['dataCollectionSubmissions'][0]['phone']); ?></p>
				</div>
				<?php } ?>
			<?php } ?>
		</div>

		<!-- Right Panel: Messages -->
		<div class="ai-botkit-chat-session-messages">
			<div class="ai-botkit-chat-session-messages-header">
				<span class="ai-botkit-chat-session-messages-item-label"><?php esc_html_e('Messages', 'ai-botkit-for-lead-generation'); ?></span>
				<span class="ai-botkit-chat-session-msg-count"><?php echo esc_html($total_messages); ?> <?php esc_html_e('messages', 'ai-botkit-for-lead-generation'); ?></span>
			</div>
			<div class="ai-botkit-chat-body" id="ai-botkit-chat-body">
				<?php foreach ($messages as $message) {
					$is_user = $message['role'] === 'user';
					$msg_class = $is_user ? 'user-msg' : 'bot-msg';
				?>
					<div class="ai-botkit-chat-msg <?php echo esc_attr($msg_class); ?>">
						<p data-raw-content="<?php echo esc_attr($message['content']); ?>"><?php echo esc_html($message['content']); ?></p>
					</div>
				<?php } ?>
			</div>
		</div>
	</div>
</div>
<script>
(function() {
    var md = { marked: null, dompurify: null, ready: false };

    function loadMarkdownDeps() {
        try {
            Promise.all([
                import('https://esm.sh/marked@14.1.0'),
                import('https://esm.sh/dompurify@3.1.0')
            ]).then(function(mods) {
                var markedMod = mods[0];
                var purifyMod = mods[1];
                md.marked = markedMod.marked || markedMod.default || markedMod;
                md.dompurify = purifyMod.default || purifyMod;
                if (typeof md.marked.setOptions === 'function') {
                    md.marked.setOptions({ gfm: true, breaks: false });
                }
                md.ready = true;
                renderMarkdownMessages();
            }).catch(function(err) {
                console.warn('[AI BotKit] Markdown libs failed to load; falling back to legacy render.', err);
            });
        } catch (err) {
            console.warn('[AI BotKit] Markdown libs failed to load; falling back to legacy render.', err);
        }
    }

    var ALLOWED_TAGS = [
        'p', 'br',
        'strong', 'b', 'em', 'i',
        'ul', 'ol', 'li',
        'a',
        'code', 'pre',
        'h3', 'h4',
        'blockquote', 'hr',
        'table', 'thead', 'tbody', 'tr', 'td', 'th',
    ];
    var ALLOWED_ATTR = ['href', 'title', 'class', 'target', 'rel'];

    function aibkSanitize(html) {
        if (md.dompurify && typeof md.dompurify.sanitize === 'function') {
            return md.dompurify.sanitize(html, {
                ALLOWED_TAGS: ALLOWED_TAGS,
                ALLOWED_ATTR: ALLOWED_ATTR,
                ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto):)/i,
            });
        }
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(html));
        return div.innerHTML;
    }

    function renderChatContent(content, contentFormat) {
        var format = contentFormat === 'html' ? 'html' : 'markdown';
        if (!md.ready || !md.dompurify) {
            return aibkSanitize(content);
        }
        if (format === 'html') {
            return aibkSanitize(content);
        }
        try {
            var raw = md.marked.parse(String(content));
            return aibkSanitize(raw);
        } catch (e) {
            console.warn('[AI BotKit] Markdown parse failed; rendering as escaped text.', e);
            return aibkSanitize(content);
        }
    }

    function renderMarkdownMessages() {
        document.querySelectorAll('.ai-botkit-chat-msg:not(.user-msg) p[data-raw-content]').forEach(function(p) {
            var raw = p.getAttribute('data-raw-content');
            var format = p.parentElement.getAttribute('data-content-format') || 'markdown';
            p.innerHTML = renderChatContent(raw, format);
        });
    }

    loadMarkdownDeps();
})();
</script>
