<?php
/**
 * Admin chat logs template for Ask Any plugin
 *
 * This template displays the chat logs interface with:
 * - Paginated chat logs
 * - Search and filters
 * - Clear functionality
 * - Detailed message view
 *
 * @package Askany
 * @since 1.0.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Get initial paginated data
$database = new \Askany\Database();
$initial_data = $database->get_paginated_chat_logs(1, 20);
?>

<div class="wrap askany-admin-page">
	<div class="section-header">
		<h1><?php esc_html_e( 'Chat Logs', 'askany' ); ?></h1>
		<div class="section-actions">
			<button type="button" class="button" id="refresh-chat-logs"><?php esc_html_e( 'Refresh', 'askany' ); ?></button>
			<button type="button" class="button button-secondary" id="clear-old-chat-logs"><?php esc_html_e( 'Clear Old Logs', 'askany' ); ?></button>
			<button type="button" class="button button-link-delete" id="clear-all-chat-logs"><?php esc_html_e( 'Clear All Logs', 'askany' ); ?></button>
		</div>
	</div>

	<!-- Filters -->
	<div class="chat-logs-filters">
		<label for="logs-per-page"><?php esc_html_e( 'Show:', 'askany' ); ?></label>
		<select id="logs-per-page">
			<option value="10">10 <?php esc_html_e( 'per page', 'askany' ); ?></option>
			<option value="20" selected>20 <?php esc_html_e( 'per page', 'askany' ); ?></option>
			<option value="50">50 <?php esc_html_e( 'per page', 'askany' ); ?></option>
			<option value="100">100 <?php esc_html_e( 'per page', 'askany' ); ?></option>
		</select>
		
		<div class="search-box">
			<input type="text" id="search-logs" placeholder="<?php esc_attr_e( 'Search messages...', 'askany' ); ?>">
			<button type="button" class="button" id="search-logs-btn"><?php esc_html_e( 'Search', 'askany' ); ?></button>
			<button type="button" class="button button-secondary" id="clear-search-btn" style="display: none;"><?php esc_html_e( 'Clear', 'askany' ); ?></button>
		</div>
	</div>

	<!-- Chat Logs Container -->
	<div id="chat-logs-container">
		<!-- Initial logs will be loaded here -->
	</div>

	<!-- Pagination -->
	<div id="chat-logs-pagination" class="tablenav">
		<!-- Pagination will be loaded here -->
	</div>

	<!-- Message Detail Modal -->
	<div id="message-detail-modal" class="askany-modal" style="display: none;">
		<div class="askany-modal-content">
			<div class="askany-modal-header">
				<h3><?php esc_html_e( 'Message Details', 'askany' ); ?></h3>
				<span class="askany-modal-close">&times;</span>
			</div>
			<div class="askany-modal-body">
				<div id="message-detail-content">
					<!-- Message details will be loaded here -->
				</div>
			</div>
		</div>
	</div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
	let currentPage = 1;
	let logsPerPage = 20;
	let searchQuery = '';

	// Load initial data
	loadChatLogs(1);

	// Filter changes
	document.getElementById('logs-per-page').addEventListener('change', function() {
		logsPerPage = parseInt(this.value);
		loadChatLogs(1);
	});

	// Search functionality
	document.getElementById('search-logs-btn').addEventListener('click', function() {
		const newSearchQuery = document.getElementById('search-logs').value.trim();
		if (newSearchQuery !== searchQuery) {
			searchQuery = newSearchQuery;
			if (searchQuery) {
				// Use Toast to show search status
				Toast.info('<?php esc_html_e( 'Searching for:', 'askany' ); ?> "' + searchQuery + '"');
			}
			loadChatLogs(1);
		}
	});

	document.getElementById('search-logs').addEventListener('keypress', function(e) {
		if (e.key === 'Enter') {
			const newSearchQuery = this.value.trim();
			if (newSearchQuery !== searchQuery) {
				searchQuery = newSearchQuery;
				if (searchQuery) {
					// Use Toast to show search status
					Toast.info('<?php esc_html_e( 'Searching for:', 'askany' ); ?> "' + searchQuery + '"');
				}
				loadChatLogs(1);
			}
		}
	});

	// Clear search functionality
	document.getElementById('search-logs').addEventListener('input', function(e) {
		const clearBtn = document.getElementById('clear-search-btn');
		if (this.value.trim()) {
			clearBtn.style.display = 'inline-block';
		} else {
			clearBtn.style.display = 'none';
			if (searchQuery !== '') {
				searchQuery = '';
				// Use Toast to show search cleared
				Toast.info('<?php esc_html_e( 'Search cleared. Showing all logs.', 'askany' ); ?>');
				loadChatLogs(1);
			}
		}
	});

	// Clear search button functionality
	document.getElementById('clear-search-btn').addEventListener('click', function() {
		document.getElementById('search-logs').value = '';
		this.style.display = 'none';
		if (searchQuery !== '') {
			searchQuery = '';
			// Use Toast to show search cleared
			Toast.info('<?php esc_html_e( 'Search cleared. Showing all logs.', 'askany' ); ?>');
			loadChatLogs(1);
		}
	});

	// Refresh button
	document.getElementById('refresh-chat-logs').addEventListener('click', function() {
		loadChatLogs(currentPage);
	});

	// Clear logs functionality
	document.getElementById('clear-old-chat-logs').addEventListener('click', function() {
		Toast.ask('<?php esc_html_e( 'Clear Old Logs', 'askany' ); ?>', '<?php esc_html_e( 'Are you sure you want to clear chat logs older than 30 days?', 'askany' ); ?>')
			.then(result => {
				if (result.ok) {
					clearChatLogs(30);
				}
			});
	});

	document.getElementById('clear-all-chat-logs').addEventListener('click', function() {
		Toast.ask('<?php esc_html_e( 'Clear All Logs', 'askany' ); ?>', '<?php esc_html_e( 'Are you sure you want to clear ALL chat logs? This action cannot be undone.', 'askany' ); ?>')
			.then(result => {
				if (result.ok) {
					clearChatLogs(0);
				}
			});
	});

	// Modal functionality
	const messageModal = document.getElementById('message-detail-modal');
	const modalClose = messageModal.querySelector('.askany-modal-close');

	modalClose.addEventListener('click', function() {
		messageModal.style.display = 'none';
	});

	window.addEventListener('click', function(event) {
		if (event.target === messageModal) {
			messageModal.style.display = 'none';
		}
	});

	// Load chat logs function
	function loadChatLogs(page) {
		currentPage = page;
		
		const container = document.getElementById('chat-logs-container');
		container.innerHTML = '<div class="loading"><?php esc_html_e( 'Loading chat logs...', 'askany' ); ?></div>';

		jQuery.post(ajaxurl, {
			action: 'askany_get_paginated_chat_logs',
			nonce: '<?php echo wp_create_nonce( 'askany_chat_nonce' ); ?>',
			page: page,
			per_page: logsPerPage,
			search: searchQuery
		}, function(response) {
			if (response.success) {
				displayChatLogs(response.data);
			} else {
				container.innerHTML = '<div class="error">' + response.data.message + '</div>';
				// Use Toast for error notification
				Toast.error('<?php esc_html_e( 'Error loading chat logs:', 'askany' ); ?> ' + response.data.message);
			}
		}).fail(function() {
			container.innerHTML = '<div class="error"><?php esc_html_e( 'Network error. Please try again.', 'askany' ); ?></div>';
			// Use Toast for network error
			Toast.error('<?php esc_html_e( 'Network error. Please try again.', 'askany' ); ?>');
		});
	}

	// Display chat logs
	function displayChatLogs(data) {
		const container = document.getElementById('chat-logs-container');
		const paginationContainer = document.getElementById('chat-logs-pagination');

		if (data.logs.length === 0) {
			let noDataMessage = '<?php esc_html_e( 'No chat logs found.', 'askany' ); ?>';
			if (searchQuery) {
				noDataMessage = '<?php esc_html_e( 'No chat logs found matching your search:', 'askany' ); ?> "' + searchQuery + '"';
				// Use Toast to show no results
				if (typeof Toast !== 'undefined') {
					Toast.warning('<?php esc_html_e( 'No results found for:', 'askany' ); ?> "' + searchQuery + '"');
				}
			}
			container.innerHTML = '<div class="no-data">' + noDataMessage + '</div>';
			paginationContainer.innerHTML = '';
			return;
		}

		// Show search results count if searching
		if (searchQuery && typeof Toast !== 'undefined') {
			const totalResults = data.pagination.total_logs;
			Toast.success('<?php esc_html_e( 'Found', 'askany' ); ?> ' + totalResults + ' <?php esc_html_e( 'results for:', 'askany' ); ?> "' + searchQuery + '"');
		}

		// Build logs table
		let html = '<table class="wp-list-table widefat fixed striped">';
		html += '<thead><tr>';
		html += '<th style="width: 150px;"><?php esc_html_e( 'Date', 'askany' ); ?></th>';
		html += '<th><?php esc_html_e( 'User Message', 'askany' ); ?></th>';
		html += '<th><?php esc_html_e( 'AI Response', 'askany' ); ?></th>';
		html += '<th style="width: 100px;"><?php esc_html_e( 'Actions', 'askany' ); ?></th>';
		html += '</tr></thead><tbody>';

		data.logs.forEach(function(log) {
			const date = new Date(log.created_at);
			const formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
			const shortMessage = log.message.length > 80 ? log.message.substring(0, 80) + '...' : log.message;
			const shortResponse = log.response.length > 80 ? log.response.substring(0, 80) + '...' : log.response;

			html += '<tr>';
			html += '<td>' + formattedDate + '</td>';
			html += '<td class="message-text" title="' + escapeHtml(log.message) + '">' + escapeHtml(shortMessage) + '</td>';
			html += '<td class="response-text" title="' + escapeHtml(log.response) + '">' + escapeHtml(shortResponse) + '</td>';
			html += '<td><button type="button" class="button button-small view-details" data-id="' + log.id + '"><?php esc_html_e( 'View', 'askany' ); ?></button></td>';
			html += '</tr>';
		});

		html += '</tbody></table>';
		container.innerHTML = html;

		// Add click handlers for view details
		container.querySelectorAll('.view-details').forEach(function(button) {
			button.addEventListener('click', function() {
				const logId = this.getAttribute('data-id');
				const log = data.logs.find(l => l.id == logId);
				showMessageDetails(log);
			});
		});

		// Build pagination
		buildChatLogsPagination(data.pagination);
	}

	// Show message details in modal
	function showMessageDetails(log) {
		const date = new Date(log.created_at);
		const formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
		
		let html = '<div class="message-details">';
		html += '<div class="detail-row"><strong><?php esc_html_e( 'Date:', 'askany' ); ?></strong> ' + formattedDate + '</div>';
		html += '<div class="detail-row"><strong><?php esc_html_e( 'User Message:', 'askany' ); ?></strong></div>';
		html += '<div class="message-content user-message">' + escapeHtml(log.message).replace(/\n/g, '<br>') + '</div>';
		html += '<div class="detail-row"><strong><?php esc_html_e( 'AI Response:', 'askany' ); ?></strong></div>';
		html += '<div class="message-content ai-response">' + escapeHtml(log.response).replace(/\n/g, '<br>') + '</div>';
		html += '</div>';

		document.getElementById('message-detail-content').innerHTML = html;
		document.getElementById('message-detail-modal').style.display = 'block';
	}

	// Build pagination controls
	function buildChatLogsPagination(pagination) {
		const container = document.getElementById('chat-logs-pagination');
		
		if (pagination.total_pages <= 1) {
			container.innerHTML = '';
			return;
		}

		let html = '<div class="tablenav-pages">';
		html += '<span class="displaying-num">' + pagination.total_logs + ' <?php esc_html_e( 'logs', 'askany' ); ?></span>';
		html += '<span class="pagination-links">';

		// First/Previous
		if (pagination.current_page > 1) {
			html += '<a class="first-page button" href="#" data-page="1">&laquo;</a>';
			html += '<a class="prev-page button" href="#" data-page="' + (pagination.current_page - 1) + '">&lsaquo;</a>';
		} else {
			html += '<span class="tablenav-pages-navspan button disabled">&laquo;</span>';
			html += '<span class="tablenav-pages-navspan button disabled">&lsaquo;</span>';
		}

		// Page input
		html += '<span class="paging-input">';
		html += '<input class="current-page" type="text" value="' + pagination.current_page + '" size="2">';
		html += '<span class="tablenav-paging-text"> <?php esc_html_e( 'of', 'askany' ); ?> <span class="total-pages">' + pagination.total_pages + '</span></span>';
		html += '</span>';

		// Next/Last
		if (pagination.current_page < pagination.total_pages) {
			html += '<a class="next-page button" href="#" data-page="' + (pagination.current_page + 1) + '">&rsaquo;</a>';
			html += '<a class="last-page button" href="#" data-page="' + pagination.total_pages + '">&raquo;</a>';
		} else {
			html += '<span class="tablenav-pages-navspan button disabled">&rsaquo;</span>';
			html += '<span class="tablenav-pages-navspan button disabled">&raquo;</span>';
		}

		html += '</span></div>';
		container.innerHTML = html;

		// Add pagination click handlers
		container.querySelectorAll('a[data-page]').forEach(function(link) {
			link.addEventListener('click', function(e) {
				e.preventDefault();
				const page = parseInt(this.getAttribute('data-page'));
				loadChatLogs(page);
			});
		});

		// Handle direct page input
		const pageInput = container.querySelector('.current-page');
		pageInput.addEventListener('keypress', function(e) {
			if (e.key === 'Enter') {
				const page = parseInt(this.value);
				if (page >= 1 && page <= pagination.total_pages) {
					loadChatLogs(page);
				}
			}
		});
	}

	// Clear chat logs function
	function clearChatLogs(days) {
		const button = days === 0 ? document.getElementById('clear-all-chat-logs') : document.getElementById('clear-old-chat-logs');
		const originalText = button.textContent;
		
		button.textContent = '<?php esc_html_e( 'Clearing...', 'askany' ); ?>';
		button.disabled = true;

		jQuery.post(ajaxurl, {
			action: 'askany_clear_chat_logs',
			nonce: '<?php echo wp_create_nonce( 'askany_chat_nonce' ); ?>',
			days: days
		}, function(response) {
			if (response.success) {
				// Use Toastmaster for success notification
				Toast.success(response.data.message);
				// Reload first page after a short delay
				setTimeout(function() {
					loadChatLogs(1);
				}, 1000);
			} else {
				// Use Toastmaster for error notification
				Toast.error('<?php esc_html_e( 'Error:', 'askany' ); ?> ' + response.data.message);
			}
		}).fail(function() {
			// Use Toastmaster for network error
			Toast.error('<?php esc_html_e( 'Network error. Please try again.', 'askany' ); ?>');
		}).always(function() {
			button.textContent = originalText;
			button.disabled = false;
		});
	}

	// Utility function to escape HTML
	function escapeHtml(text) {
		const div = document.createElement('div');
		div.textContent = text;
		return div.innerHTML;
	}
});
</script>

<style>
.askany-admin-page .section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
	padding-bottom: 10px;
	border-bottom: 1px solid #ddd;
}

.askany-admin-page .section-actions {
	display: flex;
	gap: 10px;
}

.chat-logs-filters {
	display: flex;
	align-items: center;
	gap: 20px;
	margin-bottom: 20px;
	padding: 15px;
	background: #f9f9f9;
	border: 1px solid #ddd;
	border-radius: 5px;
}

.chat-logs-filters label {
	font-weight: 500;
	color: #333;
}

.chat-logs-filters select {
	padding: 5px 8px;
	border: 1px solid #ddd;
	border-radius: 3px;
	background: #fff;
}

.search-box {
	display: flex;
	gap: 5px;
	margin-left: auto;
}

.search-box input {
	padding: 5px 10px;
	border: 1px solid #ddd;
	border-radius: 3px;
	width: 200px;
}

.message-text, .response-text {
	font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	line-height: 1.4;
	word-break: break-word;
}

.message-details {
	font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.detail-row {
	margin-bottom: 15px;
}

.message-content {
	background: #f9f9f9;
	border: 1px solid #ddd;
	border-radius: 5px;
	padding: 15px;
	margin-bottom: 20px;
	line-height: 1.6;
	white-space: pre-wrap;
	word-break: break-word;
}

.user-message {
	border-left: 4px solid #0073aa;
}

.ai-response {
	border-left: 4px solid #00a32a;
}

.loading {
	text-align: center;
	padding: 40px;
	color: #666;
	font-style: italic;
}

.loading:before {
	content: '';
	display: inline-block;
	width: 20px;
	height: 20px;
	border: 2px solid #ddd;
	border-top: 2px solid #0073aa;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-right: 10px;
	vertical-align: middle;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.no-data {
	text-align: center;
	padding: 40px;
	color: #666;
	font-style: italic;
	background: #f9f9f9;
	border: 1px solid #ddd;
	border-radius: 5px;
}

/* Modal styles (reuse from API stats) */
.askany-modal {
	position: fixed;
	z-index: 100000;
	right: 0;
	top: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	backdrop-filter: blur(2px);
}

.askany-modal-content {
	background-color: #fff;
	margin: 5% auto;
	padding: 0;
	border: 1px solid #ddd;
	border-radius: 8px;
	width: 90%;
	max-width: 800px;
	max-height: 80vh;
	overflow: hidden;
	box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.askany-modal-header {
	padding: 20px;
	background: #f9f9f9;
	border-bottom: 1px solid #ddd;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.askany-modal-header h3 {
	margin: 0;
	color: #333;
}

.askany-modal-close {
	color: #666;
	font-size: 28px;
	font-weight: bold;
	cursor: pointer;
	line-height: 1;
	padding: 0 5px;
}

.askany-modal-close:hover {
	color: #000;
}

.askany-modal-body {
	padding: 20px;
	max-height: 60vh;
	overflow-y: auto;
}

/* Pagination styles (reuse from API stats) */
.tablenav {
	margin-top: 20px;
	padding: 10px 0;
	border-top: 1px solid #ddd;
}

.tablenav-pages {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.displaying-num {
	color: #666;
	font-size: 13px;
}

.pagination-links {
	display: flex;
	align-items: center;
	gap: 5px;
}

.pagination-links .button {
	min-width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
	text-decoration: none;
	border: 1px solid #ddd;
	background: #fff;
	color: #0073aa;
	font-size: 14px;
}

.pagination-links .button:hover {
	background: #f0f0f0;
	border-color: #999;
}

.pagination-links .button.disabled {
	color: #ccc;
	cursor: not-allowed;
	background: #f9f9f9;
}

.paging-input {
	display: flex;
	align-items: center;
	gap: 5px;
	margin: 0 10px;
}

.current-page {
	width: 50px;
	text-align: center;
	padding: 4px;
	border: 1px solid #ddd;
	border-radius: 3px;
}

.tablenav-paging-text {
	color: #666;
	font-size: 13px;
}

/* Responsive design */
@media (max-width: 768px) {
	.askany-admin-page .section-header {
		flex-direction: column;
		align-items: flex-start;
		gap: 15px;
	}
	
	.askany-admin-page .section-actions {
		width: 100%;
		justify-content: flex-start;
		flex-wrap: wrap;
	}
	
	.chat-logs-filters {
		flex-direction: column;
		align-items: flex-start;
		gap: 15px;
	}
	
	.search-box {
		margin-left: 0;
		width: 100%;
	}
	
	.search-box input {
		flex: 1;
		width: auto;
	}
	
	.askany-modal-content {
		width: 95%;
		margin: 2% auto;
		max-height: 95vh;
	}
	
	.tablenav-pages {
		flex-direction: column;
		gap: 10px;
		align-items: center;
	}
	
	.pagination-links {
		flex-wrap: wrap;
		justify-content: center;
	}
}
</style>