<?php
/**
 * Widget areas and the reusable newsletter widget.
 *
 * @package Gustavo_Portfolio
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Register sidebars used by blog and footer templates.
 *
 * @return void
 */
function gustavoo_portfolio_register_sidebars() {
	$shared = array(
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h2 class="widget__title">',
		'after_title'   => '</h2>',
	);

	register_sidebar(
		array_merge(
			$shared,
			array(
				'name'        => __( 'Barra lateral do blog', 'gustavoo-portfolio' ),
				'id'          => 'sidebar-blog',
				'description' => __( 'Widgets exibidos ao lado de posts, arquivos e buscas.', 'gustavoo-portfolio' ),
			)
		)
	);

	register_sidebar(
		array_merge(
			$shared,
			array(
				'name'        => __( 'Rodapé — coluna 1', 'gustavoo-portfolio' ),
				'id'          => 'footer-1',
				'description' => __( 'Primeira coluna de widgets do rodapé.', 'gustavoo-portfolio' ),
			)
		)
	);

	register_sidebar(
		array_merge(
			$shared,
			array(
				'name'        => __( 'Rodapé — coluna 2', 'gustavoo-portfolio' ),
				'id'          => 'footer-2',
				'description' => __( 'Segunda coluna de widgets do rodapé.', 'gustavoo-portfolio' ),
			)
		)
	);
}
add_action( 'widgets_init', 'gustavoo_portfolio_register_sidebars' );

/**
 * Newsletter widget backed by the same safe Fluent Forms renderer as the CTA.
 */
class Gustavao_Portfolio_Newsletter_Widget extends WP_Widget {
	/**
	 * Register the widget with WordPress.
	 */
	public function __construct() {
		parent::__construct(
			'gustavoo_portfolio_newsletter',
			__( 'Gustavo — Newsletter', 'gustavoo-portfolio' ),
			array(
				'classname'                   => 'widget_newsletter',
				'description'                 => __( 'Exibe a chamada de newsletter integrada ao Fluent Forms e FluentCRM.', 'gustavoo-portfolio' ),
				'customize_selective_refresh' => true,
			)
		);
	}

	/**
	 * Render widget front end.
	 *
	 * @param array<string, string> $args     Sidebar wrappers.
	 * @param array<string, mixed>  $instance Saved instance.
	 * @return void
	 */
	public function widget( $args, $instance ) {
		$title   = ! empty( $instance['title'] ) ? $instance['title'] : gustavoo_portfolio_get_setting( 'newsletter_heading' );
		$text    = ! empty( $instance['text'] ) ? $instance['text'] : gustavoo_portfolio_get_setting( 'newsletter_text' );
		$form_id = ! empty( $instance['form_id'] ) ? absint( $instance['form_id'] ) : absint( gustavoo_portfolio_get_setting( 'newsletter_form_id' ) );

		echo $args['before_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Registered sidebar wrapper.

		if ( $title ) {
			echo $args['before_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Registered sidebar wrapper.
			echo esc_html( $title );
			echo $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Registered sidebar wrapper.
		}

		if ( $text ) {
			printf( '<p class="widget_newsletter__text">%s</p>', esc_html( $text ) );
		}

		gustavoo_portfolio_the_fluent_form( $form_id, 'newsletter' );

		echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Registered sidebar wrapper.
	}

	/**
	 * Render widget controls.
	 *
	 * @param array<string, mixed> $instance Saved instance.
	 * @return void
	 */
	public function form( $instance ) {
		$title   = isset( $instance['title'] ) ? (string) $instance['title'] : '';
		$text    = isset( $instance['text'] ) ? (string) $instance['text'] : '';
		$form_id = isset( $instance['form_id'] ) ? absint( $instance['form_id'] ) : 0;
		?>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Título:', 'gustavoo-portfolio' ); ?></label>
			<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
		</p>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'text' ) ); ?>"><?php esc_html_e( 'Texto:', 'gustavoo-portfolio' ); ?></label>
			<textarea class="widefat" rows="4" id="<?php echo esc_attr( $this->get_field_id( 'text' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'text' ) ); ?>"><?php echo esc_textarea( $text ); ?></textarea>
		</p>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'form_id' ) ); ?>"><?php esc_html_e( 'ID do Fluent Forms (vazio usa o global):', 'gustavoo-portfolio' ); ?></label>
			<input class="tiny-text" id="<?php echo esc_attr( $this->get_field_id( 'form_id' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'form_id' ) ); ?>" type="number" min="0" step="1" value="<?php echo esc_attr( $form_id ); ?>">
		</p>
		<?php
	}

	/**
	 * Sanitize widget settings.
	 *
	 * @param array<string, mixed> $new_instance New values.
	 * @param array<string, mixed> $old_instance Previous values.
	 * @return array<string, mixed>
	 */
	public function update( $new_instance, $old_instance ) {
		unset( $old_instance );

		return array(
			'title'   => isset( $new_instance['title'] ) ? sanitize_text_field( $new_instance['title'] ) : '',
			'text'    => isset( $new_instance['text'] ) ? sanitize_textarea_field( $new_instance['text'] ) : '',
			'form_id' => isset( $new_instance['form_id'] ) ? absint( $new_instance['form_id'] ) : 0,
		);
	}
}

/**
 * Register the newsletter widget after core has loaded WP_Widget.
 *
 * @return void
 */
function gustavoo_portfolio_register_widgets() {
	register_widget( 'Gustavao_Portfolio_Newsletter_Widget' );
}
add_action( 'widgets_init', 'gustavoo_portfolio_register_widgets' );

/**
 * Add one newsletter widget to the blog sidebar on first theme activation.
 *
 * Existing widget arrangements are preserved and the operation is idempotent.
 *
 * @return void
 */
function gustavoo_portfolio_seed_newsletter_widget() {
	$widget_id_base = 'gustavoo_portfolio_newsletter';
	$instances      = get_option( 'widget_' . $widget_id_base, array() );
	$instances      = is_array( $instances ) ? $instances : array();
	$sidebars       = wp_get_sidebars_widgets();
	$sidebars       = is_array( $sidebars ) ? $sidebars : array();

	foreach ( $sidebars as $widgets ) {
		foreach ( (array) $widgets as $widget_id ) {
			if ( str_starts_with( (string) $widget_id, $widget_id_base . '-' ) ) {
				return;
			}
		}
	}

	$indexes = array_filter( array_keys( $instances ), 'is_int' );
	$index   = $indexes ? max( $indexes ) + 1 : 1;

	$instances[ $index ] = array(
		'title'   => __( 'Newsletter', 'gustavoo-portfolio' ),
		'text'    => __( 'Receba novos artigos sobre desenvolvimento, infraestrutura e automação.', 'gustavoo-portfolio' ),
		'form_id' => 0,
	);
	$instances['_multiwidget'] = 1;

	$sidebars['sidebar-blog'] = array_values(
		array_merge(
			array( $widget_id_base . '-' . $index ),
			isset( $sidebars['sidebar-blog'] ) ? (array) $sidebars['sidebar-blog'] : array()
		)
	);

	update_option( 'widget_' . $widget_id_base, $instances, false );
	update_option( 'sidebars_widgets', $sidebars, false );
}
add_action( 'after_switch_theme', 'gustavoo_portfolio_seed_newsletter_widget' );
