<?php
/**
 * Writing Jobs Settings Page
 *
 * @package    Spawnster
 * @subpackage Spawnster/admin/partials
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// Save settings if form is submitted
if ( isset( $_POST['submit'] ) && wp_verify_nonce( $_POST['spawnster_nonce'], 'spawnster_nonce' ) ) {
	$settings = array(
		'spawnster_google_api_key' => sanitize_text_field( $_POST['spawnster_google_api_key'] ),
		'spawnster_google_search_engine_id' => sanitize_text_field( $_POST['spawnster_google_search_engine_id'] ),
	);
	
	update_option( 'spawnster_settings', $settings );
	echo '<div class="notice notice-success"><p>' . __( 'Settings saved successfully!', 'spawnster' ) . '</p></div>';
}

$current_settings = get_option( 'spawnster_settings', array() );
?>

<div class="wrap">
	<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
	
	<form method="post" action="">
		<?php wp_nonce_field( 'spawnster_nonce', 'spawnster_nonce' ); ?>
		
		<table class="form-table">
			<tr>
				<th scope="row">
					<label for="spawnster_google_api_key"><?php _e( 'Google Search API Key', 'spawnster' ); ?></label>
				</th>
				<td>
					<input type="password" id="spawnster_google_api_key" name="spawnster_google_api_key" 
						   value="<?php echo esc_attr( $current_settings['spawnster_google_api_key'] ?? '' ); ?>" 
						   class="regular-text">
					<p class="description">
						<?php _e( 'Google Custom Search API key for content research (optional).', 'spawnster' ); ?>
						<a href="https://developers.google.com/custom-search/v1/overview" target="_blank"><?php _e( 'Learn more', 'spawnster' ); ?></a>
					</p>
				</td>
			</tr>
			
			<tr>
				<th scope="row">
					<label for="spawnster_google_search_engine_id"><?php _e( 'Google Search Engine ID', 'spawnster' ); ?></label>
				</th>
				<td>
					<input type="text" id="spawnster_google_search_engine_id" name="spawnster_google_search_engine_id" 
						   value="<?php echo esc_attr( $current_settings['spawnster_google_search_engine_id'] ?? '' ); ?>" 
						   class="regular-text">
					<p class="description">
						<?php _e( 'Google Custom Search Engine ID (required if using Google Search API).', 'spawnster' ); ?>
						<a href="https://cse.google.com/cse/" target="_blank"><?php _e( 'Create search engine', 'spawnster' ); ?></a>
					</p>
				</td>
			</tr>
		</table>
		
		<h2><?php _e( 'Content Similarity Search', 'spawnster' ); ?></h2>
		<p><?php _e( 'Test the vector similarity search functionality and remote API key fetching:', 'spawnster' ); ?></p>
		
		<table class="form-table">
			<tr>
				<th scope="row">
					<label for="similarity_query"><?php _e( 'Search Query', 'spawnster' ); ?></label>
				</th>
				<td>
					<input type="text" id="similarity_query" class="regular-text" 
						   placeholder="<?php _e( 'Enter a topic or keyword to search for similar content', 'spawnster' ); ?>">
					<input type="number" id="similarity_limit" class="small-text" value="5" min="1" max="20" style="margin-left: 10px;">
					<button type="button" id="search_similar" class="button"><?php _e( 'Search', 'spawnster' ); ?></button>
					<span class="spinner" style="float: none; margin-left: 10px;"></span>
				</td>
			</tr>
		</table>
		
		<div id="similarity_results" style="display: none;">
			<h3><?php _e( 'Similar Content Results', 'spawnster' ); ?></h3>
			<div id="similarity_results_content"></div>
		</div>

		<p class="submit">
			<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e( 'Save Settings', 'spawnster' ); ?>">
		</p>
	</form>
</div>

<script>
jQuery(document).ready(function($) {
	// Handle similarity search
	$('#search_similar').click(function() {
		var query = $('#similarity_query').val();
		var limit = $('#similarity_limit').val();
		
		if (!query) {
			alert('Please enter a search query.');
			return;
		}
		
		var $button = $(this);
		var $spinner = $button.siblings('.spinner');
		
		$button.prop('disabled', true);
		$spinner.css('visibility', 'visible');
		
		console.log('Sending AJAX request with:', {query: query, limit: limit});
		
		$.ajax({
			url: spawnster.ajax_url,
			type: 'POST',
			data: {
				action: 'search_similar_content',
				nonce: $('#spawnster_nonce').val(),
				query: query,
				limit: limit
			},
			success: function(response) {
				console.log('AJAX Response received:', response);
				
				if (response.success) {
					console.log('Response data:', response.data);
					
					var html = '<table class="wp-list-table widefat fixed striped">';
					html += '<thead><tr>';
					html += '<th>Post ID</th>';
					html += '<th>Title</th>';
					html += '<th>Similarity Score</th>';
					html += '<th>Actions</th>';
					html += '</tr></thead><tbody>';
					
					if (response.data.posts && response.data.posts.length > 0) {
						console.log('Processing posts:', response.data.posts);
						response.data.posts.forEach(function(post) {
							console.log('Processing post:', post);
							html += '<tr>';
							html += '<td>' + (post.ID || 'N/A') + '</td>';
							html += '<td>' + (post.title ? post.title : 'No title') + '</td>';
							html += '<td>' + (post.similarity ? (post.similarity * 100).toFixed(2) + '%' : 'N/A') + '</td>';
							html += '<td><a href="post.php?post=' + (post.ID || '') + '&action=edit" target="_blank">Edit Post</a></td>';
							html += '</tr>';
						});
					} else {
						console.log('No posts found in response');
						html += '<tr><td colspan="4">No similar content found.</td></tr>';
					}
					
					html += '</tbody></table>';
					
					// Add API key status if provided
					if (response.data.api_key_status) {
						html = '<div class="notice notice-info"><p><strong>API Key Status:</strong> ' + response.data.api_key_status + '</p></div>' + html;
					}
					
					$('#similarity_results_content').html(html);
					$('#similarity_results').show();
				} else {
					console.error('Response indicates failure:', response);
					alert('Error searching for similar content: ' + (response.data || 'Unknown error'));
				}
			},
			error: function(xhr, status, error) {
				console.error('AJAX Error Details:', {
					xhr: xhr,
					status: status,
					error: error,
					responseText: xhr.responseText
				});
				
				// Try to parse the response text for more details
				try {
					var responseData = JSON.parse(xhr.responseText);
					console.log('Parsed error response:', responseData);
					alert('Error searching for similar content. Check console for details. Server response: ' + (responseData.data || error));
				} catch (e) {
					console.log('Could not parse error response as JSON');
					alert('Error searching for similar content. Check browser console for details. Status: ' + status + ', Error: ' + error);
				}
			},
			complete: function() {
				$button.prop('disabled', false);
				$spinner.css('visibility', 'hidden');
			}
		});
	});
	
	// Handle Enter key in search field
	$('#similarity_query').keypress(function(e) {
		if (e.which === 13) {
			$('#search_similar').click();
		}
	});
});
</script> 