<?php
/**
 * RSM Buttons SiteOrigin widget.
 *
 * SiteOrigin requires widget id, folder name, and PHP basename to match
 * (id "buttons", path widgets/buttons/buttons.php).
 *
 * @package Rsmspark_Content_Widgets
 */

/*
Widget Name: RSM Button
Description: Insert a saved reusable button or build a custom inline button.
Author: RSMSpark
Author URI: https://rsmspark.com/
*/

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'SiteOrigin_Widget', false ) ) {
	return;
}

/**
 * Rsmspark_Content_Widgets_Buttons_Widget
 */
class Rsmspark_Content_Widgets_Buttons_Widget extends SiteOrigin_Widget {

	/**
	 * Constructor.
	 */
	public function __construct() {
		parent::__construct(
			'buttons',
			__( 'RSM Button', 'rsm-content-widgets' ),
			array(
				'description' => __( 'Choose a saved button from your library or configure a custom button inline.', 'rsm-content-widgets' ),
				'panels_icon' => 'dashicons dashicons-button',
				'has_preview' => true,
				'keywords'    => array( 'button', 'cta', 'link', 'RSM' ),
			),
			array(),
			array(),
			plugin_dir_path( __FILE__ )
		);
	}

	/**
	 * @param array<string, mixed> $instance Widget instance.
	 * @return array<string, mixed>
	 */
	public function modify_instance( $instance ) {
		$instance = parent::modify_instance( $instance );

		$defaults = array(
			'source_mode'    => 'saved',
			'saved_button'   => '',
			'text_line_1'    => __( 'Click Here', 'rsm-content-widgets' ),
			'shape'          => 'rounded',
			'size'           => 'medium',
			'bg_color'       => '#2563eb',
			'bg_hover_color' => '#1d4ed8',
			'text_color'     => '#ffffff',
		);

		$instance = wp_parse_args( is_array( $instance ) ? $instance : array(), $defaults );

		if ( empty( $instance['saved_button'] ) ) {
			foreach ( array( 'button_id', 'rsmspark_button_id', 'selected_button' ) as $legacy_key ) {
				if ( ! empty( $instance[ $legacy_key ] ) ) {
					$instance['saved_button'] = (string) $instance[ $legacy_key ];
					break;
				}
			}
		}

		if ( empty( $instance['saved_button'] ) && ! empty( $instance['saved']['saved_button'] ) ) {
			$instance['saved_button'] = (string) $instance['saved']['saved_button'];
		}

		if ( ! empty( $instance['saved_button'] ) ) {
			$button_post = get_post( absint( $instance['saved_button'] ) );
			if ( $button_post && '' !== trim( (string) $button_post->post_title ) ) {
				if ( ! isset( $instance['panels_info'] ) || ! is_array( $instance['panels_info'] ) ) {
					$instance['panels_info'] = array();
				}
				$instance['panels_info']['label'] = $button_post->post_title;
			}
		}

		return $instance;
	}

	/**
	 * Row label in the Page Builder widget list.
	 *
	 * @param array<string, mixed> $instance Widget instance.
	 * @return string
	 */
	public function get_instance_title( $instance ) {
		$instance = $this->modify_instance( is_array( $instance ) ? $instance : array() );

		if ( ! empty( $instance['saved_button'] ) ) {
			$button_post = get_post( absint( $instance['saved_button'] ) );
			if ( $button_post && '' !== trim( (string) $button_post->post_title ) ) {
				return (string) $button_post->post_title;
			}
		}

		if ( 'custom' === ( $instance['source_mode'] ?? '' ) && ! empty( $instance['text_line_1'] ) ) {
			return (string) $instance['text_line_1'];
		}

		return __( 'RSM Button', 'rsm-content-widgets' );
	}

	/**
	 * @return array<string, mixed>
	 */
	public function get_widget_form() {
		$button_options = array( '' => __( '— Select a saved button —', 'rsm-content-widgets' ) );

		if ( class_exists( 'Rsmspark_Buttons', false ) ) {
			$button_options = Rsmspark_Buttons::get_saved_buttons_options();
		}

		return Rsmspark_Content_Widgets_SiteOrigin::prepend_import_export_form(
			'buttons',
			array(
			'saved_button' => array(
				'type'    => 'select',
				'label'   => __( 'Saved button', 'rsm-content-widgets' ),
				'default' => '',
				'options' => $button_options,
				'description' => __( 'For popup triggers, set the link URL on the saved button itself (for example: #rp-popup-123).', 'rsm-content-widgets' ),
			),
			'source_mode' => array(
				'type'    => 'radio',
				'label'   => __( 'Button source', 'rsm-content-widgets' ),
				'default' => 'saved',
				'options' => array(
					'saved'  => __( 'Saved button', 'rsm-content-widgets' ),
					'custom' => __( 'Custom / inline', 'rsm-content-widgets' ),
				),
			),
			'text_line_1' => array(
				'type'    => 'text',
				'label'   => __( 'Text line 1 (custom mode)', 'rsm-content-widgets' ),
				'default' => __( 'Click Here', 'rsm-content-widgets' ),
			),
			'text_line_2' => array(
				'type'  => 'text',
				'label' => __( 'Text line 2 (custom mode)', 'rsm-content-widgets' ),
			),
			'link_url' => array(
				'type'  => 'link',
				'label' => __( 'Link (custom mode)', 'rsm-content-widgets' ),
				'description' => __( 'Applies to Custom/inline mode. Saved-button mode should use the URL stored on the selected button.', 'rsm-content-widgets' ),
			),
			'shape' => array(
				'type'    => 'select',
				'label'   => __( 'Shape (custom mode)', 'rsm-content-widgets' ),
				'default' => 'rounded',
				'options' => array(
					'rectangle' => __( 'Rectangle', 'rsm-content-widgets' ),
					'rounded'   => __( 'Rounded', 'rsm-content-widgets' ),
					'pill'      => __( 'Pill', 'rsm-content-widgets' ),
				),
			),
			'size' => array(
				'type'    => 'select',
				'label'   => __( 'Size (custom mode)', 'rsm-content-widgets' ),
				'default' => 'medium',
				'options' => array(
					'small'  => __( 'Small', 'rsm-content-widgets' ),
					'medium' => __( 'Medium', 'rsm-content-widgets' ),
					'large'  => __( 'Large', 'rsm-content-widgets' ),
				),
			),
			'bg_color' => array(
				'type'    => 'color',
				'label'   => __( 'Background (custom mode)', 'rsm-content-widgets' ),
				'default' => '#2563eb',
			),
			'bg_hover_color' => array(
				'type'    => 'color',
				'label'   => __( 'Background hover (custom mode)', 'rsm-content-widgets' ),
				'default' => '#1d4ed8',
			),
			'text_color' => array(
				'type'    => 'color',
				'label'   => __( 'Text color (custom mode)', 'rsm-content-widgets' ),
				'default' => '#ffffff',
			),
			'icon' => array(
				'type'  => 'text',
				'label' => __( 'Icon slug (custom mode)', 'rsm-content-widgets' ),
			),
		)
		);
	}

	/**
	 * @param array<string, mixed> $instance Instance.
	 * @return string
	 */
	public function get_template_name( $instance ) {
		unset( $instance );
		return 'buttons';
	}

	/**
	 * @param array<string, mixed> $instance Instance.
	 * @return string
	 */
	public function get_style_name( $instance ) {
		unset( $instance );
		return '';
	}

	/**
	 * @param array<string, mixed> $instance Instance.
	 * @param array<string, mixed> $args     Args.
	 * @return array<string, mixed>
	 */
	public function get_template_variables( $instance, $args ) {
		unset( $args );
		return array(
			'html' => $this->render_button_html( $instance ),
		);
	}

	/**
	 * Direct render — same approach as RSM Directory (bypasses fragile SO tpl path resolution).
	 *
	 * @param array<string, mixed> $args     Widget wrapper args.
	 * @param array<string, mixed> $instance Saved instance.
	 * @return void
	 */
	public function widget( $args, $instance ) {
		$html = $this->render_button_html( $instance );
		if ( '' === trim( $html ) ) {
			return;
		}

		echo wp_kses_post( $args['before_widget'] );
		echo wp_kses( $html, Rsmspark_Content_Widgets_Kses::allowed_html() );
		echo wp_kses_post( $args['after_widget'] );
	}

	/**
	 * @param array<string, mixed> $instance Instance.
	 * @return void
	 */
	public function enqueue_admin_scripts() {
		Rsmspark_Content_Widgets_SiteOrigin::maybe_enqueue_widget_json_admin_for_widget( $this );
		$this->enqueue_button_assets();
	}

	/**
	 * @param array<string, mixed> $instance Instance.
	 * @return void
	 */
	public function enqueue_frontend_scripts( $instance ) {
		unset( $instance );
		$this->enqueue_button_assets();
	}

	/**
	 * @return void
	 */
	public function enqueue_button_assets() {
		if ( ! class_exists( 'Rsmspark_Content_Widgets_Assets', false ) ) {
			return;
		}

		Rsmspark_Content_Widgets_Assets::enqueue_for_widget( 'buttons' );
	}

	/**
	 * @param array<string, mixed> $instance Instance.
	 * @return string
	 */
	private function render_button_html( $instance ) {
		if ( ! class_exists( 'Rsmspark_Content_Widgets_Widget_Buttons', false ) ) {
			require_once RSMSPARK_CONTENT_WIDGETS_PATH . 'includes/widgets/class-rsmspark-content-widgets-widget-buttons.php';
		}

		$instance = $this->modify_instance( is_array( $instance ) ? $instance : array() );
		$force    = $this->is_preview()
			|| ( defined( 'DOING_AJAX' ) && DOING_AJAX )
			|| is_admin()
			|| ! empty( $GLOBALS['SITEORIGIN_PANELS_PREVIEW_RENDER'] )
			|| ! empty( $GLOBALS['SITEORIGIN_PANELS_CACHE_RENDER'] );

		$html = Rsmspark_Content_Widgets_Widget_Buttons::render_instance( $instance, $force );

		if ( '' === trim( $html ) && $force ) {
			return '<p class="rsmspark-btn-placeholder" style="margin:0;padding:12px;border:1px dashed #cbd5e1;border-radius:6px;color:#64748b;">'
				. esc_html__( 'Select a saved button in the widget settings.', 'rsm-content-widgets' )
				. '</p>';
		}

		return $html;
	}
}

if ( function_exists( 'siteorigin_widget_register' ) ) {
	siteorigin_widget_register( 'buttons', __FILE__, 'Rsmspark_Content_Widgets_Buttons_Widget' );
}
