<?php

/**
 * Changeloger Settings Options (Free Version)
 *
 * Uses Codestar Framework (CSF) for settings management.
 * Pro settings tabs are added by changeloger plugin.
 *
 * @package Changeloger
 */

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

// Check if CSF is loaded
if (!class_exists('CSF')) {
	return;
}

// Check if user has premium license
$is_premium = function_exists('cha_is_premium') && cha_is_premium();

// Check if Antimanual AI provider plugin is active.
$is_antimanual_active = class_exists( '\\Antimanual\\AIProvider' );

/**
 * Callback function to get badge options for CSF select field
 *
 * @return array Badge options with slug => name pairs.
 */
function changeloger_get_badge_options() {
	$options = [];
	$badges  = Changeloger_Post_Types::get_release_badges();

	foreach ( $badges as $badge ) {
		$options[ $badge['slug'] ] = $badge['name'];
	}

	return $options;
}

/**
 * Set a unique slug-like ID
 */
$prefix = 'changeloger_settings';

/**
 * Create Settings Options
 */
CSF::createOptions($prefix, [
	'framework_title' => __('Changeloger', 'changeloger') . ' <small>v' . (defined('CHANGELOGER_VERSION') ? CHANGELOGER_VERSION : '1.3.0') . '</small>',
	'menu_title' => __('Settings', 'changeloger'),
	'menu_slug' => 'changeloger-settings',
	'menu_type' => 'submenu',
	'menu_parent' => 'changeloger',
	'menu_capability' => 'manage_options',
	'show_bar_menu' => false,
	'show_in_customizer' => false,
	'theme' => 'dark',
	'enqueue_webfont' => false,
	'async_webfont' => false,
	'footer_text' => __('Thank you for using Changeloger!', 'changeloger'),
]);

/**
 * General Settings Section
 */
CSF::createSection($prefix, [
	'id' => 'general',
	'title' => __('General', 'changeloger'),
	'icon' => 'fas fa-cog',
	'fields' => [
		[
			'id' => 'items_per_page',
			'type' => 'spinner',
			'title' => __('Items Per Page', 'changeloger'),
			'subtitle' => __('Default number of items to display per page for releases and feedback lists.', 'changeloger'),
			'default' => 10,
			'min' => 1,
			'max' => 100,
		],
		[
			'id' => 'show_embed_watermark',
			'type' => 'switcher',
			'title' => __('Show Embed Watermark', 'changeloger'),
			'subtitle' => __('Display "Powered by Changeloger" branding in embedded content.', 'changeloger'),
			'default' => true,
		],
		[
			'id'          => 'brand_color',
			'type'        => 'color',
			'title'       => esc_html__( 'Primary Brand Color', 'changeloger' ),
			'subtitle'    => esc_html__( 'Set the main accent color used throughout your releases for buttons, tabs, and highlights.', 'changeloger' ),
			'default'     => '#6366f1',
			'output'      => ':root',
			'output_mode' => '--changeloger_brand_color',
		],
	],
]);

/**
 * Releases Settings Section
 */
CSF::createSection($prefix, [
	'id' => 'releases',
	'title' => __('Releases', 'changeloger'),
	'icon' => 'fas fa-tags',
	'fields' => [
		[
			'id' => 'change_groups',
			'type' => 'repeater',
			'title' => __('Change Groups', 'changeloger'),
			'subtitle' => __('Define categories for release items. These will be used in imports and AI generation.', 'changeloger'),
			'button_title' => __('Add Category', 'changeloger'),
			'default' => [
				['name' => 'Improvements'],
				['name' => 'Fixes'],
				['name' => 'Patches'],
			],
			'fields' => [
				[
					'id' => 'name',
					'type' => 'text',
					'title' => __('Name', 'changeloger'),
				],
			],
		],
		[
			'type' => 'subheading',
			'content' => __('Badge Settings', 'changeloger'),
		],
		[
			'id' => 'release_badges',
			'type' => 'repeater',
			'title' => __('Release Badges', 'changeloger'),
			'subtitle' => __('Define badges that can be assigned to releases. Each badge can have a custom color.', 'changeloger'),
			'button_title' => __('Add Badge', 'changeloger'),
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'default' => [
				['name' => 'Major', 'color' => '#6366F1'],
				['name' => 'Minor', 'color' => '#22C55E'],
				['name' => 'Patch', 'color' => '#F59E0B'],
				['name' => 'Beta', 'color' => '#EF4444'],
			],
			'fields' => [
				[
					'id' => 'name',
					'type' => 'text',
					'title' => __('Name', 'changeloger'),
				],
				[
					'id' => 'color',
					'type' => 'color',
					'title' => __('Color', 'changeloger'),
					'default' => '#6366F1',
				],
			],
		],
		[
			'id' => 'enable_badge_filter',
			'type' => 'switcher',
			'title' => __('Enable Badge Filter', 'changeloger'),
			'subtitle' => __('Show badge filter pills on the frontend changelog to allow users to filter releases by badge type.', 'changeloger'),
			'default' => false,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},
		],
		[
			'id' => 'badge_filter_show_all',
			'type' => 'switcher',
			'title' => __('Show "All" Filter Pill', 'changeloger'),
			'subtitle' => __('Include an "All" pill that shows all releases when clicked.', 'changeloger'),
			'default' => true,
			'dependency' => ['enable_badge_filter', '==', 'true'],
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return true;
				}
				return (bool) $value;
			},
		],
		[
			'id' => 'badge_filter_default',
			'type' => 'select',
			'title' => __('Default Active Badge', 'changeloger'),
			'subtitle' => __('Select which badge should be active by default when the page loads. Only applies when "Show All" is disabled.', 'changeloger'),
			'placeholder' => __('First available badge', 'changeloger'),
			'options' => 'changeloger_get_badge_options',
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'dependency' => [
				['enable_badge_filter', '==', 'true'],
				['badge_filter_show_all', '==', 'false'],
			],
		],
		[
			'type'    => 'subheading',
			'content' => __( 'Content Excerpt', 'changeloger' ),
		],
		[
			'id'         => 'enable_content_excerpt',
			'type'       => 'switcher',
			'title'      => __( 'Enable Content Excerpt', 'changeloger' ),
			'subtitle'   => __( 'Truncate release content on the list page and show a "Continue Reading" button. Full content is always visible on the single release page.', 'changeloger' ),
			'default'    => true,
			'text_on'    => __( 'Enabled', 'changeloger' ),
			'text_off'   => __( 'Disabled', 'changeloger' ),
			'text_width' => 100,
		],
		[
			'type'    => 'subheading',
			'content' => __( 'Interactions', 'changeloger' ),
		],
		[
			'id'         => 'enable_release_interactions',
			'type'       => 'switcher',
			'title'      => __( 'Enable Release Interactions', 'changeloger' ),
			'subtitle'   => __( 'Show a reaction bar (e.g. thumbs up, heart) at the bottom of each release.', 'changeloger' ),
			'default'    => $is_premium ? true : false,
			'text_on'    => __( 'Enabled', 'changeloger' ),
			'text_off'   => __( 'Disabled', 'changeloger' ),
			'text_width' => 100,
			'class'      => $is_premium ? '' : 'cha-pro-notice',
			'sanitize'   => function( $value ) {
				if ( ! function_exists( 'cha_is_premium' ) || ! cha_is_premium() ) {
					return false;
				}
				return (bool) $value;
			},
		],
	],
]);

/**
 * Feedback Settings Section (Pro)
 */
CSF::createSection($prefix, [
	'id' => 'feedback',
	'title' => __('Feedback', 'changeloger'),
	'icon' => 'fas fa-comments',
	'fields' => [
		[
			'id' => 'enable_feedback',
			'type' => 'switcher',
			'title' => __('Enable Feedback Module', 'changeloger'),
			'subtitle' => __('Enable the feedback collection system.', 'changeloger'),
			'default' => true,
			'text_on' => __('Enabled', 'changeloger'),
			'text_off' => __('Disabled', 'changeloger'),
			'text_width' => 100,
			'sanitize' => function ($value) {
				return (bool) $value;
			},

		],
		[
			'id' => 'allow_comments',
			'type' => 'switcher',
			'title' => __('Allow Comments', 'changeloger'),
			'subtitle' => __('Allow users to comment on feedback items.', 'changeloger'),
			'default' => $is_premium ? true : false,
			'text_on' => __('Yes', 'changeloger'),
			'text_off' => __('No', 'changeloger'),
			'text_width' => 80,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'dependency' => ['enable_feedback', '==', 'true'],
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},

		],
		[
			'id' => 'enable_downvoting',
			'type' => 'switcher',
			'title' => __('Enable Downvoting', 'changeloger'),
			'subtitle' => __('Allow users to downvote feedback and roadmap items.', 'changeloger'),
			'default' => false,
			'text_on' => __('Enabled', 'changeloger'),
			'text_off' => __('Disabled', 'changeloger'),
			'text_width' => 100,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'dependency' => ['enable_feedback', '==', 'true'],
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},

		],
		[
			'id' => 'allow_guest_voting',
			'type' => 'switcher',
			'title' => __('Allow Guest Voting', 'changeloger'),
			'subtitle' => __('Allow non-logged-in users to vote.', 'changeloger'),
			'default' => false,
			'text_on' => __('Allowed', 'changeloger'),
			'text_off' => __('Require Login', 'changeloger'),
			'text_width' => 120,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'dependency' => ['enable_feedback', '==', 'true'],
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},

		],
	],
]);

/**
 * Roadmap Settings Section (Pro)
 */
CSF::createSection($prefix, [
	'id' => 'roadmap',
	'title' => __('Roadmap', 'changeloger'),
	'icon' => 'fas fa-road',
	'fields' => [
		[
			'id' => 'enable_roadmap',
			'type' => 'switcher',
			'title' => __('Enable Roadmap Module', 'changeloger'),
			'subtitle' => __('Enable the public roadmap display.', 'changeloger'),
			'default' => $is_premium ? true : false,
			'text_on' => __('Enabled', 'changeloger'),
			'text_off' => __('Disabled', 'changeloger'),
			'text_width' => 100,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},

		],
		[
			'id' => 'show_vote_count',
			'type' => 'switcher',
			'title' => __('Show Vote Count', 'changeloger'),
			'subtitle' => __('Display vote counts on roadmap items.', 'changeloger'),
			'default' => $is_premium ? true : false,
			'text_on' => __('Show', 'changeloger'),
			'text_off' => __('Hide', 'changeloger'),
			'text_width' => 80,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'dependency' => ['enable_roadmap', '==', 'true'],
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},

		],
	],
]);


/**
 * Authentication Settings Section (Pro)
 */
CSF::createSection($prefix, [
	'id' => 'authentication',
	'title' => __('User Authentication', 'changeloger'),
	'icon' => 'fas fa-user-lock',
	'fields' => [
		[
			'id' => 'enable_email_signup',
			'type' => 'switcher',
			'title' => __('Enable Email Signup', 'changeloger'),
			'subtitle' => __('Allow new users to register via email.', 'changeloger'),
			'default' => $is_premium ? true : false,
			'text_on' => __('Enabled', 'changeloger'),
			'text_off' => __('Disabled', 'changeloger'),
			'text_width' => 100,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},

		],
		[
			'id' => 'enable_google_login',
			'type' => 'switcher',
			'title' => __('Enable Google Login', 'changeloger'),
			'subtitle' => __('Allow users to log in using their Google account.', 'changeloger'),
			'default' => false,
			'text_on' => __('Enabled', 'changeloger'),
			'text_off' => __('Disabled', 'changeloger'),
			'text_width' => 100,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},

		],
		[
			'id' => 'google_client_id',
			'type' => 'text',
			'title' => __('Google Client ID', 'changeloger'),
			'subtitle' => __('Enter your Google OAuth Client ID.', 'changeloger'),
			'desc' => sprintf(
				__('Need help? <a href="%s" target="_blank" rel="noopener noreferrer">View Google setup guide</a>.', 'changeloger'),
				'https://developers.google.com/identity/protocols/oauth2/web-server'
			),
			'dependency' => ['enable_google_login', '==', 'true'],
		],
		[
			'id' => 'google_client_secret',
			'type' => 'text',
			'title' => __('Google Client Secret', 'changeloger'),
			'subtitle' => __('Enter your Google OAuth Client Secret.', 'changeloger'),
			'attributes' => ['type' => 'password'],
			'desc' => sprintf(
				__('Need help? <a href="%s" target="_blank" rel="noopener noreferrer">View Google setup guide</a>.', 'changeloger'),
				'https://developers.google.com/identity/protocols/oauth2'
			),
			'dependency' => ['enable_google_login', '==', 'true'],
		],
	],
]);

/**
 * Version Tracking Section (Pro)
 */
CSF::createSection($prefix, [
	'id' => 'version_tracking',
	'title' => __('Version Tracking', 'changeloger'),
	'icon' => 'fas fa-sync-alt',
	'fields' => [
		// Notice for free users.
		...( ! $is_premium ? [
			[
				'type'    => 'notice',
				'style'   => 'warning',
				'content' => __( 'Upgrade to Pro to enable version tracking.', 'changeloger' ),
			],
		] : [] ),
		[
			'id' => 'enable_auto_check',
			'type' => 'switcher',
			'title' => __('Enable Auto Version Check', 'changeloger'),
			'subtitle' => __('Automatically check for new versions daily.', 'changeloger'),
			'default' => false,
			'text_on' => __('Enabled', 'changeloger'),
			'text_off' => __('Disabled', 'changeloger'),
			'text_width' => 100,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},
		],
		[
			'type' => 'callback',
			'function' => 'cha_render_version_tracking_status',
		],
	],
]);

/**
 * Subscription Settings Section (Pro)
 */
CSF::createSection($prefix, [
	'id' => 'subscription',
	'title' => __('Product Notification', 'changeloger'),
	'icon' => 'fas fa-bell',
	'fields' => [
		...( ! $is_premium ? [
			[
				'type'    => 'notice',
				'style'   => 'warning',
				'content' => __( 'Upgrade to Pro to enable email notification features.', 'changeloger' ),
			],
		] : [] ),
		[
			'id' => 'enable_notification',
			'type' => 'switcher',
			'title' => __('Enable Email Notification', 'changeloger'),
			'subtitle' => __('Allow users to get notification of changelogs and updates.', 'changeloger'),
			'default' => $is_premium ? true : false,
			'text_on' => __('Enabled', 'changeloger'),
			'text_off' => __('Disabled', 'changeloger'),
			'text_width' => 100,
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'sanitize' => function ($value) {
				if (!function_exists('cha_is_premium') || !cha_is_premium()) {
					return false;
				}
				return (bool) $value;
			},
		],

		[
			'id' => 'notification_email_from_name',
			'type' => 'text',
			'title' => __('From Name', 'changeloger'),
			'subtitle' => __('Name to display in notification emails.', 'changeloger'),
			'default' => get_bloginfo('name'),
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'dependency' => ['enable_notification', '==', 'true'],
		],
		[
			'id' => 'notification_email_subject',
			'type' => 'text',
			'title' => __('Email Subject', 'changeloger'),
			'subtitle' => __('Subject line for subscription notification emails. Use {product} and {version} as placeholders.', 'changeloger'),
			'default' => __('{product} v{version} Is Released!', 'changeloger'),
			'class' => $is_premium ? '' : 'cha-pro-notice',
			'dependency' => ['enable_notification', '==', 'true'],
		],
		[
			'type' => 'subheading',
			'content' => __('Test Email', 'changeloger'),
			'dependency' => ['enable_notification', '==', 'true'],
		],
		[
			'type' => 'callback',
			'function' => 'cha_render_notification_test',
			'dependency' => ['enable_notification', '==', 'true'],
		],
		[
			'type' => 'subheading',
			'content' => __('AI Enhanced Email', 'changeloger'),
			'dependency' => ['enable_notification', '==', 'true'],
		],
		// Show install/activate prompt when Antimanual is not active.
		...( ! $is_antimanual_active ? [
			[
				'type'       => 'callback',
				'function'   => 'cha_render_antimanual_status',
				'dependency' => [ 'enable_notification', '==', 'true' ],
			],
		] : [] ),
		// Show AI settings only when Antimanual is active.
		...( $is_antimanual_active ? [
			[
				'id'         => 'enable_ai_enhanced_email',
				'type'       => 'switcher',
				'title'      => __( 'Enable AI Enhanced Email', 'changeloger' ),
				'subtitle'   => __( 'Use AI to generate personalized email content based on release changes.', 'changeloger' ),
				'default'    => false,
				'text_on'    => __( 'Enabled', 'changeloger' ),
				'text_off'   => __( 'Disabled', 'changeloger' ),
				'text_width' => 100,
				'class'      => $is_premium ? '' : 'cha-pro-notice',
				'dependency' => [ 'enable_notification', '==', 'true' ],
				'sanitize'   => function ( $value ) {
					if ( ! function_exists( 'cha_is_premium' ) || ! cha_is_premium() ) {
						return false;
					}
					if ( ! class_exists( '\\Antimanual\\AIProvider' ) ) {
						return false;
					}
					return (bool) $value;
				},
			],
			[
				'type'       => 'callback',
				'function'   => 'cha_render_antimanual_status',
				'dependency' => [
					[ 'enable_notification', '==', 'true' ],
					[ 'enable_ai_enhanced_email', '==', 'true' ],
				],
			],
			[
				'id'         => 'ai_email_tone',
				'type'       => 'select',
				'title'      => __( 'Email Tone', 'changeloger' ),
				'subtitle'   => __( 'Select the writing style for AI-generated emails.', 'changeloger' ),
				'options'    => [
					'professional' => __( 'Professional', 'changeloger' ),
					'friendly'     => __( 'Friendly', 'changeloger' ),
					'technical'    => __( 'Technical', 'changeloger' ),
					'marketing'    => __( 'Marketing', 'changeloger' ),
				],
				'default'    => 'professional',
				'dependency' => [
					[ 'enable_notification', '==', 'true' ],
					[ 'enable_ai_enhanced_email', '==', 'true' ],
				],
			],
		] : [] ),
	],
]);

/**
 * Backup Section (Basic)
 */
CSF::createSection($prefix, [
	'id' => 'backup',
	'title' => __('Backup', 'changeloger'),
	'icon' => 'fas fa-database',
	'fields' => [
		[
			'type' => 'backup',
		],
	],
]);

/**
 * Render Version Tracking Status callback
 * Displays cron status, trigger buttons, and event logs
 */
if (!function_exists('cha_render_version_tracking_status')) {
	function cha_render_version_tracking_status($is_premium)
	{
		// Handle clear logs action
		if (isset($_POST['cha_clear_logs']) && check_admin_referer('cha_clear_logs')) {
			if (class_exists('Changeloger_Version_Tracker')) {
				Changeloger_Version_Tracker::clear_notification_logs();
				echo '<div class="notice notice-success"><p>' . esc_html__('Notification logs cleared successfully.', 'changeloger') . '</p></div>';
			}
		}

		// Handle manual cron trigger
		if (isset($_POST['cha_trigger_cron']) && check_admin_referer('cha_trigger_cron')) {
			if (function_exists('cha_run_daily_version_check')) {
				cha_run_daily_version_check();
				echo '<div class="notice notice-success"><p>' . esc_html__('Auto check executed successfully.', 'changeloger') . '</p></div>';
			} else {
				echo '<div class="notice notice-error"><p>' . esc_html__('Auto check function not found. Make sure version-notification-cron.php is loaded.', 'changeloger') . '</p></div>';
			}
		}

		if (!$is_premium) {
			return;
		}

		// Get cron schedules
		$cron_timestamp = wp_next_scheduled('cha_daily_version_check');
		$cron_status = $cron_timestamp ? human_time_diff($cron_timestamp, time()) : __('Not scheduled', 'changeloger');
		$cron_interval = 'Daily';

		// Check if fallback heartbeat is active
		$fallback_working = function_exists('cha_fallback_cron_heartbeat');

		// Get all logs
		$all_logs = Changeloger_Version_Tracker::get_notification_logs();
		$all_logs = is_array($all_logs) ? array_reverse($all_logs) : [];

		?>
		<div class="cha-version-tracking-status" style="margin-top: 20px;">
			<div class="card" style="max-width: 100%; margin-bottom: 20px; padding: 15px;">
				<h3 style="margin-top: 0;"><?php esc_html_e('Version Check Status', 'changeloger'); ?></h3>
				<table class="widefat" style="margin-bottom: 15px;">
					<tr>
						<td style="width: 200px;"><strong><?php esc_html_e('Cron Status:', 'changeloger'); ?></strong></td>
						<td>
							<?php if ($cron_timestamp): ?>
								<span style="color: green;">✓ <?php esc_html_e('Scheduled', 'changeloger'); ?></span>
							<?php else: ?>
								<span style="color: red;">✗ <?php esc_html_e('Not scheduled', 'changeloger'); ?></span>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<td><strong><?php esc_html_e('Interval:', 'changeloger'); ?></strong></td>
						<td><?php echo esc_html(ucfirst($cron_interval)); ?></td>
					</tr>
					<tr>
						<td><strong><?php esc_html_e('Next Check:', 'changeloger'); ?></strong></td>
						<td>
							<?php if ($cron_timestamp): ?>
								<?php
								$next_run = $cron_timestamp > time()
									? __('in', 'changeloger') . ' ' . $cron_status
									: $cron_status . ' ' . __('ago', 'changeloger');
								echo esc_html($next_run);
								?>
								<br><small><?php echo esc_html(date_i18n('Y-m-d H:i:s', $cron_timestamp)); ?></small>
							<?php else: ?>
								<span style="color: red;"><?php esc_html_e('Not scheduled', 'changeloger'); ?></span>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<td><strong><?php esc_html_e('Fallback Heartbeat:', 'changeloger'); ?></strong></td>
						<td>
							<?php if ($fallback_working): ?>
								<span style="color: green;">✓
									<?php esc_html_e('Active (Cron will run on admin page loads)', 'changeloger'); ?></span>
							<?php else: ?>
								<span style="color: orange;">⚠ <?php esc_html_e('Inactive', 'changeloger'); ?></span>
							<?php endif; ?>
						</td>
					</tr>
					<tr>
						<td><strong><?php esc_html_e('Total Logs:', 'changeloger'); ?></strong></td>
						<td><?php echo esc_html(count($all_logs)); ?></td>
					</tr>
				</table>

				<div style="display: flex; gap: 10px; margin-bottom: 10px;">
					<form method="post" style="display: inline-block;">
						<?php wp_nonce_field('cha_trigger_cron'); ?>
						<button type="submit" name="cha_trigger_cron" class="button button-primary">
							<?php esc_html_e('Send Email Now', 'changeloger'); ?>
						</button>
					</form>

					<form method="post" style="display: inline-block;">
						<?php wp_nonce_field('cha_clear_logs'); ?>
						<button type="submit" name="cha_clear_logs" class="button button-secondary"
							onclick="return confirm('<?php esc_attr_e('Are you sure you want to clear all logs?', 'changeloger'); ?>');">
							<?php esc_html_e('Clear All Logs', 'changeloger'); ?>
						</button>
					</form>
				</div>
			</div>

			<h3><?php esc_html_e('Version Tracking Event Logs', 'changeloger'); ?></h3>

			<?php if (empty($all_logs)): ?>
				<div class="notice notice-info" style="margin: 0;">
					<p><?php esc_html_e('No notification logs found. Logs will appear here when notifications are sent.', 'changeloger'); ?>
					</p>
				</div>
			<?php else: ?>
				<table class="wp-list-table widefat fixed striped">
					<thead>
						<tr>
							<th style="width: 180px;"><?php esc_html_e('Timestamp', 'changeloger'); ?></th>
							<th style="width: 80px;"><?php esc_html_e('Post ID', 'changeloger'); ?></th>
							<th style="width: 150px;"><?php esc_html_e('Block ID', 'changeloger'); ?></th>
							<th style="width: 120px;"><?php esc_html_e('Version', 'changeloger'); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ($all_logs as $log): ?>
							<tr>
								<td><?php echo esc_html($log['timestamp'] ?? ''); ?></td>
								<td>
									<?php if (!empty($log['post_id'])): ?>
										<a href="<?php echo esc_url(get_edit_post_link($log['post_id'])); ?>" target="_blank">
											<?php echo esc_html($log['post_id']); ?>
										</a>
									<?php endif; ?>
								</td>
								<td>
									<small style="font-family: monospace;">
										<?php echo esc_html(substr($log['block_id'] ?? '', 0, 20)); ?>
									</small>
								</td>
								<td>
									<strong><?php echo esc_html($log['version'] ?? ''); ?></strong>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</div>

		<style>
			.cha-version-tracking-status .card {
				background: #fff;
				border: 1px solid #c3c4c7;
				border-radius: 4px;
				box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
			}

			.cha-version-tracking-status .card h3 {
				border-bottom: 1px solid #c3c4c7;
				padding-bottom: 10px;
				margin-bottom: 15px;
			}
		</style>
		<?php
	}
}

/**
 * Render Antimanual Status callback
 * Displays Antimanual plugin status and install/activate prompts
 */
if (!function_exists('cha_render_antimanual_status')) {
	function cha_render_antimanual_status()
	{
		$antimanual_active = class_exists('\\Antimanual\\AIProvider');
		$api_key_configured = $antimanual_active && \Antimanual\AIProvider::has_api_key();

		// If everything is configured, don't show any notice
		if ($antimanual_active && $api_key_configured) {
			return;
		}

		// Check if Antimanual plugin file exists
		$plugin_file = 'antimanual/antimanual.php';
		$plugin_installed = file_exists(WP_PLUGIN_DIR . '/' . $plugin_file);

		?>
		<div class="cha-antimanual-status" style="margin: 10px 0 20px;">
			<div class="card"
				style="max-width: 100%; padding: 15px; background: #fff; border: 1px solid #c3c4c7; border-radius: 4px;">
				<h4 style="margin: 0 0 10px; font-size: 14px;">
					<?php esc_html_e('Antimanual AI Provider Status', 'changeloger'); ?>
				</h4>

				<?php if (!$plugin_installed): ?>
					<!-- Not Installed -->
					<div class="notice notice-error inline" style="margin: 0 0 15px; padding: 10px;">
						<p style="margin: 0;">
							<span style="color: #d63638;">✗</span>
							<?php esc_html_e('Antimanual plugin is not installed.', 'changeloger'); ?>
						</p>
					</div>
					<p style="margin: 0 0 10px; color: #666;">
						<?php esc_html_e('The Antimanual plugin is required for AI-enhanced email generation.', 'changeloger'); ?>
					</p>
					<a href="<?php echo esc_url(admin_url('plugin-install.php?s=antimanual&tab=search&type=term')); ?>"
						class="button button-primary">
						<?php esc_html_e('Install Antimanual', 'changeloger'); ?>
					</a>

				<?php elseif (!$antimanual_active): ?>
					<!-- Installed but not active -->
					<div class="notice notice-warning inline" style="margin: 0 0 15px; padding: 10px;">
						<p style="margin: 0;">
							<span style="color: #dba617;">⚠</span>
							<?php esc_html_e('Antimanual plugin is installed but not activated.', 'changeloger'); ?>
						</p>
					</div>
					<a href="<?php echo esc_url(wp_nonce_url(admin_url('plugins.php?action=activate&plugin=' . urlencode($plugin_file)), 'activate-plugin_' . $plugin_file)); ?>"
						class="button button-primary">
						<?php esc_html_e('Activate Antimanual', 'changeloger'); ?>
					</a>

				<?php elseif (!$api_key_configured): ?>
					<!-- Active but no API key -->
					<div class="notice notice-warning inline" style="margin: 0 0 15px; padding: 10px;">
						<p style="margin: 0;">
							<span style="color: #dba617;">⚠</span>
							<?php esc_html_e('Antimanual is active but no AI API key is configured.', 'changeloger'); ?>
						</p>
					</div>
					<p style="margin: 0 0 10px; color: #666;">
						<?php esc_html_e('Please configure your AI provider API key in Antimanual settings.', 'changeloger'); ?>
					</p>
					<a href="<?php echo esc_url(admin_url('admin.php?page=antimanual-settings')); ?>" class="button button-primary">
						<?php esc_html_e('Configure API Key', 'changeloger'); ?>
					</a>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}
}

/**
 * Render Notification Test callback
 * Displays product dropdown, email input, and send test email button
 */
if ( ! function_exists( 'cha_render_notification_test' ) ) {
	function cha_render_notification_test() {
		// Only available for premium users.
		if ( ! function_exists( 'cha_is_premium' ) || ! cha_is_premium() ) {
			echo '<p style="color: #999;">' . esc_html__( 'Upgrade to Pro to send test notification emails.', 'changeloger' ) . '</p>';
			return;
		}

		$products    = get_terms( [
			'taxonomy'   => 'cha_product',
			'hide_empty' => false,
			'orderby'    => 'term_id',
		] );
		$admin_email = get_option( 'admin_email' );
		?>
		<div class="cha-notification-test" style="margin: 10px 0 20px;">
			<div class="card" style="max-width: 100%; padding: 20px; background: #fff; border: 1px solid #c3c4c7; border-radius: 4px;">
				<h4 style="margin: 0 0 6px; font-size: 14px;">
					<?php esc_html_e( 'Send Test Email', 'changeloger' ); ?>
				</h4>
				<p style="margin: 0 0 16px; color: #666; font-size: 13px;">
					<?php esc_html_e( 'Send a preview notification email to verify your settings. The email will use sample release data.', 'changeloger' ); ?>
				</p>

				<table class="form-table" style="margin: 0;">
					<tr>
						<th scope="row" style="width: 140px; padding: 10px 0;">
							<label for="cha-test-product"><?php esc_html_e( 'Product', 'changeloger' ); ?></label>
						</th>
						<td style="padding: 10px 0;">
							<select id="cha-test-product" style="min-width: 250px;">
								<?php if ( ! empty( $products ) && ! is_wp_error( $products ) ) : ?>
									<?php foreach ( $products as $product ) : ?>
										<option value="<?php echo esc_attr( $product->term_id ); ?>">
											<?php echo esc_html( $product->name ); ?>
										</option>
									<?php endforeach; ?>
								<?php else : ?>
									<option value=""><?php esc_html_e( 'No products found', 'changeloger' ); ?></option>
								<?php endif; ?>
							</select>
						</td>
					</tr>
					<tr>
						<th scope="row" style="padding: 10px 0;">
							<label for="cha-test-email"><?php esc_html_e( 'Recipient Email', 'changeloger' ); ?></label>
						</th>
						<td style="padding: 10px 0;">
							<input type="email" id="cha-test-email" value="<?php echo esc_attr( $admin_email ); ?>" style="min-width: 250px;" />
						</td>
					</tr>
				</table>

				<div style="margin-top: 16px;">
					<button type="button" id="cha-send-test-email" class="button button-primary">
						<span class="dashicons dashicons-email" style="margin-top: 3px; margin-right: 4px;"></span>
						<?php esc_html_e( 'Send Test Email', 'changeloger' ); ?>
					</button>
					<span id="cha-test-email-spinner" class="spinner" style="float: none; margin-top: 4px;"></span>
				</div>

				<div id="cha-test-email-result" style="display: none; margin-top: 12px;"></div>
			</div>
		</div>

		<script type="text/javascript">
			( function() {
				'use strict';
				var btn     = document.getElementById( 'cha-send-test-email' );
				var spinner = document.getElementById( 'cha-test-email-spinner' );
				var result  = document.getElementById( 'cha-test-email-result' );

				if ( ! btn ) {
					return;
				}

				btn.addEventListener( 'click', function() {
					var productId = document.getElementById( 'cha-test-product' ).value;
					var email     = document.getElementById( 'cha-test-email' ).value;

					if ( ! productId ) {
						showResult( '<?php echo esc_js( __( 'Please select a product.', 'changeloger' ) ); ?>', 'error' );
						return;
					}

					if ( ! email ) {
						showResult( '<?php echo esc_js( __( 'Please enter a recipient email.', 'changeloger' ) ); ?>', 'error' );
						return;
					}

					btn.disabled = true;
					spinner.classList.add( 'is-active' );
					result.style.display = 'none';

					fetch( '<?php echo esc_url( rest_url( 'changeloger-pro/v1/send-test-notification' ) ); ?>', {
						method: 'POST',
						headers: {
							'Content-Type': 'application/json',
							'X-WP-Nonce': '<?php echo esc_attr( wp_create_nonce( 'wp_rest' ) ); ?>'
						},
						body: JSON.stringify( {
							product_id: parseInt( productId, 10 ),
							email: email
						} )
					} )
					.then( function( response ) {
						return response.json().then( function( data ) {
							return { ok: response.ok, data: data };
						} );
					} )
					.then( function( res ) {
						btn.disabled = false;
						spinner.classList.remove( 'is-active' );

						if ( res.ok && res.data.success ) {
							showResult( res.data.message, 'success' );
						} else {
							var msg = res.data.message || '<?php echo esc_js( __( 'Failed to send test email.', 'changeloger' ) ); ?>';
							showResult( msg, 'error' );
						}
					} )
					.catch( function() {
						btn.disabled = false;
						spinner.classList.remove( 'is-active' );
						showResult( '<?php echo esc_js( __( 'Network error. Please try again.', 'changeloger' ) ); ?>', 'error' );
					} );
				} );

				function showResult( message, type ) {
					var color = type === 'success' ? '#00a32a' : '#d63638';
					var bg    = type === 'success' ? '#ecf7ed' : '#fcf0f1';
					var icon  = type === 'success' ? '✓' : '✗';
					result.innerHTML = '<div style="padding: 10px 14px; background: ' + bg + '; border-left: 4px solid ' + color + '; border-radius: 4px;"><span style="color: ' + color + '; font-weight: 600;">' + icon + '</span> ' + message + '</div>';
					result.style.display = 'block';
				}
			} )();
		</script>
		<?php
	}
}

