<?php
/**
 * FansPaysite Skin Management
 * Admin page: Appearance > FansPaysite (wp-admin/themes.php?page=fanspaysite-skins)
 * Manages skin apply/save/delete operations.
 */

// Register admin page under Appearance
function fanspaysite_register_skins_page() {
	add_theme_page(
		__('FansPaysite Skins', 'fanspaysite'),
		__('FansPaysite', 'fanspaysite'),
		'edit_theme_options',
		'fanspaysite-skins',
		'fanspaysite_skins_page_html'
	);
}
add_action('admin_menu', 'fanspaysite_register_skins_page');

/**
 * Built-in skins that ship with the theme.
 */
function fanspaysite_get_builtin_skins() {
	return array(
		'default' => array(
			'name'        => __('Default', 'fanspaysite'),
			'description' => __('FansPaysite default: top bar layout with burger menu, light mode with purple accents.', 'fanspaysite'),
			'layout'      => 'top-bar',
			'burger_menu'    => 'yes',
			'menu_display' => 'auto',
			'submenu_display' => 'auto',
			'submenu_hover' => 'auto',
			'default_mode' => 'light',
			'archive_display' => 'classic',
			'colors'      => array(
				'light_bg'   => '#ffffff',
				'light_text' => '#333333',
				'light_link' => '#77145d',
				'dark_bg'    => '#333333',
				'dark_text'  => '#ffffff',
				'dark_link'  => '#d39ed8',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
		'onlyfans' => array(
			'name'        => __('OnlyFans', 'fanspaysite'),
			'description' => __('OnlyFans-inspired: left sidebar feed layout, light mode default, signature cyan-blue (#00AFF0) accents.', 'fanspaysite'),
			'layout'      => 'left-sidebar',
			'burger_menu'    => 'auto',
			'menu_display' => 'big_icon',
			'submenu_display' => 'auto',
			'submenu_hover' => 'auto',
			'default_mode' => 'light',
			'archive_display' => 'boxes',
			'colors'      => array(
				'light_bg'   => '#ffffff',
				'light_text' => '#0d0d0d',
				'light_link' => '#00aff0',
				'dark_bg'    => '#1a1a1a',
				'dark_text'  => '#f5f5f5',
				'dark_link'  => '#00aff0',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
		'fanvue' => array(
			'name'        => __('Fanvue', 'fanspaysite'),
			'description' => __('Fanvue-inspired: left sidebar layout, light mode default, clean white background with signature bright green accents.', 'fanspaysite'),
			'layout'      => 'left-sidebar',
			'burger_menu'    => 'auto',
			'menu_display' => 'big_icon',
			'submenu_display' => 'auto',
			'submenu_hover' => 'auto',
			'default_mode' => 'light',
			'archive_display' => 'fullpage',
			'colors'      => array(
				'light_bg'   => '#ffffff',
				'light_text' => '#1a1a1a',
				'light_link' => '#00c853',
				'dark_bg'    => '#121212',
				'dark_text'  => '#f0f0f0',
				'dark_link'  => '#69f0ae',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
		'patreon' => array(
			'name'        => __('Patreon', 'fanspaysite'),
			'description' => __('Patreon-inspired: left sidebar layout, light mode default, clean white/grey palette with blue links.', 'fanspaysite'),
			'layout'      => 'left-sidebar',
			'burger_menu'    => 'auto',
			'menu_display' => 'small_icon_text',
			'submenu_display' => 'auto',
			'submenu_hover' => 'auto',
			'default_mode' => 'light',
			'archive_display' => 'classic',
			'colors'      => array(
				'light_bg'   => '#ffffff',
				'light_text' => '#2d2d2d',
				'light_link' => '#0066cc',
				'dark_bg'    => '#1c1c1c',
				'dark_text'  => '#e0e0e0',
				'dark_link'  => '#4d94ff',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
		'fansly' => array(
			'name'        => __('Fansly', 'fanspaysite'),
			'description' => __('Fansly-inspired: top bar navigation, dark mode default, near-black background with purple-violet accents.', 'fanspaysite'),
			'layout'      => 'top-bar',
			'burger_menu'    => 'auto',
			'menu_display' => 'big_icon',
			'submenu_display' => 'small_icon_text',
			'submenu_hover' => 'auto',
			'default_mode' => 'dark',
			'archive_display' => 'fullpage',
			'colors'      => array(
				'light_bg'   => '#f8f8ff',
				'light_text' => '#1a1a2e',
				'light_link' => '#6c5ce7',
				'dark_bg'    => '#0d0d0d',
				'dark_text'  => '#e8e8f0',
				'dark_link'  => '#a29bfe',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
	);
}

/**
 * Get all skins: built-in + custom saved ones.
 */
function fanspaysite_get_all_skins() {
	$builtin = fanspaysite_get_builtin_skins();
	$custom  = get_option('fanspaysite_skins', array());
	return array_merge($builtin, $custom);
}

/**
 * Capture current theme settings as a skin data array.
 */
function fanspaysite_capture_current_settings() {
	return array(
		'layout'          => get_theme_mod('fanspaysite_layout', 'left-sidebar'),
		'burger_menu'     => get_theme_mod('fanspaysite_burger_menu', 'auto'),
		'menu_display'    => get_theme_mod('fanspaysite_menu_display_mode', 'auto'),
		'submenu_display' => get_theme_mod('fanspaysite_submenu_display_mode', 'auto'),
		'submenu_hover'   => get_theme_mod('fanspaysite_submenu_hover', 'auto'),
		'default_mode'    => get_theme_mod('fanspaysite_default_theme_mode', 'light'),
		'colors'          => array(
			'light_bg'   => get_theme_mod('light_mode_background_color', '#ffffff'),
			'light_text' => get_theme_mod('light_mode_text_color', '#333333'),
			'light_link' => get_theme_mod('light_mode_link_color', '#77145d'),
			'dark_bg'    => get_theme_mod('dark_mode_background_color', '#333333'),
			'dark_text'  => get_theme_mod('dark_mode_text_color', '#ffffff'),
			'dark_link'  => get_theme_mod('dark_mode_link_color', '#d39ed8'),
		),
		'custom_css'      => get_theme_mod('fanspaysite_skin_custom_css', ''),
		// New v2.2 settings
		'sticky_header'   => get_theme_mod('fanspaysite_sticky_header', true),
		'content_width'   => get_theme_mod('fanspaysite_content_width', 'default'),
		'right_sidebar'   => get_theme_mod('fanspaysite_show_right_sidebar', 'auto'),
		'font_preset'     => get_theme_mod('fanspaysite_font_preset', 'system'),
		'footer_columns'  => get_theme_mod('fanspaysite_footer_columns', 1),
		'archive_display' => get_theme_mod('fanspaysite_archive_display', 'classic'),
		'is_builtin'      => false,
	);
}

/**
 * Apply a skin's settings to theme_mods.
 */
function fanspaysite_apply_skin($skin_key) {
	$skins = fanspaysite_get_all_skins();
	if (!isset($skins[$skin_key])) {
		return false;
	}

	$skin = $skins[$skin_key];

	set_theme_mod('fanspaysite_layout', $skin['layout']);
	set_theme_mod('fanspaysite_burger_menu', $skin['burger_menu'] ?? 'auto');
	set_theme_mod('fanspaysite_menu_display_mode', $skin['menu_display']);
	set_theme_mod('fanspaysite_submenu_display_mode', $skin['submenu_display'] ?? 'auto');
	set_theme_mod('fanspaysite_submenu_hover', $skin['submenu_hover'] ?? 'auto');
	set_theme_mod('fanspaysite_default_theme_mode', $skin['default_mode']);

	if (!empty($skin['colors'])) {
		set_theme_mod('light_mode_background_color', $skin['colors']['light_bg']);
		set_theme_mod('light_mode_text_color', $skin['colors']['light_text']);
		set_theme_mod('light_mode_link_color', $skin['colors']['light_link']);
		set_theme_mod('dark_mode_background_color', $skin['colors']['dark_bg']);
		set_theme_mod('dark_mode_text_color', $skin['colors']['dark_text']);
		set_theme_mod('dark_mode_link_color', $skin['colors']['dark_link']);
	}

	set_theme_mod('fanspaysite_skin_custom_css', $skin['custom_css'] ?? '');

	// New v2.2 settings (backward-compatible: use defaults when missing)
	set_theme_mod('fanspaysite_sticky_header', $skin['sticky_header'] ?? true);
	set_theme_mod('fanspaysite_content_width', $skin['content_width'] ?? 'default');
	set_theme_mod('fanspaysite_show_right_sidebar', $skin['right_sidebar'] ?? 'auto');
	set_theme_mod('fanspaysite_font_preset', $skin['font_preset'] ?? 'system');
	set_theme_mod('fanspaysite_footer_columns', $skin['footer_columns'] ?? 1);
	set_theme_mod('fanspaysite_archive_display', $skin['archive_display'] ?? 'classic');

	update_option('fanspaysite_active_skin', $skin_key);

	return true;
}

/**
 * Save current settings as a skin.
 */
function fanspaysite_save_skin($skin_key, $name, $description) {
	$custom_skins = get_option('fanspaysite_skins', array());
	$settings     = fanspaysite_capture_current_settings();

	$settings['name']        = sanitize_text_field($name);
	$settings['description'] = sanitize_textarea_field($description);
	$settings['is_builtin']  = false;

	$custom_skins[$skin_key] = $settings;
	update_option('fanspaysite_skins', $custom_skins);
	update_option('fanspaysite_active_skin', $skin_key);

	return true;
}

/**
 * Delete a custom skin.
 */
function fanspaysite_delete_skin($skin_key) {
	$builtin = fanspaysite_get_builtin_skins();
	if (isset($builtin[$skin_key])) {
		return false; // Cannot delete built-in skins
	}

	$custom_skins = get_option('fanspaysite_skins', array());
	if (isset($custom_skins[$skin_key])) {
		unset($custom_skins[$skin_key]);
		update_option('fanspaysite_skins', $custom_skins);

		// If active skin was deleted, revert to default
		if (get_option('fanspaysite_active_skin') === $skin_key) {
			fanspaysite_apply_skin('default');
		}
		return true;
	}
	return false;
}

/**
 * Handle form submissions on the skins page.
 */
function fanspaysite_handle_skins_actions() {
	if (!current_user_can('edit_theme_options')) {
		return;
	}

	// Apply skin
	if (isset($_POST['fanspaysite_apply_skin']) && check_admin_referer('fanspaysite_skins_action', 'fanspaysite_skins_nonce')) {
		$skin_key = sanitize_key($_POST['skin_key']);
		if (fanspaysite_apply_skin($skin_key)) {
			add_settings_error('fanspaysite_skins', 'skin_applied', __('Skin applied successfully.', 'fanspaysite'), 'updated');
		} else {
			add_settings_error('fanspaysite_skins', 'skin_error', __('Skin not found.', 'fanspaysite'), 'error');
		}
	}

	// Save current as skin
	if (isset($_POST['fanspaysite_save_skin']) && check_admin_referer('fanspaysite_skins_action', 'fanspaysite_skins_nonce')) {
		$name        = sanitize_text_field($_POST['skin_name'] ?? '');
		$description = sanitize_textarea_field($_POST['skin_description'] ?? '');
		$skin_key    = sanitize_key($_POST['save_skin_key'] ?? '');

		if (empty($name)) {
			add_settings_error('fanspaysite_skins', 'skin_error', __('Skin name is required.', 'fanspaysite'), 'error');
		} else {
			if (empty($skin_key)) {
				$skin_key = sanitize_key(str_replace(' ', '-', strtolower($name)));
			}
			// Prevent overwriting built-in skins
			$builtin = fanspaysite_get_builtin_skins();
			if (isset($builtin[$skin_key])) {
				$skin_key = 'custom-' . $skin_key;
			}
			fanspaysite_save_skin($skin_key, $name, $description);
			add_settings_error('fanspaysite_skins', 'skin_saved', __('Skin saved successfully.', 'fanspaysite'), 'updated');
		}
	}

	// Delete skin
	if (isset($_POST['fanspaysite_delete_skin']) && check_admin_referer('fanspaysite_skins_action', 'fanspaysite_skins_nonce')) {
		$skin_key = sanitize_key($_POST['skin_key']);
		if (fanspaysite_delete_skin($skin_key)) {
			add_settings_error('fanspaysite_skins', 'skin_deleted', __('Skin deleted successfully.', 'fanspaysite'), 'updated');
		} else {
			add_settings_error('fanspaysite_skins', 'skin_error', __('Cannot delete this skin.', 'fanspaysite'), 'error');
		}
	}
}
add_action('admin_init', 'fanspaysite_handle_skins_actions');

/**
 * Output custom CSS from skin settings on the frontend.
 */
function fanspaysite_skin_custom_css() {
	$custom_css = get_theme_mod('fanspaysite_skin_custom_css', '');
	if (!empty($custom_css)) {
		echo '<style id="fanspaysite-skin-css">' . wp_strip_all_tags($custom_css) . '</style>';
	}
}
add_action('wp_head', 'fanspaysite_skin_custom_css', 20);

/**
 * Render the skins admin page.
 */
function fanspaysite_skins_page_html() {
	if (!current_user_can('edit_theme_options')) {
		return;
	}

	$skins       = fanspaysite_get_all_skins();
	$active_skin = get_option('fanspaysite_active_skin', 'default');

	settings_errors('fanspaysite_skins');
	?>
	<div class="wrap">
		<h1><?php esc_html_e('FansPaysite Skin Management', 'fanspaysite'); ?></h1>
		<p><?php esc_html_e('Skins control the layout, menu style, color scheme, and theme mode. Apply a skin to quickly switch between configurations, or save your current settings as a custom skin.', 'fanspaysite'); ?></p>

		<style>
			.fps-skins-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 20px; margin: 20px 0; }
			.fps-skin-card { background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 20px; position: relative; }
			.fps-skin-card.active { border-color: #2271b1; border-width: 2px; }
			.fps-skin-card h3 { margin: 0 0 8px; font-size: 16px; }
			.fps-skin-card .description { color: #646970; margin-bottom: 12px; }
			.fps-skin-card .skin-meta { font-size: 12px; color: #8c8f94; margin-bottom: 12px; }
			.fps-skin-card .skin-meta span { display: inline-block; margin-right: 12px; }
			.fps-skin-card .skin-colors { display: flex; gap: 4px; margin-bottom: 12px; }
			.fps-skin-color { width: 24px; height: 24px; border-radius: 3px; border: 1px solid #ddd; }
			.fps-skin-card .actions { display: flex; gap: 8px; }
			.fps-skin-badge { display: inline-block; background: #2271b1; color: #fff; font-size: 11px; padding: 2px 8px; border-radius: 3px; margin-left: 8px; }
			.fps-skin-badge.builtin { background: #8c8f94; }
			.fps-save-section { background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 20px; margin-top: 30px; max-width: 600px; }
			.fps-save-section h2 { margin-top: 0; }
			.fps-save-section label { display: block; margin-bottom: 4px; font-weight: 600; }
			.fps-save-section input[type="text"],
			.fps-save-section textarea { width: 100%; margin-bottom: 12px; }
			.fps-save-section textarea { height: 60px; }
			.fps-current-info { background: #f0f6fc; border: 1px solid #c3c4c7; border-radius: 4px; padding: 16px; margin: 20px 0; }
		</style>

		<div class="fps-current-info">
			<strong><?php esc_html_e('Current Settings:', 'fanspaysite'); ?></strong>
			<?php
			$current_layout       = get_theme_mod('fanspaysite_layout', 'left-sidebar');
			$current_burger       = get_theme_mod('fanspaysite_burger_menu', 'auto');
			$current_menu         = get_theme_mod('fanspaysite_menu_display_mode', 'auto');
			$current_submenu      = get_theme_mod('fanspaysite_submenu_display_mode', 'auto');
			$current_hover        = get_theme_mod('fanspaysite_submenu_hover', 'auto');
			$current_mode         = get_theme_mod('fanspaysite_default_theme_mode', 'light');
			?>
			<span><?php printf(__('Layout: %s', 'fanspaysite'), '<code>' . esc_html($current_layout) . '</code>'); ?></span> |
			<span><?php printf(__('Burger: %s', 'fanspaysite'), '<code>' . esc_html($current_burger) . '</code>'); ?></span> |
			<span><?php printf(__('Main Menu: %s', 'fanspaysite'), '<code>' . esc_html($current_menu) . '</code>'); ?></span> |
			<span><?php printf(__('Submenus: %s', 'fanspaysite'), '<code>' . esc_html($current_submenu) . '</code>'); ?></span> |
			<span><?php printf(__('Hover: %s', 'fanspaysite'), '<code>' . esc_html($current_hover) . '</code>'); ?></span> |
			<span><?php printf(__('Mode: %s', 'fanspaysite'), '<code>' . esc_html($current_mode) . '</code>'); ?></span> |
			<span><?php printf(__('Active Skin: %s', 'fanspaysite'), '<code>' . esc_html($active_skin) . '</code>'); ?></span>
		</div>

		<h2><?php esc_html_e('Available Skins', 'fanspaysite'); ?></h2>
		<div class="fps-skins-grid">
			<?php foreach ($skins as $key => $skin) : ?>
				<div class="fps-skin-card <?php echo ($key === $active_skin) ? 'active' : ''; ?>">
					<h3>
						<?php echo esc_html($skin['name']); ?>
						<?php if ($key === $active_skin) : ?>
							<span class="fps-skin-badge"><?php esc_html_e('Active', 'fanspaysite'); ?></span>
						<?php endif; ?>
						<?php if (!empty($skin['is_builtin'])) : ?>
							<span class="fps-skin-badge builtin"><?php esc_html_e('Built-in', 'fanspaysite'); ?></span>
						<?php endif; ?>
					</h3>
					<div class="description"><?php echo esc_html($skin['description'] ?? ''); ?></div>
					<div class="skin-meta">
						<span><?php printf(__('Layout: %s', 'fanspaysite'), esc_html($skin['layout'])); ?></span>
						<span><?php printf(__('Burger: %s', 'fanspaysite'), esc_html($skin['burger_menu'] ?? 'auto')); ?></span>
						<span><?php printf(__('Menu: %s', 'fanspaysite'), esc_html($skin['menu_display'])); ?></span>
						<span><?php printf(__('Submenus: %s', 'fanspaysite'), esc_html($skin['submenu_display'] ?? 'auto')); ?></span>
						<span><?php printf(__('Hover: %s', 'fanspaysite'), esc_html($skin['submenu_hover'] ?? 'auto')); ?></span>
						<span><?php printf(__('Mode: %s', 'fanspaysite'), esc_html($skin['default_mode'])); ?></span>
					</div>
					<?php if (!empty($skin['colors'])) : ?>
						<div class="skin-colors">
							<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['light_bg']); ?>;" title="Light BG"></div>
							<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['light_text']); ?>;" title="Light Text"></div>
							<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['light_link']); ?>;" title="Light Link"></div>
							<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['dark_bg']); ?>;" title="Dark BG"></div>
							<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['dark_text']); ?>;" title="Dark Text"></div>
							<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['dark_link']); ?>;" title="Dark Link"></div>
						</div>
					<?php endif; ?>
					<div class="actions">
						<?php if ($key !== $active_skin) : ?>
							<form method="post" style="display:inline;">
								<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
								<input type="hidden" name="skin_key" value="<?php echo esc_attr($key); ?>">
								<button type="submit" name="fanspaysite_apply_skin" class="button button-primary"><?php esc_html_e('Apply', 'fanspaysite'); ?></button>
							</form>
						<?php endif; ?>
						<?php if (empty($skin['is_builtin'])) : ?>
							<form method="post" style="display:inline;" onsubmit="return confirm('<?php esc_attr_e('Delete this skin?', 'fanspaysite'); ?>');">
								<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
								<input type="hidden" name="skin_key" value="<?php echo esc_attr($key); ?>">
								<button type="submit" name="fanspaysite_delete_skin" class="button button-link-delete"><?php esc_html_e('Delete', 'fanspaysite'); ?></button>
							</form>
						<?php endif; ?>
					</div>
				</div>
			<?php endforeach; ?>
		</div>

		<div class="fps-save-section">
			<h2><?php esc_html_e('Save Current Settings as Skin', 'fanspaysite'); ?></h2>
			<p><?php esc_html_e('Capture your current layout, menu mode, theme mode, and color settings as a reusable skin.', 'fanspaysite'); ?></p>
			<form method="post">
				<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
				<label for="skin_name"><?php esc_html_e('Skin Name', 'fanspaysite'); ?></label>
				<input type="text" id="skin_name" name="skin_name" required placeholder="<?php esc_attr_e('My Custom Skin', 'fanspaysite'); ?>">

				<label for="skin_description"><?php esc_html_e('Description', 'fanspaysite'); ?></label>
				<textarea id="skin_description" name="skin_description" placeholder="<?php esc_attr_e('Brief description of this skin configuration...', 'fanspaysite'); ?>"></textarea>

				<label for="save_skin_key"><?php esc_html_e('Skin Key (optional, auto-generated from name)', 'fanspaysite'); ?></label>
				<input type="text" id="save_skin_key" name="save_skin_key" placeholder="<?php esc_attr_e('my-custom-skin', 'fanspaysite'); ?>" pattern="[a-z0-9\-]*">

				<p class="description"><?php esc_html_e('Use an existing key to overwrite that skin. Leave empty to auto-generate.', 'fanspaysite'); ?></p>

				<button type="submit" name="fanspaysite_save_skin" class="button button-primary" style="margin-top:8px;"><?php esc_html_e('Save Current Settings as Skin', 'fanspaysite'); ?></button>
			</form>
		</div>
	</div>
	<?php
}
