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

use AI_BotKit\Integration\API_Handler;

$api_handler = new API_Handler();

// Get current page and items per page
$current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
$items_per_page = 20;

$session_data = $api_handler->send_get_request('chatbots/' . $bot_id . '/conversations', [
	'page' => $current_page,
	'limit' => $items_per_page,
]);

$sessions = [];
$total_sessions = 0;
$total_pages = 1;
$total_messages = 0;

if (isset($session_data['success']) && $session_data['success'] == true) {
	$data = $session_data['data'];
	$sessions = $data['conversations'];
	$total_sessions = $data['totalConversations'];
	$total_pages = ceil($total_sessions / $items_per_page);
	$total_messages = $data['totalMessages'];
}

$nonce = wp_create_nonce('ai_botkit_chatbots');
?>

<div class="ai-botkit-knowledge-container" id="ai-botkit-sessions-page" data-bot-id="<?php echo esc_attr($bot_id); ?>">

	<!-- 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&nonce=' . $nonce)); ?>">
				<i class="ti ti-arrow-left"></i>
				<?php esc_html_e('Back to Chatbots', 'ai-botkit-for-lead-generation'); ?>
			</a>
			<h1 class="ai-botkit-knowledge-title"><?php esc_html_e('Conversations & Leads', 'ai-botkit-for-lead-generation'); ?></h1>
			<p class="ai-botkit-knowledge-description"><?php esc_html_e('View user interactions and collected leads', 'ai-botkit-for-lead-generation'); ?></p>
		</div>
	</div>

	<!-- Stats Cards -->
	<div class="ai-botkit-knowledge-stats">
		<div class="ai-botkit-knowledge-stats-item">
			<div class="ai-botkit-stats-body">
				<span class="ai-botkit-knowledge-stats-item-label"><?php esc_html_e('Total Sessions', 'ai-botkit-for-lead-generation'); ?></span>
				<span class="ai-botkit-knowledge-stats-item-value"><?php echo esc_html($total_sessions); ?></span>
			</div>
			<div class="ai-botkit-stats-icon">
				<i class="ti ti-message"></i>
			</div>
		</div>
		<div class="ai-botkit-knowledge-stats-item">
			<div class="ai-botkit-stats-body">
				<span class="ai-botkit-knowledge-stats-item-label"><?php esc_html_e('Total Messages', 'ai-botkit-for-lead-generation'); ?></span>
				<span class="ai-botkit-knowledge-stats-item-value"><?php echo esc_html($total_messages); ?></span>
			</div>
			<div class="ai-botkit-stats-icon">
				<i class="ti ti-messages"></i>
			</div>
		</div>
	</div>

	<!-- Tabs -->
	<div class="ai-botkit-sessions-tabs">
		<button class="ai-botkit-sessions-tab active" data-tab="conversations">
			<i class="ti ti-message"></i>
			<?php esc_html_e('Conversations', 'ai-botkit-for-lead-generation'); ?>
		</button>
		<button class="ai-botkit-sessions-tab" data-tab="leads">
			<i class="ti ti-users"></i>
			<?php esc_html_e('Leads', 'ai-botkit-for-lead-generation'); ?>
		</button>
	</div>

	<!-- Conversations Tab Content -->
	<div class="ai-botkit-tab-content active" id="ai-botkit-tab-conversations">
		<?php if (empty($sessions)) { ?>
			<div class="ai-botkit-sessions-empty-state">
				<div class="ai-botkit-sessions-empty-icon">
					<i class="ti ti-message-off"></i>
				</div>
				<h3><?php esc_html_e('No conversations yet', 'ai-botkit-for-lead-generation'); ?></h3>
				<p><?php esc_html_e('Conversations will appear here once users start chatting with your bot.', 'ai-botkit-for-lead-generation'); ?></p>
			</div>
		<?php } else { ?>
			<div class="ai-botkit-split-pane">
				<!-- Left Panel: Conversation List -->
				<div class="ai-botkit-conv-list">
					<div class="ai-botkit-conv-search">
						<div class="ai-botkit-conv-search-wrapper">
							<i class="ti ti-search"></i>
							<input type="text" id="ai-botkit-conv-search-input" placeholder="<?php esc_attr_e('Search conversations...', 'ai-botkit-for-lead-generation'); ?>" />
						</div>
					</div>
					<div class="ai-botkit-conv-items" id="ai-botkit-conv-items">
						<?php foreach ($sessions as $index => $session) {
							$user_name = !empty($session['userName']) ? $session['userName'] : 'Guest #' . substr($session['sessionId'], -6);
							$message_count = isset($session['messageCount']) ? $session['messageCount'] : 0;
							$last_message_at = isset($session['lastMessageAt']) ? $session['lastMessageAt'] : '';
							$time_ago = '';
							if (!empty($last_message_at)) {
								$timestamp = strtotime($last_message_at);
								$time_ago = human_time_diff($timestamp, current_time('timestamp')) . ' ' . __('ago', 'ai-botkit-for-lead-generation');
							}
						?>
							<div class="ai-botkit-conv-item <?php echo $index === 0 ? 'selected' : ''; ?>"
								data-conversation-id="<?php echo esc_attr($session['id']); ?>"
								data-user-name="<?php echo esc_attr($user_name); ?>">
								<div class="ai-botkit-conv-item-avatar">
									<i class="ti ti-user"></i>
								</div>
								<div class="ai-botkit-conv-item-info">
									<div class="ai-botkit-conv-item-top">
										<span class="ai-botkit-conv-item-name"><?php echo esc_html($user_name); ?></span>
										<span class="ai-botkit-conv-item-time"><?php echo esc_html($time_ago); ?></span>
									</div>
									<div class="ai-botkit-conv-item-bottom">
										<span class="ai-botkit-conv-item-preview"><?php echo esc_html(sprintf(_n('%d message', '%d messages', $message_count, 'ai-botkit-for-lead-generation'), $message_count)); ?></span>
									</div>
								</div>
							</div>
						<?php } ?>
					</div>
					<!-- Conversations Pagination -->
					<div class="ai-botkit-conv-pagination" id="ai-botkit-conv-pagination"
						data-current-page="<?php echo esc_attr($current_page); ?>"
						data-total-pages="<?php echo esc_attr($total_pages); ?>">
						<button class="ai-botkit-btn-outline ai-botkit-btn-sm ai-botkit-conv-page-prev" <?php echo $current_page <= 1 ? 'disabled' : ''; ?>>
							<i class="ti ti-chevron-left"></i>
						</button>
						<span class="ai-botkit-conv-page-info">
							<?php echo esc_html($current_page . ' / ' . $total_pages); ?>
						</span>
						<button class="ai-botkit-btn-outline ai-botkit-btn-sm ai-botkit-conv-page-next" <?php echo $current_page >= $total_pages ? 'disabled' : ''; ?>>
							<i class="ti ti-chevron-right"></i>
						</button>
					</div>
				</div>

				<!-- Right Panel: Conversation Detail -->
				<div class="ai-botkit-conv-detail" id="ai-botkit-conv-detail">
					<div class="ai-botkit-conv-detail-placeholder" id="ai-botkit-conv-detail-loading">
						<div class="ai-botkit-spinner"></div>
						<p><?php esc_html_e('Loading conversation...', 'ai-botkit-for-lead-generation'); ?></p>
					</div>
					<div class="ai-botkit-conv-detail-content" id="ai-botkit-conv-detail-content" style="display:none;"></div>
				</div>
			</div>
		<?php } ?>
	</div>

	<!-- Leads Tab Content -->
	<div class="ai-botkit-tab-content" id="ai-botkit-tab-leads" style="display:none;">
		<div class="ai-botkit-leads-container">
			<div class="ai-botkit-leads-loading" id="ai-botkit-leads-loading">
				<div class="ai-botkit-spinner"></div>
				<p><?php esc_html_e('Loading leads...', 'ai-botkit-for-lead-generation'); ?></p>
			</div>
			<div id="ai-botkit-leads-content" style="display:none;">
				<div class="ai-botkit-table-container">
					<table class="ai-botkit-table ai-botkit-leads-table">
						<thead>
							<tr>
								<th><?php esc_html_e('Name', 'ai-botkit-for-lead-generation'); ?></th>
								<th><?php esc_html_e('Email', 'ai-botkit-for-lead-generation'); ?></th>
								<th><?php esc_html_e('Phone', 'ai-botkit-for-lead-generation'); ?></th>
								<th><?php esc_html_e('Date', 'ai-botkit-for-lead-generation'); ?></th>
								<th><?php esc_html_e('Chat', 'ai-botkit-for-lead-generation'); ?></th>
							</tr>
						</thead>
						<tbody id="ai-botkit-leads-tbody"></tbody>
					</table>
				</div>
				<div class="ai-botkit-leads-pagination" id="ai-botkit-leads-pagination"></div>
			</div>
			<div class="ai-botkit-sessions-empty-state" id="ai-botkit-leads-empty" style="display:none;">
				<div class="ai-botkit-sessions-empty-icon">
					<i class="ti ti-user-off"></i>
				</div>
				<h3><?php esc_html_e('No leads collected yet', 'ai-botkit-for-lead-generation'); ?></h3>
				<p><?php esc_html_e('Leads will appear here once users submit their contact information through the chatbot.', 'ai-botkit-for-lead-generation'); ?></p>
			</div>
		</div>
	</div>
</div>
