<?php
/**
 * Plugin Name:       BW Favicon
 * Plugin URI:        https://bowdenworks.com
 * Description:       Overrides theme favicons by injecting a custom PNG favicon into the head with high priority.
 * Version:           1.0.0
 * Author:            Adi Pramono
 * Author URI:        https://bowdenworks.com
 * License:           GPL v2 or later
 */

// Prevent direct access to the file
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * 1. Add Submenu under Settings (Dashboard -> Settings -> BW Favicon)
 */
function bw_favicon_add_admin_menu() {
	add_options_page(
		'BW Favicon Settings', // Page Title
		'BW Favicon',          // Menu Title
		'manage_options',      // Capability
		'bw-favicon',          // Menu Slug
		'bw_favicon_options_page_html' // Callback to render page
	);
}
add_action( 'admin_menu', 'bw_favicon_add_admin_menu' );

/**
 * 2. Register Settings
 */
function bw_favicon_settings_init() {
	register_setting( 'bw_favicon_group', 'bw_favicon_url' );

	add_settings_section(
		'bw_favicon_section',
		'Favicon Configuration',
		'bw_favicon_section_callback',
		'bw-favicon'
	);

	add_settings_field(
		'bw_favicon_url',
		'Favicon Image',
		'bw_favicon_field_callback',
		'bw-favicon',
		'bw_favicon_section'
	);
}
add_action( 'admin_init', 'bw_favicon_settings_init' );

/**
 * 3. Settings Callbacks & HTML
 */
function bw_favicon_section_callback() {
	echo '<p>Upload your PNG favicon here. This will force the favicon to load on the frontend, overriding themes like Kadence.</p>';
}

function bw_favicon_field_callback() {
	// Get the current value
	$url = get_option( 'bw_favicon_url' );
	?>
	<div style="display:flex; align-items:center; gap: 10px;">
		<input type="text" 
			   id="bw_favicon_url" 
			   name="bw_favicon_url" 
			   value="<?php echo esc_attr( $url ); ?>" 
			   class="regular-text" 
			   placeholder="https://..." />
		
		<input type="button" 
			   id="bw_favicon_upload_btn" 
			   class="button-secondary" 
			   value="Upload / Select Image" />
	</div>

	<div id="bw_favicon_preview" style="margin-top: 20px;">
		<?php if ( $url ) : ?>
			<p><strong>Preview:</strong></p>
			<img src="<?php echo esc_url( $url ); ?>" style="max-width: 64px; border: 1px solid #ccc; padding: 5px;" />
		<?php endif; ?>
	</div>

	<script type="text/javascript">
		jQuery(document).ready(function($){
			$('#bw_favicon_upload_btn').click(function(e) {
				e.preventDefault();
				var image = wp.media({ 
					title: 'Upload Favicon',
					multiple: false
				}).open()
				.on('select', function(e){
					var uploaded_image = image.state().get('selection').first();
					var image_url = uploaded_image.toJSON().url;
					$('#bw_favicon_url').val(image_url);
					$('#bw_favicon_preview').html('<p><strong>Preview:</strong></p><img src="' + image_url + '" style="max-width: 64px; border: 1px solid #ccc; padding: 5px;" />');
				});
			});
		});
	</script>
	<?php
}

function bw_favicon_options_page_html() {
	// Check user capabilities
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	?>
	<div class="wrap">
		<h1>BW Favicon Settings</h1>
		<form action="options.php" method="post">
			<?php
			settings_fields( 'bw_favicon_group' );
			do_settings_sections( 'bw-favicon' );
			submit_button( 'Save Favicon' );
			?>
		</form>
	</div>
	<?php
}

/**
 * 4. Enqueue Media Scripts in Admin
 * Required for the upload button to work.
 */
function bw_favicon_admin_scripts( $hook ) {
	if ( 'settings_page_bw-favicon' !== $hook ) {
		return;
	}
	wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'bw_favicon_admin_scripts' );

/**
 * 5. Output Favicon on Frontend
 * Using Priority 9999 to run last and override theme defaults.
 */
function bw_favicon_output_head() {
	$favicon_url = get_option( 'bw_favicon_url' );

	if ( ! empty( $favicon_url ) ) {
		// Output the link tags
		echo "\n\n";
		echo '<link rel="icon" href="' . esc_url( $favicon_url ) . '" type="image/png" />' . "\n";
		echo '<link rel="shortcut icon" href="' . esc_url( $favicon_url ) . '" type="image/png" />' . "\n";
		echo '<link rel="apple-touch-icon" href="' . esc_url( $favicon_url ) . '" />' . "\n";
		echo "\n";
	}
}
// Hook into frontend head
add_action( 'wp_head', 'bw_favicon_output_head', 9999 );
// Hook into login screen head
add_action( 'login_head', 'bw_favicon_output_head', 9999 );
// Hook into admin dashboard head
add_action( 'admin_head', 'bw_favicon_output_head', 9999 );