<?php
/**
 * Content Personalization Features for Easy AI Blog Generator
 *
 * This file handles all personalization features for Easy AI Blog Generator:
 * - Adds company/brand information to the settings page
 * - Provides controls for personalization strength
 * - Automatically integrates with all content generation (blog posts, titles, format conversions)
 * - Adds custom CSS for personalization-specific elements
 *
 * Personalization is automatically applied to ALL content generation including:
 * - New blog post generation
 * - Scheduled post generation
 * - Format conversions
 * - Headline updates
 * - Content improvements
 *
 * This works by filtering all API calls through a unified API system.
 *
 * @package EasyAIBlogGenerator
 */

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

/**
 * Register personalization settings fields.
 */
function easyaibloggen_register_personalization_settings() {
	// Register a new section in the existing settings page.
	add_settings_section(
		'easyaibloggen_personalization_section',
		__( 'Content Personalization', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_personalization_section',
		'easyaibloggen-settings'
	);

	// Enable Personalization.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_enable_personalization',
		'easyaibloggen_sanitize_checkbox'
	);

	add_settings_field(
		'easyaibloggen_enable_personalization',
		__( 'Enable Personalization', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_checkbox_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_enable_personalization',
			'description' => __( 'Enable or disable content personalization', 'easy-ai-blog-generator' ),
		)
	);

	// Personalization Strength.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_personalization_strength',
		'easyaibloggen_sanitize_personalization_strength'
	);

	add_settings_field(
		'easyaibloggen_personalization_strength',
		__( 'Personalization Strength', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_select_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_personalization_strength',
			'description' => __( 'Control how heavily the AI should incorporate your brand into the content', 'easy-ai-blog-generator' ),
			'options'     => array(
				'subtle'   => __( 'Subtle - Minimal brand mentions', 'easy-ai-blog-generator' ),
				'moderate' => __( 'Moderate - Balanced approach', 'easy-ai-blog-generator' ),
				'strong'   => __( 'Strong - Emphasize brand throughout', 'easy-ai-blog-generator' ),
			),
		)
	);

	// Company/Website Name.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_company_name',
		'sanitize_text_field'
	);

	add_settings_field(
		'easyaibloggen_company_name',
		__( 'Company/Website Name', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_text_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_company_name',
			'description' => __( 'Enter your company or website name', 'easy-ai-blog-generator' ),
		)
	);

	// Website Purpose.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_website_purpose',
		'sanitize_textarea_field'
	);

	add_settings_field(
		'easyaibloggen_website_purpose',
		__( 'Website Purpose', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_textarea_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_website_purpose',
			'description' => __( 'Describe the main purpose of your website (e.g., "Educate home gardeners about organic methods" or "Sell premium fitness equipment")', 'easy-ai-blog-generator' ),
		)
	);

	// Target Audience.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_target_audience',
		'sanitize_textarea_field'
	);

	add_settings_field(
		'easyaibloggen_target_audience',
		__( 'Target Audience', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_textarea_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_target_audience',
			'description' => __( 'Describe your target audience (e.g., "Home gardeners aged 30-60" or "Professional fitness trainers")', 'easy-ai-blog-generator' ),
		)
	);

	// Products/Services.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_products_services',
		'sanitize_textarea_field'
	);

	add_settings_field(
		'easyaibloggen_products_services',
		__( 'Products/Services', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_textarea_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_products_services',
			'description' => __( 'List and briefly describe your main products or services', 'easy-ai-blog-generator' ),
		)
	);

	// Brand Voice.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_brand_voice',
		'sanitize_textarea_field'
	);

	add_settings_field(
		'easyaibloggen_brand_voice',
		__( 'Brand Voice', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_textarea_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_brand_voice',
			'description' => __( 'Describe your brand voice and tone (e.g., "Professional but friendly" or "Authoritative and educational")', 'easy-ai-blog-generator' ),
		)
	);

	// Key Differentiators.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_differentiators',
		'sanitize_textarea_field'
	);

	add_settings_field(
		'easyaibloggen_differentiators',
		__( 'Key Differentiators', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_textarea_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_differentiators',
			'description' => __( 'What makes your company/products unique? (e.g., "Sustainable materials" or "24/7 customer support")', 'easy-ai-blog-generator' ),
		)
	);

	// Call-to-Action.
	register_setting(
		'easyaibloggen_personalization_group',
		'easyaibloggen_call_to_action',
		'sanitize_text_field'
	);

	add_settings_field(
		'easyaibloggen_call_to_action',
		__( 'Preferred Call-to-Action', 'easy-ai-blog-generator' ),
		'easyaibloggen_render_text_field',
		'easyaibloggen-settings',
		'easyaibloggen_personalization_section',
		array(
			'label_for'   => 'easyaibloggen_call_to_action',
			'description' => __( 'What action do you want readers to take? (e.g., "Sign up for a free consultation" or "Shop our catalog")', 'easy-ai-blog-generator' ),
		)
	);
}
add_action( 'admin_init', 'easyaibloggen_register_personalization_settings' );

/**
 * Render the personalization section description.
 */
function easyaibloggen_render_personalization_section() {
	echo '<p>' . esc_html__( 'Configure content personalization settings to make AI-generated content align with your brand.', 'easy-ai-blog-generator' ) . '</p>';
}

/**
 * Render a text field.
 *
 * @param array $args Field arguments.
 */
function easyaibloggen_render_text_field( $args ) {
	$option_name  = $args['label_for'];
	$option_value = get_option( $option_name, '' );
	$description  = isset( $args['description'] ) ? $args['description'] : '';

	echo '<input type="text" id="' . esc_attr( $option_name ) . '" name="' . esc_attr( $option_name ) . '" value="' . esc_attr( $option_value ) . '" class="regular-text">';

	if ( ! empty( $description ) ) {
		echo '<p class="description">' . esc_html( $description ) . '</p>';
	}
}

/**
 * Render a textarea field.
 *
 * @param array $args Field arguments.
 */
function easyaibloggen_render_textarea_field( $args ) {
	$option_name  = $args['label_for'];
	$option_value = get_option( $option_name, '' );
	$description  = isset( $args['description'] ) ? $args['description'] : '';

	echo '<textarea id="' . esc_attr( $option_name ) . '" name="' . esc_attr( $option_name ) . '" rows="4" class="large-text">' . esc_textarea( $option_value ) . '</textarea>';

	if ( ! empty( $description ) ) {
		echo '<p class="description">' . esc_html( $description ) . '</p>';
	}
}

/**
 * Render a checkbox field.
 *
 * @param array $args Field arguments.
 */
function easyaibloggen_render_checkbox_field( $args ) {
	$option_name  = $args['label_for'];
	$option_value = get_option( $option_name, 0 );
	$description  = isset( $args['description'] ) ? $args['description'] : '';

	echo '<input type="checkbox" id="' . esc_attr( $option_name ) . '" name="' . esc_attr( $option_name ) . '" value="1" ' . checked( 1, $option_value, false ) . '>';

	if ( ! empty( $description ) ) {
		echo '<p class="description">' . esc_html( $description ) . '</p>';
	}
}

/**
 * Render a select field.
 *
 * @param array $args Field arguments.
 */
function easyaibloggen_render_select_field( $args ) {
	$option_name  = $args['label_for'];
	$option_value = get_option( $option_name, '' );
	$description  = isset( $args['description'] ) ? $args['description'] : '';
	$options      = isset( $args['options'] ) ? $args['options'] : array();

	echo '<select id="' . esc_attr( $option_name ) . '" name="' . esc_attr( $option_name ) . '" class="regular-text">';

	foreach ( $options as $value => $label ) {
		echo '<option value="' . esc_attr( $value ) . '" ' . selected( $option_value, $value, false ) . '>' . esc_html( $label ) . '</option>';
	}

	echo '</select>';

	if ( ! empty( $description ) ) {
		echo '<p class="description">' . esc_html( $description ) . '</p>';
	}
}

/**
 * Get personalization data formatted for inclusion in prompts.
 *
 * @return string Formatted personalization data.
 */
function easyaibloggen_get_personalization_data() {
	// Check if personalization is enabled.
	$personalization_enabled = get_option( 'easyaibloggen_enable_personalization', 1 );
	if ( ! $personalization_enabled ) {
		return '';
	}

	$personalization_strength = get_option( 'easyaibloggen_personalization_strength', 'moderate' );
	$company_name             = get_option( 'easyaibloggen_company_name', '' );
	$website_purpose          = get_option( 'easyaibloggen_website_purpose', '' );
	$target_audience          = get_option( 'easyaibloggen_target_audience', '' );
	$products_services        = get_option( 'easyaibloggen_products_services', '' );
	$brand_voice              = get_option( 'easyaibloggen_brand_voice', '' );
	$differentiators          = get_option( 'easyaibloggen_differentiators', '' );
	$call_to_action           = get_option( 'easyaibloggen_call_to_action', '' );

	$personalization_data = '';

	if ( ! empty( $company_name ) ) {
		$personalization_data .= 'COMPANY NAME: ' . $company_name . "\n";
	}

	if ( ! empty( $website_purpose ) ) {
		$personalization_data .= 'WEBSITE PURPOSE: ' . $website_purpose . "\n";
	}

	if ( ! empty( $target_audience ) ) {
		$personalization_data .= 'TARGET AUDIENCE: ' . $target_audience . "\n";
	}

	if ( ! empty( $products_services ) ) {
		$personalization_data .= 'PRODUCTS/SERVICES: ' . $products_services . "\n";
	}

	if ( ! empty( $brand_voice ) ) {
		$personalization_data .= 'BRAND VOICE: ' . $brand_voice . "\n";
	}

	if ( ! empty( $differentiators ) ) {
		$personalization_data .= 'KEY DIFFERENTIATORS: ' . $differentiators . "\n";
	}

	if ( ! empty( $call_to_action ) ) {
		$personalization_data .= 'PREFERRED CALL-TO-ACTION: ' . $call_to_action . "\n";
	}

	if ( empty( $personalization_data ) ) {
		return '';
	}

	$personalization_data .= 'PERSONALIZATION STRENGTH: ' . $personalization_strength . "\n";

	return "PERSONALIZATION DATA:\n" . $personalization_data;
}

/**
 * Filter the prompt to include personalization data.
 *
 * @param string $prompt The original prompt.
 * @return string Modified prompt with personalization data.
 */
function easyaibloggen_add_personalization_to_prompt( $prompt ) {
	$personalization_data = easyaibloggen_get_personalization_data();

	if ( empty( $personalization_data ) ) {
		return $prompt;
	}

	$personalization_strength     = get_option( 'easyaibloggen_personalization_strength', 'moderate' );
	$personalization_instructions = '';

	switch ( $personalization_strength ) {
		case 'subtle':
			$personalization_instructions = 'Please write the blog post to align with the above personalization data, but keep brand mentions minimal. The content should be primarily educational and helpful, with only subtle references to the company/products/services where absolutely relevant. Limit explicit brand mentions to 1-2 places maximum.';
			break;

		case 'strong':
			$personalization_instructions = "Please write the blog post to align closely with the above personalization data, prominently featuring the company/products/services throughout the content. While still providing value to readers, make sure to emphasize how the brand's offerings directly address the topic. Include specific call-to-actions and product mentions where appropriate. Make the brand a central theme of the content.";
			break;

		case 'moderate':
		default:
			$personalization_instructions = 'Please write the blog post to align with the above personalization data, promoting the company/products/services where relevant without making the content sound like an advertisement. Content should be helpful and educational first, while naturally incorporating the brand and its offerings.';
			break;
	}

	// Add personalization data to the prompt.
	$new_prompt = $prompt . "\n\n" . $personalization_data . "\n\n" . $personalization_instructions;

	return $new_prompt;
}

/**
 * Hook into the unified API call to modify the prompt.
 *
 * @param array  $data The API request data.
 * @param string $type The request type.
 * @return array Modified API request data.
 */
function easyaibloggen_modify_api_call_data( $data, $type ) {
	if ( 'text' === $type && isset( $data['messages'] ) && is_array( $data['messages'] ) ) {
		// Find the user message (usually the last one).
		foreach ( $data['messages'] as $index => $message ) {
			if ( isset( $message['role'] ) && 'user' === $message['role'] && isset( $message['content'] ) ) {
				// Modify the prompt.
				$data['messages'][ $index ]['content'] = easyaibloggen_add_personalization_to_prompt( $message['content'] );
				break;
			}
		}
	}

	return $data;
}
add_filter( 'easyaibloggen_pre_api_call_data', 'easyaibloggen_modify_api_call_data', 10, 2 );

/**
 * Add personalization CSS to the front-end.
 */
function easyaibloggen_add_personalization_css() {
	// Only add this CSS to public-facing pages.
	if ( is_admin() ) {
		return;
	}

	// Enqueue the personalization CSS file.
	wp_enqueue_style(
		'easyaibloggen-personalization',
		plugin_dir_url( __FILE__ ) . 'css/easyaibloggen-personalization.css',
		array(),
		'1.0.0'
	);
}
add_action( 'wp_enqueue_scripts', 'easyaibloggen_add_personalization_css' );

/**
 * Sanitize personalization strength values.
 *
 * @param string $input The value to sanitize.
 * @return string Sanitized value.
 */
function easyaibloggen_sanitize_personalization_strength( $input ) {
	$valid_options = array( 'subtle', 'moderate', 'strong' );
	if ( in_array( $input, $valid_options, true ) ) {
		return $input;
	}
	return 'moderate';
}
