<?php
/**
 * Announcement Bar / Top Bar Widget.
 *
 * Renders the site top bar with a left column of info items (icon + text),
 * a right column of utility links, and trailing social icons.
 *
 * @package shopbar
 */

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'Shopbar_Announcement_Bar_Widget' ) ) :

class Shopbar_Announcement_Bar_Widget extends WP_Widget {

	/**
	 * Social platforms allowed in the widget.
	 *
	 * @var array
	 */
	private $social_platforms = array(
		'facebook'  => 'Facebook',
		'instagram' => 'Instagram',
		'youtube'   => 'YouTube',
		'twitter'   => 'X (Twitter)',
		'pinterest' => 'Pinterest',
	);

	/**
	 * Register widget with WordPress.
	 */
	public function __construct() {
		parent::__construct(
			'shopbar_announcement_bar_widget',
			esc_html__( 'Shopbar: Announcement Bar', 'shopbar' ),
			array(
				'description' => esc_html__( 'Top bar with left info items (icon + text), right utility links and social icons.', 'shopbar' ),
			)
		);
	}

	/**
	 * Icons available for the left info items.
	 *
	 * @return array
	 */
	private function info_icon_options() {
		return array(
			''            => esc_html__( '— No icon —', 'shopbar' ),
			'truck'       => esc_html__( 'Truck (Shipping)', 'shopbar' ),
			'rotate'      => esc_html__( 'Rotate (Returns)', 'shopbar' ),
			'lock'        => esc_html__( 'Lock (Secure)', 'shopbar' ),
			'shield'      => esc_html__( 'Shield', 'shopbar' ),
			'credit-card' => esc_html__( 'Credit Card', 'shopbar' ),
			'headphones'  => esc_html__( 'Headphones (Support)', 'shopbar' ),
			'mail'        => esc_html__( 'Mail', 'shopbar' ),
			'clock'       => esc_html__( 'Clock', 'shopbar' ),
			'calendar'    => esc_html__( 'Calendar', 'shopbar' ),
			'send'        => esc_html__( 'Send', 'shopbar' ),
			'zap'         => esc_html__( 'Zap (Deals)', 'shopbar' ),
			'heart'       => esc_html__( 'Heart', 'shopbar' ),
			'user'        => esc_html__( 'User', 'shopbar' ),
			'cart'        => esc_html__( 'Cart', 'shopbar' ),
			'bag'         => esc_html__( 'Bag', 'shopbar' ),
			'search'      => esc_html__( 'Search', 'shopbar' ),
			'arrow-right' => esc_html__( 'Arrow Right', 'shopbar' ),
		);
	}

	/**
	 * Default widget instance
	 *
	 * @return array
	 */
	private function defaults() {
		$account_url = '#';
		if ( shopbar_is_active_woocommerce() ) {
			$account_id = get_option( 'woocommerce_myaccount_page_id' );
			if ( $account_id ) {
				$account_url = get_permalink( $account_id );
			}
		}

		return array(
			'bar_bg_color' => '#1C1C1C',
			'text_color'   => '#FFFFFF',
			'info'         => array(
				array( 'icon' => 'truck',  'text' => __( 'Free Shipping on Orders Over $49', 'shopbar' ) ),
				array( 'icon' => 'rotate', 'text' => __( '30-Day Returns', 'shopbar' ) ),
				array( 'icon' => 'lock',   'text' => __( 'Secure Payment', 'shopbar' ) ),
			),
			'links'        => array(
				array( 'text' => __( 'Track Order', 'shopbar' ), 'url' => $account_url ),
				array( 'text' => __( 'Help Center', 'shopbar' ), 'url' => $account_url ),
			),
			'social'       => array(
				array( 'platform' => 'facebook',  'url' => '#' ),
				array( 'platform' => 'instagram', 'url' => '#' ),
				array( 'platform' => 'twitter',   'url' => '#' ),
				array( 'platform' => 'pinterest', 'url' => '#' ),
			),
		);
	}

	/**
	 * Empty item shape per group.
	 *
	 * @param string $group Group key (info|links|social).
	 * @return array
	 */
	private function empty_item( $group ) {
		switch ( $group ) {
			case 'info':
				return array( 'icon' => '', 'text' => '' );
			case 'links':
				return array( 'text' => '', 'url' => '' );
			case 'social':
				return array( 'platform' => '', 'url' => '' );
			default:
				return array();
		}
	}

	/**
	 * Merge a raw saved instance with sane behaviour.
	 *
	 * Brand-new widgets (nothing saved yet) fall back to defaults; configured
	 * widgets respect explicit empty arrays so the user can clear a column.
	 *
	 * @param array $instance Raw instance.
	 * @return array
	 */
	private function merge_instance( $instance ) {
		$defaults = $this->defaults();

		$configured = isset( $instance['info'] ) || isset( $instance['links'] ) || isset( $instance['social'] ) || isset( $instance['bar_bg_color'] );

		if ( ! $configured ) {
			return $defaults;
		}

		return array(
			'bar_bg_color' => ! empty( $instance['bar_bg_color'] ) ? sanitize_hex_color( $instance['bar_bg_color'] ) : $defaults['bar_bg_color'],
			'text_color'   => ! empty( $instance['text_color'] ) ? sanitize_hex_color( $instance['text_color'] ) : $defaults['text_color'],
			'info'         => isset( $instance['info'] ) && is_array( $instance['info'] ) ? $instance['info'] : array(),
			'links'        => isset( $instance['links'] ) && is_array( $instance['links'] ) ? $instance['links'] : array(),
			'social'       => isset( $instance['social'] ) && is_array( $instance['social'] ) ? $instance['social'] : array(),
		);
	}

	/**
	 * Sanitise and filter items for front-end output.
	 *
	 * @param array  $items Raw items.
	 * @param string $group Group key.
	 * @return array
	 */
	private function clean_items( $items, $group ) {
		$out = array();
		if ( ! is_array( $items ) ) {
			return $out;
		}

		foreach ( $items as $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}
			$item = wp_parse_args( $item, $this->empty_item( $group ) );

			if ( 'info' === $group ) {
				$icon = sanitize_key( $item['icon'] );
				$text = sanitize_text_field( $item['text'] );
				if ( '' === $text && '' === $icon ) {
					continue;
				}
				$out[] = array(
					'icon' => $icon,
					'text' => $text,
				);
			} elseif ( 'links' === $group ) {
				$text = sanitize_text_field( $item['text'] );
				if ( '' === $text ) {
					continue;
				}
				$out[] = array(
					'text' => $text,
					'url'  => '' === trim( $item['url'] ) ? '#' : esc_url_raw( $item['url'] ),
				);
			} elseif ( 'social' === $group ) {
				$platform = sanitize_key( $item['platform'] );
				if ( ! isset( $this->social_platforms[ $platform ] ) ) {
					continue;
				}
				$out[] = array(
					'platform' => $platform,
					'url'      => '' === trim( $item['url'] ) ? '#' : esc_url_raw( $item['url'] ),
				);
			}
		}

		return $out;
	}

	/**
	 * Front-end display of widget.
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		$data   = $this->merge_instance( $instance );
		$info   = $this->clean_items( $data['info'], 'info' );
		$links  = $this->clean_items( $data['links'], 'links' );
		$social = $this->clean_items( $data['social'], 'social' );

		if ( empty( $info ) && empty( $links ) && empty( $social ) ) {
			return;
		}

		$bg_style   = $data['bar_bg_color'] ? 'background-color:' . $data['bar_bg_color'] . ';' : '';
		$text_style = $data['text_color']   ? 'color:' . $data['text_color'] . ';' : '';

		echo $args['before_widget'];
		?>
		<div class="sb-topbar"<?php echo $bg_style ? ' style="' . esc_attr( $bg_style ) . '"' : ''; ?>>
			<div class="sb-topbar-inner"<?php echo $text_style ? ' style="' . esc_attr( $text_style ) . '"' : ''; ?>>

				<?php if ( ! empty( $info ) ) : ?>
					<div class="sb-topbar-left">
						<?php foreach ( $info as $item ) :
							$svg = $item['icon'] ? shopbar_get_icon( $item['icon'], 14 ) : '';
							?>
							<span class="sb-topbar-item">
								<?php if ( $svg ) : ?>
									<?php echo $svg; ?>
								<?php endif; ?>
								<?php if ( '' !== $item['text'] ) : ?>
									<span><?php echo esc_html( $item['text'] ); ?></span>
								<?php endif; ?>
							</span>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>

				<?php if ( ! empty( $links ) || ! empty( $social ) ) : ?>
					<div class="sb-topbar-right">
						<?php foreach ( $links as $link ) : ?>
							<a href="<?php echo esc_url( $link['url'] ); ?>" class="sb-topbar-link"><?php echo esc_html( $link['text'] ); ?></a>
						<?php endforeach; ?>

						<?php if ( ! empty( $social ) ) : ?>
							<div class="sb-topbar-social">
								<?php foreach ( $social as $s ) : ?>
									<a href="<?php echo esc_url( $s['url'] ); ?>" class="sb-social-icon" aria-label="<?php echo esc_attr( $this->social_platforms[ $s['platform'] ] ); ?>" target="_blank" rel="noopener noreferrer">
										<?php echo shopbar_get_icon( $s['platform'], 14 ); ?>
									</a>
								<?php endforeach; ?>
							</div>
						<?php endif; ?>
					</div>
				<?php endif; ?>

			</div>
		</div>
		<?php
		echo $args['after_widget'];
	}

	/**
	 * Render a single repeater field row.
	 *
	 * @param string $group   Group key.
	 * @param int    $i       Item index.
	 * @param array  $item    Item values.
	 * @param array  $fields  Field definitions.
	 */
	private function render_item_row( $group, $i, $item, $fields ) {
		$base = $this->get_field_name( $group );
		?>
		<div class="shopbar-repeater-item" style="border:1px solid #eee;padding:10px;margin-bottom:10px;border-radius:4px;">
			<?php foreach ( $fields as $fkey => $fdata ) :
				$val  = isset( $item[ $fkey ] ) ? $item[ $fkey ] : ( isset( $fdata['default'] ) ? $fdata['default'] : '' );
				$name = $base . '[' . $i . '][' . $fkey . ']';
				$id   = $this->get_field_id( $group . '_' . $fkey . '_' . $i );
				?>
				<p style="margin:4px 0;">
					<label for="<?php echo esc_attr( $id ); ?>"><?php echo esc_html( $fdata['label'] ); ?></label><br>
					<?php if ( 'select' === $fdata['type'] ) : ?>
						<select id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $name ); ?>" class="widefat">
							<?php foreach ( $fdata['options'] as $opt_val => $opt_label ) : ?>
								<option value="<?php echo esc_attr( $opt_val ); ?>" <?php selected( $opt_val, $val ); ?>><?php echo esc_html( $opt_label ); ?></option>
							<?php endforeach; ?>
						</select>
					<?php else : ?>
						<input type="<?php echo esc_attr( $fdata['type'] ); ?>" id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $val ); ?>" class="widefat" placeholder="<?php echo esc_attr( isset( $fdata['placeholder'] ) ? $fdata['placeholder'] : '' ); ?>">
					<?php endif; ?>
				</p>
			<?php endforeach; ?>
			<button type="button" class="button shopbar-repeater-remove" style="color:#d63639;"><?php esc_html_e( 'Remove', 'shopbar' ); ?></button>
		</div>
		<?php
	}

	/**
	 * Render a full repeater group.
	 *
	 * @param string $group     Group key.
	 * @param array  $items     Saved items.
	 * @param array  $fields    Field definitions.
	 * @param string $add_label Add button label.
	 */
	private function render_repeater( $group, $items, $fields, $add_label ) {
		if ( ! is_array( $items ) || empty( $items ) ) {
			$items = array( $this->empty_item( $group ) );
		}
		?>
		<div class="shopbar-repeater" data-repeater="<?php echo esc_attr( $group ); ?>">
			<div class="shopbar-repeater-items">
				<?php foreach ( $items as $i => $item ) :
					$item = is_array( $item ) ? $item : $this->empty_item( $group );
					$this->render_item_row( $group, $i, $item, $fields );
				endforeach; ?>
			</div>
			<p>
				<button type="button" class="button shopbar-repeater-add" data-repeater="<?php echo esc_attr( $group ); ?>"><?php echo esc_html( $add_label ); ?></button>
			</p>
		</div>
		<?php
	}

	/**
	 * Back-end widget form.
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form( $instance ) {
		$data = $this->merge_instance( $instance );

		$bar_bg_color = $data['bar_bg_color'];
		$text_color   = $data['text_color'];
		$info         = is_array( $data['info'] ) ? $data['info'] : array();
		$links        = is_array( $data['links'] ) ? $data['links'] : array();
		$social       = is_array( $data['social'] ) ? $data['social'] : array();

		$info_fields = array(
			'icon' => array(
				'type'    => 'select',
				'label'   => __( 'Icon', 'shopbar' ),
				'options' => $this->info_icon_options(),
			),
			'text' => array(
				'type'        => 'text',
				'label'       => __( 'Text', 'shopbar' ),
				'placeholder' => __( 'e.g. Free shipping on orders over $49', 'shopbar' ),
			),
		);

		$link_fields = array(
			'text' => array(
				'type'        => 'text',
				'label'       => __( 'Link Text', 'shopbar' ),
				'placeholder' => __( 'e.g. Track Order', 'shopbar' ),
			),
			'url'  => array(
				'type'        => 'url',
				'label'       => __( 'Link URL', 'shopbar' ),
				'placeholder' => 'https://',
			),
		);

		$social_fields = array(
			'platform' => array(
				'type'    => 'select',
				'label'   => __( 'Platform', 'shopbar' ),
				'options' => array_merge( array( '' => __( '— Select —', 'shopbar' ) ), $this->social_platforms ),
			),
			'url'      => array(
				'type'        => 'url',
				'label'       => __( 'Profile URL', 'shopbar' ),
				'placeholder' => 'https://',
			),
		);
		?>
		<div class="shopbar-announcement-widget-form">

			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'bar_bg_color' ) ); ?>"><?php esc_html_e( 'Background Color:', 'shopbar' ); ?></label><br>
				<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="shopbar-announcement-color-picker">
			</p>
			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( 'text_color' ) ); ?>"><?php esc_html_e( 'Text Color:', 'shopbar' ); ?></label><br>
				<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="shopbar-announcement-color-picker">
			</p>

			<hr style="margin:15px 0;border-top:1px solid #ddd">
			<p><strong><?php esc_html_e( 'Left — Info Items', 'shopbar' ); ?></strong></p>
			<?php $this->render_repeater( 'info', $info, $info_fields, __( '+ Add Info Item', 'shopbar' ) ); ?>

			<hr style="margin:15px 0;border-top:1px solid #ddd">
			<p><strong><?php esc_html_e( 'Right — Links', 'shopbar' ); ?></strong></p>
			<?php $this->render_repeater( 'links', $links, $link_fields, __( '+ Add Link', 'shopbar' ) ); ?>

			<hr style="margin:15px 0;border-top:1px solid #ddd">
			<p><strong><?php esc_html_e( 'Right — Social Icons', 'shopbar' ); ?></strong></p>
			<?php $this->render_repeater( 'social', $social, $social_fields, __( '+ Add Social Icon', 'shopbar' ) ); ?>

		</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 save.
	 */
	public function update( $new_instance, $old_instance ) {
		$defaults = $this->defaults();

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

		$instance['info']   = $this->clean_items( isset( $new_instance['info'] ) ? $new_instance['info'] : array(), 'info' );
		$instance['links']  = $this->clean_items( isset( $new_instance['links'] ) ? $new_instance['links'] : array(), 'links' );
		$instance['social'] = $this->clean_items( isset( $new_instance['social'] ) ? $new_instance['social'] : array(), 'social' );

		return $instance;
	}
}
endif;

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

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

	wp_enqueue_script(
		'shopbar-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', 'shopbar_announcement_bar_widget_admin_scripts' );
