<?php
/**
 * Prompt History
 *
 * This file contains all prompt history functionality.
 *
 * @package Simple_Ai_Auto_Post
 * @since 1.0.0
 */

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

// Make sure this file is being included by a parent file.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Create database tables for prompt history
 */
function saiap_create_prompt_tables() {
	global $wpdb;
	$charset_collate = $wpdb->get_charset_collate();

	// Create prompts table
	$table_name = $wpdb->prefix . 'saiap_prompts';
	$sql1       = "CREATE TABLE $table_name (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        prompt TEXT NOT NULL,
        system_prompt TEXT NOT NULL,
        model VARCHAR(50) NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        user_id BIGINT(20) UNSIGNED NOT NULL,
        PRIMARY KEY (id),
        KEY user_id (user_id)
    ) $charset_collate;";

	// Create prompt-post relationship table
	$table_name_rel = $wpdb->prefix . 'saiap_prompt_posts';
	$sql2           = "CREATE TABLE $table_name_rel (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        prompt_id BIGINT(20) UNSIGNED NOT NULL,
        post_id BIGINT(20) UNSIGNED NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY prompt_post (prompt_id, post_id),
        KEY post_id (post_id)
    ) $charset_collate;";

	// Include WordPress database upgrade functions
	require_once ABSPATH . 'wp-admin/includes/upgrade.php';

	// Execute the SQL statements
	dbDelta( $sql1 );
	dbDelta( $sql2 );

	// Store the current schema version
	update_option( 'saiap_db_version', '1.0' );
}

/**
 * Render the prompt history section
 */
function saiap_render_prompt_history() {
	global $wpdb;

	// Get recent prompts (limit to 10)
	$prompts = $wpdb->get_results(
		$wpdb->prepare(
			"
        SELECT p.*, 
               GROUP_CONCAT(pp.post_id) as post_ids,
               GROUP_CONCAT(posts.post_title SEPARATOR '||') as post_titles
        FROM {$wpdb->prefix}saiap_prompts p
        LEFT JOIN {$wpdb->prefix}saiap_prompt_posts pp ON p.id = pp.prompt_id
        LEFT JOIN {$wpdb->posts} posts ON pp.post_id = posts.ID
        WHERE p.user_id = %d
        GROUP BY p.id
        ORDER BY p.created_at DESC
        LIMIT 5
    ",
			get_current_user_id()
		)
	);

	// Get total count to determine if we need the "Load More" button
	$total_count = $wpdb->get_var(
		$wpdb->prepare(
			"
        SELECT COUNT(id)
        FROM {$wpdb->prefix}saiap_prompts
        WHERE user_id = %d
    ",
			get_current_user_id()
		)
	);

	if ( empty( $prompts ) ) {
		echo '<p class="body-text">' . esc_html__( 'No prompt history yet.', 'clearpost-simple-ai-auto-post' ) . '</p>';
		return;
	}

	?>
	<div class="saiap-prompt-history">
		<div class="saiap-prompt-buttons" id="saiap-prompt-list">
			<?php foreach ( $prompts as $prompt ) : ?>
				<button type="button" 
						class="secondary-button saiap-history-prompt" 
						data-prompt="<?php echo esc_attr( $prompt->prompt ); ?>"
						data-model="<?php echo esc_attr( $prompt->model ); ?>"
						data-system-prompt="<?php echo esc_attr( $prompt->system_prompt ); ?>"
						data-timestamp="<?php echo esc_attr( $prompt->created_at ); ?>"
						title="<?php echo esc_attr( $prompt->prompt ); ?>">
					<?php
					// Show a truncated version of the prompt
					echo esc_html( wp_trim_words( $prompt->prompt, 12, '...' ) );
					?>
					
					<?php if ( ! empty( $prompt->post_ids ) ) : ?>
						<span class="saiap-prompt-posts">
							<?php
							$post_titles = ! empty( $prompt->post_titles ) ? explode( '||', $prompt->post_titles ) : array();
							echo esc_html( implode( ', ', array_map( 'wp_trim_words', $post_titles, array_fill( 0, count( $post_titles ), 7 ) ) ) );
							?>
						</span>
					<?php endif; ?>
					
					<span class="saiap-prompt-timestamp">
						<?php echo esc_html( human_time_diff( strtotime( $prompt->created_at ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'clearpost-simple-ai-auto-post' ) ); ?>
					</span>
				</button>
			<?php endforeach; ?>
		</div>
		
		<?php if ( $total_count > count( $prompts ) ) : ?>
		<div class="spacing-16 text-align-center display-grid">
			<button type="button" id="saiap-load-more-prompts" class="secondary-button" data-page="1" data-nonce="<?php echo esc_attr( wp_create_nonce( 'saiap_get_all_prompts' ) ); ?>">
				<?php esc_html_e( 'Load More', 'clearpost-simple-ai-auto-post' ); ?>
			</button>
		</div>
		<?php endif; ?>
		
	</div>
	<?php
}


/**
 * AJAX handler to get all prompts for the current user
 */
function saiap_get_all_prompts() {
	// Verify nonce
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'saiap_get_all_prompts' ) ) {
		wp_send_json_error( array( 'message' => 'Security check failed.' ) );
		return;
	}

	// Get page and per_page parameters with defaults
	$page     = isset( $_POST['page'] ) ? intval( sanitize_text_field( wp_unslash( $_POST['page'] ) ) ) : 1;
	$per_page = isset( $_POST['per_page'] ) ? intval( sanitize_text_field( wp_unslash( $_POST['per_page'] ) ) ) : 10;

	// Calculate offset
	$offset = ( $page - 1 ) * $per_page;

	// Get prompts from database
	global $wpdb;
	$table_name = $wpdb->prefix . 'saiap_prompts';

	// Get total count
	$total_prompts = $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(id) FROM {$table_name} WHERE user_id = %d",
			get_current_user_id()
		)
	);

	// Get prompts with pagination
	$prompts = $wpdb->get_results(
		$wpdb->prepare(
			"
        SELECT p.*, 
               GROUP_CONCAT(pp.post_id) as post_ids,
               GROUP_CONCAT(posts.post_title SEPARATOR '||') as post_titles
        FROM {$wpdb->prefix}saiap_prompts p
        LEFT JOIN {$wpdb->prefix}saiap_prompt_posts pp ON p.id = pp.prompt_id
        LEFT JOIN {$wpdb->posts} posts ON pp.post_id = posts.ID
        WHERE p.user_id = %d
        GROUP BY p.id
        ORDER BY p.created_at DESC
        LIMIT %d, %d
    ",
			get_current_user_id(),
			$offset,
			$per_page
		)
	);

	if ( $prompts ) {
		wp_send_json_success(
			array(
				'prompts'  => $prompts,
				'total'    => (int) $total_prompts,
				'has_more' => $offset + count( $prompts ) < $total_prompts,
			)
		);
	} else {
		wp_send_json_error( array( 'message' => 'No prompts found.' ) );
	}
}
add_action( 'wp_ajax_saiap_get_all_prompts', 'saiap_get_all_prompts' );

/**
 * Save a prompt and its associated post to the database
 *
 * @param string $prompt The user's prompt
 * @param string $system_prompt The system prompt used
 * @param string $model The model used
 * @param int    $post_id The ID of the generated post
 * @return int|false The ID of the saved prompt or false on failure
 */
function saiap_save_prompt( $prompt, $system_prompt, $model, $post_id ) {
	global $wpdb;

	// Don't save if prompt history is disabled
	if ( get_option( 'saiap_enable_prompt_history', 'yes' ) !== 'yes' ) {
		return false;
	}

	// Get current user ID
	$user_id = get_current_user_id();
	if ( ! $user_id ) {
		return false;
	}

	// Insert the prompt
	$result = $wpdb->insert(
		$wpdb->prefix . 'saiap_prompts',
		array(
			'prompt'        => $prompt,
			'system_prompt' => $system_prompt,
			'model'         => $model,
			'user_id'       => $user_id,
		),
		array( '%s', '%s', '%s', '%d' )
	);

	if ( ! $result ) {
		return false;
	}

	$prompt_id = $wpdb->insert_id;

	// If we have a post ID, create the relationship
	if ( $post_id ) {
		$wpdb->insert(
			$wpdb->prefix . 'saiap_prompt_posts',
			array(
				'prompt_id' => $prompt_id,
				'post_id'   => $post_id,
			),
			array( '%d', '%d' )
		);
	}

	return $prompt_id;
}
