<?php
/**
 * Announcement Bar Widget.
 *
 *
 * @package pawwell
 */

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'Pawwell_Announcement_Bar_Widget' ) ) :

class Pawwell_Announcement_Bar_Widget extends WP_Widget {

	/**
	 * Register widget with WordPress.
	 */
	public function __construct() {
		parent::__construct(
			'pawwell_announcement_bar_widget',
			esc_html__( 'Pawwell: Announcement Bar', 'pawwell' ),
			array(
				'description' => esc_html__( 'Add multiple announcements displayed in a centered bar with dot separators.', 'pawwell' ),
			)
		);
	}

	/**
	 * Available announcement icons.
	 *
	 * @return array
	 */
	public function get_icons() {
		return array(
			'none'        => '',
			'truck'       => '<path d="M3 7h11v9H3zM14 10h4l3 3v3h-7"/><circle cx="7" cy="18" r="1.8"/><circle cx="17.5" cy="18" r="1.8"/>',
			'stethoscope' => '<path d="M5 4v5a4 4 0 0 0 8 0V4"/><path d="M5 4H3M13 4h2"/><path d="M9 17v-3"/><path d="M9 17a5 5 0 0 0 9 0v-2"/><circle cx="18" cy="13" r="2"/>',
			'return'      => '<path d="M4 9a8 8 0 0 1 14-3l2 2"/><path d="M20 4v4h-4"/><path d="M20 15a8 8 0 0 1-14 3l-2-2"/><path d="M4 20v-4h4"/>',
			'shield'      => '<path d="M12 3 5 6v6c0 4 3 7 7 9 4-2 7-5 7-9V6l-7-3z"/><path d="m9 12 2 2 4-4"/>',
			'zap'         => '<path d="M13 2 4 14h7l-1 8 9-12h-7l1-8z"/>',
			'paw'         => '<circle cx="5.5" cy="11" r="2"/><circle cx="8" cy="6" r="2"/><circle cx="13" cy="5.5" r="2"/><circle cx="16.5" cy="9.5" r="2"/><path d="M8 15c-2 0-4 1.5-4 3.5C4 20.5 6 21 7.5 21h7c2 0 3.5-.8 3.5-2.8 0-2.2-2.2-3.2-4.5-3.2"/>',
			'gift'        => '<path d="M4 11h16v9H4zM4 8h16v3H4zM12 8v12"/><path d="M12 8C12 8 10 4 8 5s2 3 4 3zM12 8c0 0 2-4 4-3s-2 3-4 3z"/>',
			'heart'       => '<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>',
			'clock'       => '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
			'mail'        => '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
			'phone'       => '<path d="M5 4h4l2 5-3 2a12 12 0 0 0 5 5l2-3 5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2z"/>',
			'pin'         => '<path d="M12 21s7-6 7-11a7 7 0 0 0-14 0c0 5 7 11 7 11z"/><circle cx="12" cy="10" r="2.5"/>',
			'star'        => '<path d="M12 2.5l2.9 5.9 6.5.9-4.7 4.6 1.1 6.5L12 17.8 6.2 20.9l1.1-6.5L2.6 9.8l6.5-.9L12 2.5z"/>',
			'check'       => '<path d="M5 13l4 4L19 7"/>',
		);
	}

	/**
	 * Render an announcement icon SVG.
	 *
	 * @param string $key Icon key.
	 * @return string SVG markup, empty string if none.
	 */
	public function render_icon( $key ) {
		$icons = $this->get_icons();

		if ( empty( $key ) || 'none' === $key || ! isset( $icons[ $key ] ) || empty( $icons[ $key ] ) ) {
			return '';
		}

		$fill = 'star' === $key ? 'currentColor' : 'none';

		return '<svg class="pawwell-announcement-icon" width="15" height="15" viewBox="0 0 24 24" fill="' . esc_attr( $fill ) . '" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">' . $icons[ $key ] . '</svg>';
	}

	/**
	 * Front-end display of widget.
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {

		$announcements = ! empty( $instance['announcements'] ) ? $instance['announcements'] : array();
		$bar_bg_color  = ! empty( $instance['bar_bg_color'] ) ? sanitize_hex_color( $instance['bar_bg_color'] ) : '';
		$text_color    = ! empty( $instance['text_color'] ) ? sanitize_hex_color( $instance['text_color'] ) : '';

		// Filter out empty announcements.
		$announcements = array_filter( $announcements, function( $item ) {
			return ! empty( $item['text'] );
		});

		if ( empty( $announcements ) ) {
			return;
		}

		// Re-index array after filter.
		$announcements = array_values( $announcements );

		$bg_style   = $bar_bg_color ? 'background-color:' . esc_attr( $bar_bg_color ) . ';' : '';
		$text_style = $text_color ? 'color:' . esc_attr( $text_color ) . ';' : '';

		// Build the announcement items HTML once
		ob_start();
		foreach ( $announcements as $announcement ) :
			$icon_key = ! empty( $announcement['icon'] ) ? $announcement['icon'] : 'none';
			$icon_svg = $this->render_icon( $icon_key );
		?>
			<span class="pawwell-announcement-item">
				<?php echo $icon_svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe SVG built internally. ?>
				<span class="pawwell-announcement-text"><?php echo esc_html( $announcement['text'] ); ?></span>
			</span>
			<span class="pawwell-announcement-dot"></span>
		<?php
		endforeach;
		$items_html = ob_get_clean();

		// Repeat the item
		$repeat_count = 4;
		$group_html   = str_repeat( $items_html, $repeat_count );
		?>
		<div class="pawwell-announcement-bar-widget"<?php echo $bg_style ? ' style="' . esc_attr( $bg_style ) . '"' : ''; ?>>
			<div class="pawwell-announcement-wrap"<?php echo $text_style ? ' style="' . esc_attr( $text_style ) . '"' : ''; ?>>
				<div class="pawwell-announcement-content">
					<div class="pawwell-announcement-group">
						<?php echo $group_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built with escaping above. ?>
					</div>
					<div class="pawwell-announcement-group" aria-hidden="true">
						<?php echo $group_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- duplicated for seamless marquee loop. ?>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Back-end widget form.
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form( $instance ) {

		$announcements = ! empty( $instance['announcements'] ) ? $instance['announcements'] : array();
		$bar_bg_color  = ! empty( $instance['bar_bg_color'] ) ? $instance['bar_bg_color'] : '#1C1C1C';
		$text_color    = ! empty( $instance['text_color'] ) ? $instance['text_color'] : '#FBF9F6';

		// Ensure at least one empty announcement.
		if ( empty( $announcements ) ) {
			$announcements = array(
				array(
					'text' => '',
					'icon' => 'none',
				),
			);
		}

		$available_icons = $this->get_icons();

		?>
		<div class="pawwell-announcement-widget-form">
			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'bar_bg_color' ) ); ?>"><?php esc_html_e( 'Background Color:', 'pawwell' ); ?></label>
				<input type="color" id="<?php echo esc_attr( $this->get_field_id( 'bar_bg_color' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'bar_bg_color' ) ); ?>" value="<?php echo esc_attr( $bar_bg_color ); ?>" class="pawwell-announcement-color-picker">
			</p>
			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'text_color' ) ); ?>"><?php esc_html_e( 'Text Color:', 'pawwell' ); ?></label>
				<input type="color" id="<?php echo esc_attr( $this->get_field_id( 'text_color' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'text_color' ) ); ?>" value="<?php echo esc_attr( $text_color ); ?>" class="pawwell-announcement-color-picker">
			</p>

			<hr style="margin:15px 0;border-top:1px solid #ddd">
			<p><strong><?php esc_html_e( 'Announcements', 'pawwell' ); ?></strong></p>

			<div class="pawwell-announcement-items">
			<?php foreach ( $announcements as $i => $announcement ) :
				$current_icon = isset( $announcement['icon'] ) ? $announcement['icon'] : 'none';
			?>
				<div class="pawwell-announcement-item-field">
					<p>
						<label><?php esc_html_e( 'Icon:', 'pawwell' ); ?></label>
						<select name="<?php echo esc_attr( $this->get_field_name( 'announcements' ) ); ?>[<?php echo esc_attr( $i ); ?>][icon]" class="widefat pawwell-announcement-icon-select">
							<?php foreach ( $available_icons as $icon_key => $icon_path ) : ?>
								<option value="<?php echo esc_attr( $icon_key ); ?>" <?php selected( $current_icon, $icon_key ); ?>><?php echo esc_html( ucfirst( $icon_key ) ); ?></option>
							<?php endforeach; ?>
						</select>
					</p>
					<p>
						<label><?php esc_html_e( 'Text:', 'pawwell' ); ?></label>
						<input type="text" name="<?php echo esc_attr( $this->get_field_name( 'announcements' ) ); ?>[<?php echo esc_attr( $i ); ?>][text]" value="<?php echo esc_attr( isset( $announcement['text'] ) ? $announcement['text'] : '' ); ?>" class="widefat pawwell-announcement-text-input" placeholder="<?php esc_attr_e( 'e.g. Free shipping on orders over $200', 'pawwell' ); ?>">
					</p>
					<button type="button" class="button pawwell-announcement-remove-btn" style="margin-bottom:10px;color:#d63639;"><?php esc_html_e( '✕ Remove', 'pawwell' ); ?></button>
					<hr style="margin:10px 0;border-top:1px solid #eee">
				</div>
			<?php endforeach; ?>
			</div>

			<button type="button" class="button pawwell-announcement-add-btn"><?php esc_html_e( '+ Add Announcement', 'pawwell' ); ?></button>
		</div>
		<?php
	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 * @return array Updated safe values to be saved.
	 */
	public function update( $new_instance, $old_instance ) {

		$instance = array();

		$instance['bar_bg_color'] = ! empty( $new_instance['bar_bg_color'] ) ? sanitize_hex_color( $new_instance['bar_bg_color'] ) : '#1C1C1C';
		$instance['text_color']   = ! empty( $new_instance['text_color'] ) ? sanitize_hex_color( $new_instance['text_color'] ) : '#FBF9F6';

		$instance['announcements'] = array();

		if ( ! empty( $new_instance['announcements'] ) && is_array( $new_instance['announcements'] ) ) {
			$valid_icons = array_keys( $this->get_icons() );
			foreach ( $new_instance['announcements'] as $announcement ) {
				$text = isset( $announcement['text'] ) ? sanitize_text_field( $announcement['text'] ) : '';
				$icon = isset( $announcement['icon'] ) ? sanitize_key( $announcement['icon'] ) : 'none';

				if ( ! in_array( $icon, $valid_icons, true ) ) {
					$icon = 'none';
				}

				if ( ! empty( $text ) ) {
					$instance['announcements'][] = array(
						'text' => $text,
						'icon' => $icon,
					);
				}
			}
		}

		return $instance;
	}
}
endif;

if ( ! function_exists( 'pawwell_register_announcement_bar_widget' ) ) :
/**
 * Register the Announcement Bar widget.
 */
function pawwell_register_announcement_bar_widget() {
	register_widget( 'Pawwell_Announcement_Bar_Widget' );
}
endif;
add_action( 'widgets_init', 'pawwell_register_announcement_bar_widget' );

/**
 * Enqueue admin scripts for the Announcement Bar widget.
 */
if ( ! function_exists( 'pawwell_announcement_bar_widget_admin_scripts' ) ) :
function pawwell_announcement_bar_widget_admin_scripts( $hook ) {
	if ( 'widgets.php' !== $hook ) {
		return;
	}

	wp_enqueue_script(
		'pawwell-widget-admin',
		get_template_directory_uri() . '/assets/js/admin/widgets.js',
		array( 'jquery' ),
		wp_get_theme()->get( 'Version' ),
		true
	);


}
endif;
add_action( 'admin_enqueue_scripts', 'pawwell_announcement_bar_widget_admin_scripts' );
