<?php
/**
 * Admin settings page template.
 *
 * @package    MaplePress
 * @subpackage MaplePress/includes
 */

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

$options     = get_option( 'maplepress_settings', array() );
$has_api_key = ! empty( $options['api_key'] );
$is_verified = isset( $options['is_verified'] ) && $options['is_verified'];

// Debug: Log current options
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
	error_log( 'MaplePress Settings Page - api_url: ' . ( $options['api_url'] ?? 'NOT SET' ) );
	error_log( 'MaplePress Settings Page - api_key: ' . ( isset( $options['api_key'] ) ? 'SET (' . strlen( $options['api_key'] ) . ' chars)' : 'NOT SET' ) );
	error_log( 'MaplePress Settings Page - has_api_key: ' . ( $has_api_key ? 'true' : 'false' ) );
	error_log( 'MaplePress Settings Page - is_verified: ' . ( $is_verified ? 'true' : 'false' ) );
}
?>

<div class="wrap">
	<h1><?php esc_html_e( 'MaplePress Settings', 'maplepress' ); ?></h1>

	<?php
	// WordPress automatically displays settings errors, no need to call settings_errors() manually
	?>

	<?php if ( ! $has_api_key ) : ?>
		<!-- First-time setup instructions -->
		<div class="notice notice-info" style="padding: 15px; margin: 20px 0;">
			<h2 style="margin-top: 0;"><?php esc_html_e( '🚀 Getting Started', 'maplepress' ); ?></h2>
			<p><?php esc_html_e( 'Connect your WordPress site to MaplePress cloud services to enable advanced search and more.', 'maplepress' ); ?></p>
			<ol style="margin-left: 20px;">
				<li>
					<strong><?php esc_html_e( 'Create a MaplePress account:', 'maplepress' ); ?></strong><br>
					<a href="https://getmaplepress.com/register" target="_blank" class="button button-primary" style="margin-top: 5px;">
						<?php esc_html_e( 'Sign Up', 'maplepress' ); ?>
					</a>
					<?php esc_html_e( 'or', 'maplepress' ); ?>
					<a href="https://getmaplepress.com/login" target="_blank" class="button" style="margin-top: 5px;">
						<?php esc_html_e( 'Login', 'maplepress' ); ?>
					</a>
				</li>
				<li style="margin-top: 10px;">
					<strong><?php esc_html_e( 'Create a site in your dashboard', 'maplepress' ); ?></strong>
				</li>
				<li style="margin-top: 10px;">
					<strong><?php esc_html_e( 'Copy your API credentials and paste them below', 'maplepress' ); ?></strong>
				</li>
			</ol>
		</div>
	<?php endif; ?>

	<form method="post" action="options.php">
		<?php settings_fields( 'maplepress_settings_group' ); ?>

		<table class="form-table">
			<tr>
				<th scope="row">
					<label for="api_url"><?php esc_html_e( 'API URL', 'maplepress' ); ?></label>
				</th>
				<td>
					<?php if ( $is_verified ) : ?>
						<!-- Show URL as read-only when verified -->
						<input type="text"
							   id="api_url"
							   value="<?php echo esc_attr( $options['api_url'] ?? '' ); ?>"
							   class="regular-text"
							   disabled>
						<input type="hidden"
							   name="maplepress_settings[api_url]"
							   value="<?php echo esc_attr( $options['api_url'] ?? '' ); ?>">
						<p class="description">
							<?php esc_html_e( 'Connected. To change, disconnect first.', 'maplepress' ); ?>
						</p>
					<?php else : ?>
						<!-- Allow editing when not verified -->
						<input type="text"
							   id="api_url"
							   name="maplepress_settings[api_url]"
							   value="<?php echo esc_attr( ! empty( $options['api_url'] ) ? $options['api_url'] : 'https://getmaplepress.ca' ); ?>"
							   class="regular-text"
							   placeholder="https://getmaplepress.ca">
						<p class="description">
							<?php esc_html_e( 'Your MaplePress API endpoint URL', 'maplepress' ); ?>
						</p>
					<?php endif; ?>
				</td>
			</tr>

			<tr>
				<th scope="row">
					<label for="api_key"><?php esc_html_e( 'API Key', 'maplepress' ); ?></label>
				</th>
				<td>
					<?php if ( $is_verified ) : ?>
						<!-- Show masked key when verified -->
						<div style="margin-bottom: 10px;">
							<code style="background: #f0f0f1; padding: 8px 12px; border-radius: 3px; font-size: 13px;">
								<?php
								$prefix = $options['api_key_prefix'] ?? 'mpsk';
								$last_four = $options['api_key_last_four'] ?? '****';
								echo esc_html( $prefix . '_' . str_repeat( '*', 28 ) . $last_four );
								?>
							</code>
						</div>
						<input type="hidden"
							   name="maplepress_settings[api_key]"
							   value="<?php echo esc_attr( $options['api_key'] ?? '' ); ?>">
						<p class="description">
							<?php esc_html_e( 'Your API key is securely stored. To change it, disconnect first.', 'maplepress' ); ?>
						</p>
					<?php else : ?>
						<!-- Allow editing when not verified -->
						<input type="password"
							   id="api_key"
							   name="maplepress_settings[api_key]"
							   value="<?php echo esc_attr( $options['api_key'] ?? '' ); ?>"
							   class="regular-text"
							   placeholder="live_sk_... or test_sk_...">
						<p class="description">
							<?php esc_html_e( 'Your MaplePress API key. Use "live_" prefix for production (https://getmaplepress.ca) or "test_" prefix for development/custom URLs.', 'maplepress' ); ?>
						</p>
					<?php endif; ?>
				</td>
			</tr>

			<?php if ( $has_api_key && ! $is_verified ) : ?>
				<!-- DNS Verification Required Section -->
				<tr>
					<th scope="row" colspan="2">
						<h3 style="margin: 30px 0 10px 0; color: #d63638;">
							⚠️ <?php esc_html_e( 'Domain Verification Required', 'maplepress' ); ?>
						</h3>
					</th>
				</tr>
				<tr>
					<td colspan="2">
						<div class="notice notice-warning inline" style="margin: 0; padding: 20px; background: #fff3cd; border-left: 4px solid #ffc107;">
							<h4 style="margin-top: 0;">
								<?php esc_html_e( '🔐 Your API key is connected, but your domain needs verification to enable syncing.', 'maplepress' ); ?>
							</h4>

							<p><?php esc_html_e( 'To verify ownership of your domain, please add the following DNS TXT record:', 'maplepress' ); ?></p>

							<table class="widefat" style="background: #f9f9f9; margin: 15px 0; max-width: 600px;">
								<tbody>
									<tr>
										<td style="width: 150px; font-weight: bold; padding: 12px;">
											<?php esc_html_e( 'Host/Name:', 'maplepress' ); ?>
										</td>
										<td style="padding: 12px;">
											<code style="background: #fff; padding: 5px 10px; font-size: 13px;">
												<?php echo esc_html( $options['domain'] ?? 'your-domain.com' ); ?>
											</code>
										</td>
									</tr>
									<tr>
										<td style="font-weight: bold; padding: 12px;">
											<?php esc_html_e( 'Type:', 'maplepress' ); ?>
										</td>
										<td style="padding: 12px;">
											<code style="background: #fff; padding: 5px 10px; font-size: 13px;">TXT</code>
										</td>
									</tr>
									<tr>
										<td style="font-weight: bold; padding: 12px;">
											<?php esc_html_e( 'Value:', 'maplepress' ); ?>
										</td>
										<td style="padding: 12px;">
											<code style="background: #fff; padding: 5px 10px; font-size: 13px; word-break: break-all;">
												maplepress-verify=<?php echo esc_html( $options['verification_token'] ?? 'xxx' ); ?>
											</code>
										</td>
									</tr>
								</tbody>
							</table>

							<div style="background: #e7f3ff; border-left: 3px solid #2271b1; padding: 15px; margin: 20px 0;">
								<h4 style="margin-top: 0;">
									<?php esc_html_e( '📋 Step-by-Step Instructions:', 'maplepress' ); ?>
								</h4>
								<ol style="margin: 10px 0 10px 20px; line-height: 1.8;">
									<li><?php esc_html_e( 'Log in to your domain registrar (GoDaddy, Namecheap, Cloudflare, etc.)', 'maplepress' ); ?></li>
									<li><?php esc_html_e( 'Navigate to DNS settings for your domain', 'maplepress' ); ?></li>
									<li><?php esc_html_e( 'Add a new TXT record with the values shown above', 'maplepress' ); ?></li>
									<li><?php esc_html_e( 'Wait 5-10 minutes for DNS propagation (can take up to 48 hours)', 'maplepress' ); ?></li>
									<li><?php esc_html_e( 'Click the "Verify Domain Now" button below', 'maplepress' ); ?></li>
								</ol>
							</div>

							<!-- Progress indicator (hidden by default) -->
							<div id="maplepress-verification-progress" style="display: none; background: #fff; border: 1px solid #dcdcde; padding: 20px; margin: 20px 0; border-radius: 4px;">
								<div style="display: flex; align-items: center; margin-bottom: 15px;">
									<span class="spinner is-active" style="float: none; margin: 0 10px 0 0;"></span>
									<strong id="maplepress-verification-status" style="font-size: 14px;">Verifying domain...</strong>
								</div>

								<div id="maplepress-verification-details" style="color: #666; font-size: 13px; margin-top: 10px;">
									<!-- Progress details will appear here -->
								</div>

								<!-- Progress bar -->
								<div id="maplepress-verification-progressbar" style="display: none; margin-top: 15px;">
									<div style="background: #f0f0f1; border-radius: 4px; height: 24px; position: relative; overflow: hidden;">
										<div id="maplepress-verification-progressbar-fill" style="background: linear-gradient(90deg, #2271b1 0%, #135e96 100%); height: 100%; width: 0%; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center;">
											<span id="maplepress-verification-progressbar-text" style="color: #fff; font-size: 12px; font-weight: 600; position: absolute; width: 100%; text-align: center; z-index: 2;"></span>
										</div>
									</div>
								</div>
							</div>

							<form id="maplepress-verify-form" method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" style="margin-top: 20px;">
								<input type="hidden" name="action" value="maplepress_verify_domain">
								<?php wp_nonce_field( 'maplepress_verify_domain' ); ?>
								<p>
									<button type="submit" id="maplepress-verify-button" class="button button-primary button-large">
										🔍 <?php esc_html_e( 'Verify Domain Now', 'maplepress' ); ?>
									</button>
									<span style="margin-left: 15px; color: #666;">
										<?php esc_html_e( 'Make sure you\'ve added the DNS record and waited a few minutes before clicking.', 'maplepress' ); ?>
									</span>
								</p>
							</form>

							<script>
							jQuery(document).ready(function($) {
								$('#maplepress-verify-form').on('submit', function(e) {
									e.preventDefault();

									var button = $('#maplepress-verify-button');
									var progressBox = $('#maplepress-verification-progress');
									var statusText = $('#maplepress-verification-status');
									var detailsBox = $('#maplepress-verification-details');
									var progressBar = $('#maplepress-verification-progressbar');
									var progressBarFill = $('#maplepress-verification-progressbar-fill');
									var progressBarText = $('#maplepress-verification-progressbar-text');

									// Disable button and show progress
									button.prop('disabled', true);
									button.text('⏳ Verifying...');
									progressBox.show();
									statusText.text('Step 1 of 2: Verifying domain ownership...');
									detailsBox.html('Checking DNS TXT record...');

									var startTime = Date.now();

									// Make AJAX request
									$.ajax({
										url: ajaxurl,
										type: 'POST',
										data: {
											action: 'maplepress_verify_and_sync_ajax',
											nonce: '<?php echo wp_create_nonce( 'maplepress_verify_and_sync_ajax' ); ?>'
										},
										timeout: 300000, // 5 minute timeout for large sites
										xhr: function() {
											var xhr = new window.XMLHttpRequest();

											// Simulate progress during long operations
											var progressSimulator = setInterval(function() {
												var elapsed = (Date.now() - startTime) / 1000;

												if (elapsed < 5) {
													detailsBox.html('Checking DNS TXT record...');
												} else if (elapsed < 10) {
													statusText.text('Step 2 of 2: Syncing pages to MaplePress...');
													detailsBox.html('Preparing pages for sync...');
													progressBar.show();
													progressBarFill.css('width', '10%');
													progressBarText.text('10%');
												} else if (elapsed < 30) {
													var progress = Math.min(10 + ((elapsed - 10) / 20) * 60, 70);
													detailsBox.html('Syncing pages to MaplePress cloud...<br><small>This may take a moment for large sites...</small>');
													progressBarFill.css('width', progress + '%');
													progressBarText.text(Math.round(progress) + '%');
												} else {
													var progress = Math.min(70 + ((elapsed - 30) / 30) * 25, 95);
													detailsBox.html('Almost done, finalizing sync...<br><small>Processing batches...</small>');
													progressBarFill.css('width', progress + '%');
													progressBarText.text(Math.round(progress) + '%');
												}
											}, 1000);

											xhr.addEventListener('loadend', function() {
												clearInterval(progressSimulator);
											});

											return xhr;
										},
										success: function(response) {
											if (response.success) {
												// Show 100% complete
												progressBar.show();
												progressBarFill.css('width', '100%');
												progressBarText.text('100%');

												statusText.html('<span style="color: #008a00;">✓ ' + response.data.message + '</span>');
												detailsBox.html(response.data.details || '');

												// Reload page after 2 seconds
												setTimeout(function() {
													window.location.href = '<?php echo admin_url( 'admin.php?page=maplepress-settings&verification_status=success' ); ?>';
												}, 2000);
											} else {
												progressBar.hide();
												statusText.html('<span style="color: #d63638;">✗ Verification failed</span>');
												detailsBox.html('<strong>Error:</strong> ' + (response.data || 'Unknown error'));
												button.prop('disabled', false);
												button.text('🔍 <?php esc_html_e( 'Verify Domain Now', 'maplepress' ); ?>');
											}
										},
										error: function(xhr, status, error) {
											progressBar.hide();
											statusText.html('<span style="color: #d63638;">✗ Network error</span>');
											detailsBox.html('<strong>Error:</strong> ' + error);
											button.prop('disabled', false);
											button.text('🔍 <?php esc_html_e( 'Verify Domain Now', 'maplepress' ); ?>');
										}
									});
								});
							});
							</script>

							<?php if ( isset( $_GET['verification_status'] ) && $_GET['verification_status'] === 'failed' ) : ?>
								<div class="notice notice-error inline" style="margin-top: 20px; padding: 15px; background: #fee; border-left: 4px solid #dc3232;">
									<h4 style="margin: 0 0 10px 0; color: #dc3232;">
										❌ <?php esc_html_e( 'Verification Failed', 'maplepress' ); ?>
									</h4>
									<p style="margin: 0 0 15px 0; font-size: 14px;">
										<strong><?php esc_html_e( 'Error:', 'maplepress' ); ?></strong><br>
										<?php
										if ( isset( $_GET['verification_message'] ) ) {
											echo esc_html( urldecode( $_GET['verification_message'] ) );
										} else {
											esc_html_e( 'Unknown verification error. Please check your settings and try again.', 'maplepress' );
										}
										?>
									</p>

									<?php
									$error_message = isset( $_GET['verification_message'] ) ? urldecode( $_GET['verification_message'] ) : '';

									// Show different troubleshooting tips based on error type
									if ( strpos( $error_message, 'API URL' ) !== false || strpos( $error_message, 'API Key' ) !== false ) :
										?>
										<div style="background: #fff; padding: 15px; border-radius: 4px; margin-top: 15px;">
											<h4 style="margin: 0 0 10px 0;"><?php esc_html_e( 'Configuration Issue:', 'maplepress' ); ?></h4>
											<p style="margin: 0;"><?php esc_html_e( 'Please go back and save your API URL and API Key before attempting verification.', 'maplepress' ); ?></p>
										</div>
									<?php else : ?>
										<div style="background: #fff; padding: 15px; border-radius: 4px; margin-top: 15px;">
											<h4 style="margin: 0 0 10px 0;"><?php esc_html_e( 'Common Issues:', 'maplepress' ); ?></h4>
											<ul style="margin: 0; padding-left: 20px; line-height: 1.8;">
												<li><?php esc_html_e( 'DNS record hasn\'t propagated yet (usually takes 5-10 minutes, can take up to 48 hours)', 'maplepress' ); ?></li>
												<li><?php esc_html_e( 'TXT record value doesn\'t match exactly (check for typos or extra spaces)', 'maplepress' ); ?></li>
												<li><?php esc_html_e( 'TXT record added to wrong domain or subdomain', 'maplepress' ); ?></li>
												<li><?php esc_html_e( 'Backend API connectivity issue (check if https://getmaplepress.ca is accessible)', 'maplepress' ); ?></li>
											</ul>
										</div>

										<div style="background: #e7f3ff; border-left: 3px solid #2271b1; padding: 15px; margin-top: 15px;">
											<p style="margin: 0; font-size: 14px;">
												<strong>💡 <?php esc_html_e( 'Tip:', 'maplepress' ); ?></strong>
												<?php esc_html_e( 'You can check if your DNS record is visible using online tools like "whatsmydns.net" or "dnschecker.org". Search for TXT records for your domain.', 'maplepress' ); ?>
											</p>
										</div>
									<?php endif; ?>
								</div>
							<?php endif; ?>
						</div>
					</td>
				</tr>
			<?php endif; ?>

			<?php if ( isset( $_GET['verification_status'] ) && $_GET['verification_status'] === 'success' ) : ?>
				<tr>
					<td colspan="2">
						<div class="notice notice-success inline" style="margin: 20px 0; padding: 15px;">
							<p style="margin: 0;">
								<strong>✓ <?php esc_html_e( 'Domain Verified Successfully!', 'maplepress' ); ?></strong><br>
								<?php
								if ( isset( $_GET['sync_status'] ) && $_GET['sync_status'] === 'success' && isset( $_GET['synced_count'] ) ) {
									printf(
										esc_html__( 'Your domain has been verified and %d pages have been synced to MaplePress!', 'maplepress' ),
										absint( $_GET['synced_count'] )
									);
								} else {
									esc_html_e( 'Your site is now fully connected to MaplePress. You can now sync pages and use all features.', 'maplepress' );
								}
								?>
							</p>
						</div>
					</td>
				</tr>
			<?php endif; ?>

			<?php if ( $is_verified ) : ?>
				<!-- Connection Status -->
				<tr>
					<th scope="row"><?php esc_html_e( 'Connection Status', 'maplepress' ); ?></th>
					<td>
						<span style="color: #46b450; font-weight: bold;">
							✓ <?php esc_html_e( 'Connected', 'maplepress' ); ?>
						</span>
						<p class="description">
							<?php esc_html_e( 'Your site is successfully connected to MaplePress.', 'maplepress' ); ?>
						</p>
					</td>
				</tr>

				<!-- Billing Information -->
				<tr>
					<th scope="row"><?php esc_html_e( 'Billing Model', 'maplepress' ); ?></th>
					<td>
						<strong><?php esc_html_e( 'Usage-Based', 'maplepress' ); ?></strong>
						<p class="description">
							<?php esc_html_e( 'Pay only for what you use with no limits or quotas.', 'maplepress' ); ?>
							<a href="https://getmaplepress.com/pricing" target="_blank">
								<?php esc_html_e( 'View pricing details', 'maplepress' ); ?>
							</a>
						</p>
					</td>
				</tr>
			<?php endif; ?>

			<!-- Enable MaplePress -->
			<tr>
				<th scope="row"><?php esc_html_e( 'Enable Services', 'maplepress' ); ?></th>
				<td>
					<fieldset>
						<label>
							<input type="checkbox"
								   name="maplepress_settings[enabled]"
								   value="1"
								   <?php checked( 1, $options['enabled'] ?? false ); ?>>
							<strong><?php esc_html_e( 'Enable MaplePress', 'maplepress' ); ?></strong>
						</label>
						<p class="description">
							<?php esc_html_e( 'Turn on MaplePress cloud services for this site.', 'maplepress' ); ?>
						</p>
					</fieldset>
				</td>
			</tr>

			<!-- Search Settings -->
			<tr>
				<th scope="row"><?php esc_html_e( 'Search Settings', 'maplepress' ); ?></th>
				<td>
					<fieldset>
						<label>
							<input type="checkbox"
								   name="maplepress_settings[enable_frontend_search]"
								   value="1"
								   <?php checked( 1, $options['enable_frontend_search'] ?? true ); ?>>
							<?php esc_html_e( 'Enable frontend search', 'maplepress' ); ?>
						</label>
						<br>
						<label style="margin-top: 8px; display: inline-block;">
							<input type="checkbox"
								   name="maplepress_settings[enable_admin_search]"
								   value="1"
								   <?php checked( 1, $options['enable_admin_search'] ?? false ); ?>>
							<?php esc_html_e( 'Enable admin search', 'maplepress' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'Choose where MaplePress search should be used.', 'maplepress' ); ?>
						</p>
					</fieldset>
				</td>
			</tr>
		</table>

		<?php if ( $is_verified ) : ?>
			<!-- Show both Save and Disconnect buttons when connected -->
			<p class="submit">
				<?php submit_button( __( 'Save Settings', 'maplepress' ), 'primary', 'submit', false ); ?>
				&nbsp;
				<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=maplepress-settings&action=disconnect' ), 'maplepress_disconnect' ) ); ?>"
				   class="button button-secondary"
				   onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to disconnect from MaplePress? Your data will remain in the cloud.', 'maplepress' ); ?>');">
					<?php esc_html_e( 'Disconnect', 'maplepress' ); ?>
				</a>
			</p>
		<?php else : ?>
			<!-- Show only Connect button when not connected -->
			<?php submit_button( __( 'Connect to MaplePress', 'maplepress' ), 'primary', 'submit', true ); ?>
		<?php endif; ?>
	</form>

	<!-- Reset Settings -->
	<hr style="margin: 40px 0 20px 0;">
	<h3><?php esc_html_e( 'Reset Settings', 'maplepress' ); ?></h3>
	<p><?php esc_html_e( 'If you need to start over, you can reset all MaplePress settings.', 'maplepress' ); ?></p>
	<form method="post" action="<?php echo esc_url( admin_url( 'admin.php' ) ); ?>" style="margin-top: 20px;">
		<input type="hidden" name="action" value="maplepress_reset_settings">
		<?php wp_nonce_field( 'maplepress_reset_settings' ); ?>
		<button type="submit"
				class="button button-secondary"
				style="color: #d63638; border-color: #d63638;"
				onclick="return confirm('<?php esc_attr_e( 'Are you sure you want to reset all MaplePress settings?\n\nThis will:\n- Delete API URL and API Key\n- Clear verification status\n- Remove all configuration\n\nYour data in the MaplePress cloud will NOT be affected.\n\nYou will need to reconnect after reset.', 'maplepress' ); ?>');">
			🔄 <?php esc_html_e( 'Reset All Settings', 'maplepress' ); ?>
		</button>
		<p class="description">
			<?php esc_html_e( 'This will delete all plugin settings from WordPress. Your data in the MaplePress cloud will remain safe.', 'maplepress' ); ?>
		</p>
	</form>

	<?php if ( $is_verified ) : ?>
		<!-- Show connection info when connected -->
		<hr style="margin: 40px 0;">
		<h2><?php esc_html_e( 'Connection Details', 'maplepress' ); ?></h2>
		<table class="form-table">
			<tr>
				<th scope="row"><?php esc_html_e( 'Domain', 'maplepress' ); ?></th>
				<td><?php echo esc_html( $options['domain'] ?? 'N/A' ); ?></td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Connected Since', 'maplepress' ); ?></th>
				<td>
					<?php
					// Assuming connection doesn't change often, we can use current time as reference
					// In a real scenario, you'd store a 'connected_at' timestamp
					esc_html_e( 'Active connection', 'maplepress' );
					?>
				</td>
			</tr>
		</table>
	<?php endif; ?>
</div>
