<?php
/**
 * AI content assistant – OpenAI-compatible API integration.
 *
 * @package EasySite_Pro
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Get configured AI API key.
 *
 * @return string
 */
function easysite_get_ai_api_key() {
	if ( defined( 'EASYSITE_OPENAI_API_KEY' ) && EASYSITE_OPENAI_API_KEY ) {
		return EASYSITE_OPENAI_API_KEY;
	}
	return (string) easysite_get_mod( 'easysite_ai_api_key', '' );
}

/**
 * Get AI model name.
 *
 * @return string
 */
function easysite_get_ai_model() {
	$model = easysite_get_mod( 'easysite_ai_model', 'gpt-4o-mini' );
	return apply_filters( 'easysite_ai_model', $model );
}

/**
 * Get AI API endpoint.
 *
 * @return string
 */
function easysite_get_ai_api_url() {
	return apply_filters( 'easysite_ai_api_url', 'https://api.openai.com/v1/chat/completions' );
}

/**
 * Whether live AI API should be used (Ultimate + license + key).
 *
 * @return bool
 */
function easysite_ai_uses_live_api() {
	if ( ! easysite_get_ai_api_key() ) {
		return false;
	}
	if ( easysite_is_bundle() && function_exists( 'easysite_license_is_active' ) && ! easysite_license_is_active() ) {
		return false;
	}
	return (bool) apply_filters( 'easysite_ai_uses_live_api', true );
}

/**
 * Build prompt for content type.
 *
 * @param string $type    Content type.
 * @param string $context Optional existing text.
 * @return string
 */
function easysite_ai_build_prompt( $type, $context = '' ) {
	$site_name = get_bloginfo( 'name' );
	$tagline   = get_bloginfo( 'description' );
	$industry  = function_exists( 'easysite_get_industry_key' ) ? easysite_get_industry_key() : 'business';

	$industry_hints = array(
		'beauty'     => 'hair salon or spa',
		'fitness'    => 'personal trainer or gym',
		'coach'      => 'life or business coach',
		'realestate' => 'real estate agency',
		'restaurant' => 'restaurant',
		'shop'       => 'online shop',
	);
	$hint = isset( $industry_hints[ $industry ] ) ? $industry_hints[ $industry ] : 'small business';

	$prompts = array(
		'homepage' => "Write a friendly homepage hero subtitle for a {$hint} called \"{$site_name}\". Tagline: \"{$tagline}\". Keep it under 30 words, plain language, no jargon.",
		'about'    => "Write a short About Us paragraph for \"{$site_name}\", a {$hint}. Warm, trustworthy tone. 2-3 sentences.",
		'product'  => 'Write a short WooCommerce product description. Clear benefits, under 50 words.',
		'meta'     => "Write an SEO meta description for \"{$site_name}\" ({$hint}). Under 155 characters, include a call to action.",
		'general'  => "Write helpful website copy in plain language for a {$hint}.",
		'alt'      => 'Write a short, descriptive image alt text for a business website photo. Under 12 words.',
		'shorter'  => "Rewrite this copy to be shorter and punchier for a {$hint} website. Max 25 words.",
		'friendlier' => "Rewrite this copy in a warmer, friendlier tone for a {$hint} website.",
		'professional' => "Rewrite this copy in a more professional tone for a {$hint} website.",
		'seo_title' => "Write an SEO page title for \"{$site_name}\" ({$hint}). Under 60 characters.",
	);

	$prompt = isset( $prompts[ $type ] ) ? $prompts[ $type ] : $prompts['general'];

	if ( $context ) {
		$prompt .= ' Improve or replace this draft: ' . $context;
	}

	return apply_filters( 'easysite_ai_prompt', $prompt, $type, $context );
}

/**
 * Request suggestion from OpenAI-compatible API.
 *
 * @param string $type    Content type.
 * @param string $context Existing content.
 * @return string|WP_Error
 */
function easysite_ai_request_suggestion( $type, $context = '' ) {
	$api_key = easysite_get_ai_api_key();

	if ( ! $api_key ) {
		return new WP_Error( 'no_api_key', __( 'Add your OpenAI API key in EasySite Settings → AI Assistant, or define EASYSITE_OPENAI_API_KEY in wp-config.php.', 'easysite-pro' ) );
	}

	$body = array(
		'model'       => easysite_get_ai_model(),
		'temperature' => 0.7,
		'max_tokens'  => 300,
		'messages'    => array(
			array(
				'role'    => 'system',
				'content' => 'You are a helpful copywriter for small business WordPress websites. Write concise, friendly text. Return only the requested copy with no quotes or labels.',
			),
			array(
				'role'    => 'user',
				'content' => easysite_ai_build_prompt( $type, $context ),
			),
		),
	);

	$response = wp_remote_post(
		easysite_get_ai_api_url(),
		array(
			'timeout' => 30,
			'headers' => array(
				'Authorization' => 'Bearer ' . $api_key,
				'Content-Type'  => 'application/json',
			),
			'body'    => wp_json_encode( $body ),
		)
	);

	if ( is_wp_error( $response ) ) {
		return $response;
	}

	$code = wp_remote_retrieve_response_code( $response );
	$data = json_decode( wp_remote_retrieve_body( $response ), true );

	if ( $code < 200 || $code >= 300 ) {
		$message = isset( $data['error']['message'] ) ? $data['error']['message'] : __( 'AI request failed. Check your API key and try again.', 'easysite-pro' );
		return new WP_Error( 'ai_api_error', $message );
	}

	$text = isset( $data['choices'][0]['message']['content'] ) ? trim( $data['choices'][0]['message']['content'] ) : '';

	if ( ! $text ) {
		return new WP_Error( 'ai_empty', __( 'No suggestion was returned. Please try again.', 'easysite-pro' ) );
	}

	return apply_filters( 'easysite_ai_suggestion', $text, $type, $context );
}

/**
 * Add AI suggest buttons in customizer.
 */
function easysite_ai_customizer_buttons() {
	?>
	<script>
	document.addEventListener('DOMContentLoaded', function() {
		document.querySelectorAll('.easysite-ai-suggest').forEach(function(btn) {
			btn.addEventListener('click', function() {
				var target = document.getElementById(btn.dataset.target);
				var type = btn.dataset.type || 'general';
				if (target && window.easysiteAI) {
					window.easysiteAI.suggest(type, target);
				}
			});
		});
	});
	</script>
	<?php
}
add_action( 'customize_controls_print_footer_scripts', 'easysite_ai_customizer_buttons' );

/**
 * Register AI settings in customizer.
 *
 * @param WP_Customize_Manager $wp_customize Customizer.
 */
function easysite_ai_customizer_settings( $wp_customize ) {
	$wp_customize->add_section( 'easysite_ai', array(
		'title'       => __( 'AI Assistant', 'easysite-pro' ),
		'description' => __( 'Connect OpenAI to get text suggestions. For better security, use define( \'EASYSITE_OPENAI_API_KEY\', \'sk-...\' ); in wp-config.php instead.', 'easysite-pro' ),
		'panel'       => 'easysite_settings',
	) );

	easysite_add_setting( $wp_customize, 'easysite_ai_api_key', array(
		'section'     => 'easysite_ai',
		'label'       => __( 'OpenAI API key', 'easysite-pro' ),
		'description' => __( 'Your API key is stored in your site database. Use wp-config.php for production sites.', 'easysite-pro' ),
		'default'     => '',
	) );

	easysite_add_setting( $wp_customize, 'easysite_ai_model', array(
		'section' => 'easysite_ai',
		'label'   => __( 'AI model', 'easysite-pro' ),
		'type'    => 'select',
		'choices' => array(
			'gpt-4o-mini' => 'GPT-4o Mini (recommended)',
			'gpt-4o'      => 'GPT-4o',
			'gpt-4.1-mini'=> 'GPT-4.1 Mini',
			'gpt-4.1'     => 'GPT-4.1',
		),
		'default' => 'gpt-4o-mini',
	) );
}
add_action( 'customize_register', 'easysite_ai_customizer_settings', 25 );

/**
 * AJAX handler for AI suggestions.
 */
function easysite_ajax_ai_suggest() {
	check_ajax_referer( 'easysite_admin_nonce', 'nonce' );

	if ( ! current_user_can( 'edit_theme_options' ) ) {
		wp_send_json_error( array( 'message' => __( 'Permission denied.', 'easysite-pro' ) ) );
	}

	$type    = isset( $_POST['suggest_type'] ) ? sanitize_key( wp_unslash( $_POST['suggest_type'] ) ) : 'general';
	$context = isset( $_POST['context'] ) ? sanitize_textarea_field( wp_unslash( $_POST['context'] ) ) : '';

	$result = easysite_ai_request_suggestion( $type, $context );

	if ( is_wp_error( $result ) ) {
		$fallbacks = array(
			'homepage' => __( 'We help local businesses grow with friendly, reliable service. Get in touch today for a free consultation.', 'easysite-pro' ),
			'about'    => __( 'Founded with a passion for quality, our team brings expertise and care to every project we take on.', 'easysite-pro' ),
			'product'  => __( 'A high-quality product designed to make your life easier. Order today with fast shipping.', 'easysite-pro' ),
			'meta'     => __( 'Learn more about our services, read customer reviews, and contact us for a free quote.', 'easysite-pro' ),
			'general'  => __( 'Friendly, professional website copy for your business.', 'easysite-pro' ),
		);

		$text = isset( $fallbacks[ $type ] ) ? $fallbacks[ $type ] : $fallbacks['general'];

		wp_send_json_success( array(
			'text'    => $text,
			'message' => $result->get_error_message() . ' ' . __( '(Showing demo text.)', 'easysite-pro' ),
			'demo'    => true,
		) );
	}

	wp_send_json_success( array(
		'text'    => $result,
		'message' => __( 'Suggestion ready!', 'easysite-pro' ),
		'demo'    => false,
	) );
}
add_action( 'wp_ajax_easysite_ai_suggest', 'easysite_ajax_ai_suggest' );

/**
 * Add AI buttons to onboarding and post editor (bundle).
 */
function easysite_ai_admin_footer() {
	$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
	if ( ! $screen ) {
		return;
	}

	$allowed = array( 'page', 'post', 'product', 'customize' );
	if ( ! in_array( $screen->base, array( 'post', 'page', 'product' ), true ) && 'customize' !== $screen->base ) {
		return;
	}
	?>
	<script>
	document.addEventListener('DOMContentLoaded', function() {
		var map = {
			'easysite_hero_subtitle': 'homepage',
			'easysite_about_text': 'about',
			'easysite_seo_description': 'meta',
			'content': 'general'
		};
		Object.keys(map).forEach(function(id) {
			var el = document.getElementById(id);
			if (!el || el.dataset.easysiteAi) return;
			el.dataset.easysiteAi = '1';
			var btn = document.createElement('button');
			btn.type = 'button';
			btn.className = 'button easysite-ai-suggest';
			btn.textContent = '<?php echo esc_js( __( 'Suggest text', 'easysite-pro' ) ); ?>';
			btn.dataset.target = id;
			btn.dataset.type = map[id];
			el.parentNode.insertBefore(btn, el.nextSibling);
		});
	});
	</script>
	<?php
}
add_action( 'admin_footer', 'easysite_ai_admin_footer' );
