<?php
/**
 * Output inline CSS for Customizer color, layout, and typography settings.
 *
 * @since 2.0
 */
function fanspaysite_customizer_css() {
	?>
	<style id="fanspaysite-customizer-css">
		[data-theme="light"] {
			--text-color: <?php echo esc_attr( get_theme_mod( 'light_mode_text_color', '#333333' ) ); ?>;
			--background-color: <?php echo esc_attr( get_theme_mod( 'light_mode_background_color', '#ffffff' ) ); ?>;
			--link-color: <?php echo esc_attr( get_theme_mod( 'light_mode_link_color', '#77145d' ) ); ?>;
		}
		[data-theme="dark"] {
			--text-color: <?php echo esc_attr( get_theme_mod( 'dark_mode_text_color', '#ffffff' ) ); ?>;
			--background-color: <?php echo esc_attr( get_theme_mod( 'dark_mode_background_color', '#333333' ) ); ?>;
			--link-color: <?php echo esc_attr( get_theme_mod( 'dark_mode_link_color', '#d39ed8' ) ); ?>;
		}
		<?php // Sticky Menu Bar ?>
		<?php if ( get_theme_mod( 'fanspaysite_sticky_header', true ) ) : ?>
		.site-wrapper { height: 100vh; }
		.layout-top-bar .site-topbar { position: sticky; top: 0; z-index: 1000; }
		<?php else : ?>
		html, body { height: auto !important; overflow-y: auto !important; }
		.site-wrapper { height: auto !important; min-height: 100vh; }
		.site-sidebar { overflow: visible !important; }
		.site-content { overflow: visible !important; }
		.site-sidebar-right { overflow: visible !important; }
		.site-content-wrapper { overflow: visible !important; }
		<?php endif; ?>
		<?php // Content width ?>
		<?php $cw = get_theme_mod( 'fanspaysite_content_width', 'default' ); ?>
		<?php if ( $cw === 'boxed' ) : ?>
		.site-content { max-width: 960px; margin-left: auto; margin-right: auto; }
		<?php elseif ( $cw === 'wide' ) : ?>
		.site-content { max-width: 100%; }
		<?php endif; ?>
		<?php // Right sidebar ?>
		<?php $rs = get_theme_mod( 'fanspaysite_show_right_sidebar', 'auto' ); ?>
		<?php if ( $rs === 'no' ) : ?>
		.site-sidebar-right { display: none !important; }
		<?php elseif ( $rs === 'yes' ) : ?>
		.site-sidebar-right { display: block !important; }
		<?php endif; ?>
		<?php // Font preset ?>
		<?php
		$font_stacks = array(
			'system'       => '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
			'modern'       => '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
			'rounded'      => '"Nunito", -apple-system, BlinkMacSystemFont, sans-serif',
			'lato'         => '"Lato", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
			'roboto'       => '"Roboto", -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif',
			'open_sans'    => '"Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif',
			'poppins'      => '"Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
			'serif'        => 'Georgia, "Times New Roman", Times, serif',
			'merriweather' => '"Merriweather", Georgia, "Times New Roman", Times, serif',
		);
		$font = get_theme_mod( 'fanspaysite_font_preset', 'system' );
		if ( isset( $font_stacks[ $font ] ) ) :
		?>
		:root { --font-family-base: <?php echo $font_stacks[ $font ]; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded CSS font stacks, no user input ?>; }
		body,
		h1, h2, h3, h4, h5, h6,
		.site-content, .entry-content,
		.ui.menu, .ui.button, .ui.header, .ui.form,
		.ui.input input, .ui.input textarea,
		.ui.card, .ui.item, .ui.list,
		.ui.accordion, .ui.statistic, .ui.step,
		.ui.segment, .ui.message, .ui.label,
		.ui.dropdown, .ui.comment {
			font-family: var(--font-family-base) !important;
		}
		<?php endif; ?>
		<?php // Fullpage archive mode: remove padding for edge-to-edge media ?>
		<?php if ( 'fullpage' === get_theme_mod( 'fanspaysite_archive_display', 'classic' ) ) : ?>
		.archive-display-fullpage .site-main { padding: 0; max-width: 100%; }
		.archive-display-fullpage .content-area { padding: 0; }
		<?php endif; ?>
	</style>
	<?php
}
add_action( 'wp_head', 'fanspaysite_customizer_css' );

/**
 * Get the Google Font family for the active preset.
 *
 * @since 2.6
 * @return string
 */
function fanspaysite_get_google_font_family() {
	$font = get_theme_mod( 'fanspaysite_font_preset', 'system' );
	$google_fonts = array(
		'modern'       => 'Inter:wght@400;600;700',
		'rounded'      => 'Nunito:wght@400;600;700',
		'roboto'       => 'Roboto:wght@400;500;700',
		'open_sans'    => 'Open Sans:wght@400;600;700',
		'poppins'      => 'Poppins:wght@400;500;600;700',
		'merriweather' => 'Merriweather:wght@400;700',
	);

	return isset( $google_fonts[ $font ] ) ? $google_fonts[ $font ] : '';
}

/**
 * Enqueue Google Fonts when a non-system font preset is selected.
 *
 * @since 2.2
 */
function fanspaysite_enqueue_fonts() {
	$font_family = fanspaysite_get_google_font_family();
	if ( '' === $font_family ) {
		return;
	}

	wp_enqueue_style(
		'fanspaysite-google-fonts',
		'https://fonts.googleapis.com/css2?family=' . urlencode( $font_family ) . '&display=swap',
		array(),
		null
	);
}
add_action( 'wp_enqueue_scripts', 'fanspaysite_enqueue_fonts' );

/**
 * Add resource hints for Google Fonts when a webfont preset is active.
 *
 * @since 2.6
 * @param array  $urls          Existing resource hints.
 * @param string $relation_type Hint type.
 * @return array
 */
function fanspaysite_google_fonts_resource_hints( $urls, $relation_type ) {
	if ( '' === fanspaysite_get_google_font_family() || 'preconnect' !== $relation_type ) {
		return $urls;
	}

	$urls[] = 'https://fonts.googleapis.com';
	$urls[] = array(
		'href'        => 'https://fonts.gstatic.com',
		'crossorigin' => 'anonymous',
	);

	return $urls;
}
add_filter( 'wp_resource_hints', 'fanspaysite_google_fonts_resource_hints', 10, 2 );

/**
 * Load Google Fonts asynchronously to keep them out of the critical render path.
 *
 * @since 2.6
 * @param string $html   The generated link tag.
 * @param string $handle Style handle.
 * @param string $href   Style URL.
 * @param string $media  Media attribute.
 * @return string
 */
function fanspaysite_google_fonts_style_loader_tag( $html, $handle, $href, $media ) {
	if ( 'fanspaysite-google-fonts' !== $handle ) {
		return $html;
	}

	$media = $media ? $media : 'all';

	return sprintf(
		"<link rel='stylesheet' id='%1\$s-css' href='%2\$s' media='print' onload=\"this.media='%3\$s'\" />\n<noscript><link rel='stylesheet' id='%1\$s-noscript-css' href='%2\$s' media='%3\$s' /></noscript>\n",
		esc_attr( $handle ),
		esc_url( $href ),
		esc_attr( $media )
	);
}
add_filter( 'style_loader_tag', 'fanspaysite_google_fonts_style_loader_tag', 10, 4 );


// Theme Mode settings
function fanspaysite_add_user_theme_mode_field($user) {
	$user_theme_mode = get_user_meta($user->ID, 'fanspaysite_user_theme_mode', true);
	?>
	<h3><?php _e('Theme Mode', 'fanspaysite'); ?></h3>
	<table class="form-table">
		<tr>
			<th><label for="fanspaysite_user_theme_mode"><?php _e('Theme Mode', 'fanspaysite'); ?></label></th>
			<td>
				<select name="fanspaysite_user_theme_mode" id="fanspaysite_user_theme_mode">
					<option value=""><?php _e('Use Site Default', 'fanspaysite'); ?></option>
					<option value="light" <?php selected($user_theme_mode, 'light'); ?>><?php _e('Light', 'fanspaysite'); ?></option>
					<option value="dark" <?php selected($user_theme_mode, 'dark'); ?>><?php _e('Dark', 'fanspaysite'); ?></option>
					<option value="auto" <?php selected($user_theme_mode, 'auto'); ?>><?php _e('Auto', 'fanspaysite'); ?></option>
				</select>
			</td>
		</tr>
	</table>
	<?php
}
add_action('show_user_profile', 'fanspaysite_add_user_theme_mode_field');
add_action('edit_user_profile', 'fanspaysite_add_user_theme_mode_field');

function fanspaysite_save_user_theme_mode($user_id) {
	if (!current_user_can('edit_user', $user_id)) {
		return false;
	}
	update_user_meta($user_id, 'fanspaysite_user_theme_mode', sanitize_text_field( $_POST['fanspaysite_user_theme_mode'] ?? '' ));
}
add_action('personal_options_update', 'fanspaysite_save_user_theme_mode');
add_action('edit_user_profile_update', 'fanspaysite_save_user_theme_mode');

/**
 * Apply theme mode early in <head> to prevent FOUC (flash of unstyled content).
 *
 * Sets data-theme on <html> before CSS renders so color variables resolve immediately.
 * The Fomantic UI .inverted class toggle runs after DOMContentLoaded since it needs <body>.
 *
 * @since 2.2
 */
function fanspaysite_apply_theme_mode() {
	$theme_mode = fanspaysite_get_current_theme_mode();
	?>
	<script>
	(function(){
		var theme = "<?php echo esc_js( $theme_mode ); ?>";
		var isDark = (theme === "dark") || (theme === "auto" && window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches);
		document.documentElement.setAttribute("data-theme", isDark ? "dark" : "light");
	})();
	</script>
	<?php
}
add_action( 'wp_head', 'fanspaysite_apply_theme_mode', 1 );

/**
 * Apply Fomantic UI inverted classes after DOM is ready.
 *
 * @since 2.2
 */
function fanspaysite_apply_theme_mode_body() {
	$theme_mode = fanspaysite_get_current_theme_mode();
	?>
	<script>
	if (typeof setConfiguredTheme !== "function") {
		function setConfiguredTheme(theme) {
			if (theme === "auto") {
				if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
					document.body.dataset.theme = "dark";
				} else {
					document.body.dataset.theme = "light";
				}
			} else {
				document.body.dataset.theme = theme;
			}
			document.documentElement.setAttribute("data-theme", document.body.dataset.theme);
			var isDark = (document.body.dataset.theme === "dark");
			jQuery("body").toggleClass("inverted", isDark);
			jQuery("body").find(".ui").toggleClass("inverted", isDark);
		}
	}
	document.addEventListener("DOMContentLoaded", function() {
		setConfiguredTheme("<?php echo esc_js( $theme_mode ); ?>");
	});
	</script>
	<?php
}
add_action( 'wp_footer', 'fanspaysite_apply_theme_mode_body' );

/**
 * Enqueue the theme mode switch script.
 *
 * @since 2.0
 */
function fanspaysite_enqueue_theme_switch_script() {
	$scriptPath = get_template_directory() . '/js/theme.js';
	$version = file_exists( $scriptPath ) ? filemtime( $scriptPath ) : '2.2';
	wp_enqueue_script( 'fanspaysite-theme-switch', get_template_directory_uri() . '/js/theme.js', array( 'jquery' ), $version, true );

	// Pass the current theme mode to the script
	wp_localize_script('fanspaysite-theme-switch', 'fanspaysiteThemeSwitch', array(
		'ajax_url' => admin_url('admin-ajax.php'),
		'current_mode' => fanspaysite_get_current_theme_mode(),
		'nonce' => wp_create_nonce('fanspaysite-theme-switch-nonce'),
	));
}
add_action('wp_enqueue_scripts', 'fanspaysite_enqueue_theme_switch_script');

// Helper function to get the current theme mode
function fanspaysite_get_current_theme_mode() {

	// Get user-specific theme mode if logged in
	if (is_user_logged_in()) {
		$user_theme_mode = get_user_meta(get_current_user_id(), 'fanspaysite_user_theme_mode', true);
		if ($user_theme_mode ?? false) {
			return $user_theme_mode;
		}
	}

	// Check for a theme mode set in a cookie for non-logged-in users
	if (isset($_COOKIE['fanspaysite_user_theme_mode'])) {
		$cookie_theme_mode = sanitize_text_field($_COOKIE['fanspaysite_user_theme_mode']);
		if (!empty($cookie_theme_mode)) {
			return $cookie_theme_mode;
		}
	}

	// Fallback to the site-wide default theme mode
	return get_theme_mod('fanspaysite_default_theme_mode', 'light') ;
}

// AJAX action to update user theme mode
function fanspaysite_update_theme_mode() {
	check_ajax_referer('fanspaysite-theme-switch-nonce', 'nonce');

	$mode = isset($_POST['mode']) ? sanitize_text_field($_POST['mode']) : 'light'; // Default to light mode if not set.

	if (!is_user_logged_in()) {
		// Set a cookie for non-logged-in users to remember the theme mode.
		$cookie_name = 'fanspaysite_user_theme_mode';
		$cookie_value = $mode;
		$expire = time() + (86400 * 30); // 30 days from now.
		$path = '/'; // Available site-wide.

		setcookie($cookie_name, $cookie_value, $expire, $path, COOKIE_DOMAIN, is_ssl(), true);

		wp_send_json(array(
			'success' => true,
			'message' => 'Theme mode saved in a cookie.'
		));
		return;
	}

	// For logged-in users, update user meta.
	update_user_meta(get_current_user_id(), 'fanspaysite_user_theme_mode', $mode);

	wp_send_json_success('Theme mode updated for user: ' . esc_attr($mode));
}
add_action('wp_ajax_fanspaysite_update_theme_mode', 'fanspaysite_update_theme_mode'); // For logged-in users.
add_action('wp_ajax_nopriv_fanspaysite_update_theme_mode', 'fanspaysite_update_theme_mode'); // For not logged-in users.
