<?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',
			'serif'   => 'Georgia, "Times New Roman", Times, serif',
			'modern'  => '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
			'rounded' => '"Nunito", -apple-system, BlinkMacSystemFont, sans-serif',
		);
		$font = get_theme_mod( 'fanspaysite_font_preset', 'system' );
		if ( isset( $font_stacks[ $font ] ) ) :
		?>
		:root { --font-family-base: <?php echo esc_html( $font_stacks[ $font ] ); ?>; }
		body, .site-content, .entry-content { font-family: var(--font-family-base); }
		<?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' );

/**
 * Enqueue Google Fonts when a non-system font preset is selected.
 *
 * @since 2.2
 */
function fanspaysite_enqueue_fonts() {
	$font = get_theme_mod( 'fanspaysite_font_preset', 'system' );
	$google_fonts = array(
		'modern'  => 'Inter:wght@400;600;700',
		'rounded' => 'Nunito:wght@400;600;700',
	);
	if ( isset( $google_fonts[ $font ] ) ) {
		wp_enqueue_style(
			'fanspaysite-google-fonts',
			'https://fonts.googleapis.com/css2?family=' . urlencode( $google_fonts[ $font ] ) . '&display=swap',
			array(),
			null
		);
	}
}
add_action( 'wp_enqueue_scripts', 'fanspaysite_enqueue_fonts' );


// 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.
