<?php
namespace UM_Elementor;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Typography;
use UM_Elementor\Abstracts\UM_Profile_Base_Widget;

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

/**
 * Styles Ultimate Member’s password reset flow (shortcode {@see 'ultimatemember_password'}).
 */
class UM_Password_Reset_Styler_Widget extends UM_Profile_Base_Widget {

	public function get_name(): string {
		return 'um-password-reset-styler';
	}

	public function get_title(): string {
		return __( 'Password Reset', 'ultimate-member-widgets-for-elementor' );
	}

	public function get_icon(): string {
		return 'eicon-lock-user';
	}

	public function get_keywords(): array {
		return [ 'um', 'ultimate member', 'password', 'reset', 'forgot', 'styler' ];
	}

	public function get_script_depends(): array {
		return [ 'umep-styler-editor' ];
	}

	public function show_in_panel(): bool {
		return true;
	}

	protected function register_controls(): void {
		$this->start_controls_section(
			'section_form_select',
			[ 'label' => __( 'Form', 'ultimate-member-widgets-for-elementor' ) ]
		);

		$this->register_core_page_panel_hint( 'password-reset' );
		$this->register_um_edit_form_notice();

		$this->add_control(
			'reset_form_id',
			[
				'label'       => __( 'Password reset form', 'ultimate-member-widgets-for-elementor' ),
				'type'        => Controls_Manager::SELECT,
				'options'     => self::get_password_form_options(),
				'default'     => '',
				'description' => __( 'Optional: pick a published UM form in password-reset mode. Leave blank to use UM’s default.', 'ultimate-member-widgets-for-elementor' ),
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_wrapper_style',
			[
				'label' => __( 'Wrapper', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'pw_wrapper_bg',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um.um-password-reset' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_responsive_control(
			'pw_wrapper_padding',
			[
				'label'      => __( 'Padding', 'ultimate-member-widgets-for-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', 'em' ],
				'selectors'  => [
					'{{WRAPPER}} .um.um-password-reset' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'     => 'pw_wrapper_border',
				'selector' => '{{WRAPPER}} .um.um-password-reset',
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_input_style',
			[
				'label' => __( 'Email / text fields', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'pw_input_bg',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-password-reset .um-field input[type="text"],
					 {{WRAPPER}} .um-password-reset .um-field input[type="email"]' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_button_style',
			[
				'label' => __( 'Submit button', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'pw_btn_bg',
			[
				'label'     => __( 'Background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-password-reset input.um-button[type="submit"],
					 {{WRAPPER}} .um-password-reset .um-button' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'pw_btn_typography',
				'selector' => '{{WRAPPER}} .um-password-reset input.um-button[type="submit"],
				               {{WRAPPER}} .um-password-reset .um-button',
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_notice_style',
			[
				'label' => __( 'Notices', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'pw_notice_success_bg',
			[
				'label'     => __( 'Success background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-password-reset .um-notice.notice-success,
					 {{WRAPPER}} .um-password-reset .um-notice.um-notice-success' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->add_control(
			'pw_notice_error_bg',
			[
				'label'     => __( 'Error background', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-password-reset .um-notice.notice-error,
					 {{WRAPPER}} .um-password-reset .um-notice.um-notice-error' => 'background-color: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_link_style',
			[
				'label' => __( 'Back / footer links', 'ultimate-member-widgets-for-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_control(
			'pw_link_color',
			[
				'label'     => __( 'Color', 'ultimate-member-widgets-for-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .um-password-reset .um-link a,
					 {{WRAPPER}} .um-password-reset .um-link' => 'color: {{VALUE}} !important;',
				],
			]
		);

		$this->end_controls_section();
	}

	/**
	 * Password reset does not use UM profile context.
	 */
	protected function render(): void {
		if ( ! function_exists( 'UM' ) ) {
			if ( current_user_can( 'edit_pages' ) ) {
				echo '<p>' . esc_html__( 'This widget requires Ultimate Member to be active.', 'ultimate-member-widgets-for-elementor' ) . '</p>';
			}
			return;
		}

		$this->render_profile_widget( 0 );
	}

	protected function render_profile_widget( int $user_id ): void {
		$settings  = $this->get_settings_for_display();
		$form_id   = (int) ( $settings['reset_form_id'] ?? 0 );
		$is_editor = \Elementor\Plugin::$instance->editor->is_edit_mode();

		if ( ! shortcode_exists( 'ultimatemember_password' ) ) {
			if ( $is_editor ) {
				echo '<p class="umep-profile-body-empty">' . esc_html__( 'Ultimate Member password reset shortcode is not registered.', 'ultimate-member-widgets-for-elementor' ) . '</p>';
			}
			return;
		}

		if ( $form_id > 0 ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Shortcode output from UM.
			echo do_shortcode( '[ultimatemember_password form_id="' . (int) $form_id . '"]' );
			return;
		}

		if ( $is_editor ) {
			$this->render_editor_skeleton();
			return;
		}

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Shortcode output from UM.
		echo do_shortcode( '[ultimatemember_password]' );
	}

	private function render_editor_skeleton(): void {
		echo '<div class="umep-editor-preview-notice" style="'
			. 'background:#1d2939;color:#93c5fd;font-size:11px;font-family:monospace;'
			. 'padding:6px 12px;border-radius:4px;margin-bottom:16px;border-left:3px solid #3b82f6;">'
			. esc_html__( 'Editor preview — assign a password reset form above, or configure the default in UM → Settings → Pages.', 'ultimate-member-widgets-for-elementor' )
			. '</div>';
		echo '<div class="um um-password-reset" style="max-width:480px;padding:24px;border:1px solid #e2e8f0;border-radius:8px;">';
		echo '<div class="um-field"><span class="um-field-label"><label>' . esc_html__( 'Email address', 'ultimate-member-widgets-for-elementor' ) . '</label></span>';
		echo '<div class="um-field-area"><input type="text" class="um-form-field" value="" placeholder="name@example.com" style="width:100%;padding:8px;box-sizing:border-box;" /></div></div>';
		echo '<p style="margin-top:12px;"><input type="submit" class="um-button" value="' . esc_attr__( 'Reset password', 'ultimate-member-widgets-for-elementor' ) . '" /></p>';
		echo '<p class="um-link" style="margin-top:12px;"><a href="#">' . esc_html__( 'Back to login', 'ultimate-member-widgets-for-elementor' ) . '</a></p>';
		echo '</div>';
	}

	/**
	 * @return array<string, string>
	 */
	private static function get_password_form_options(): array {
		$cache_key = 'umep_um_form_options_password';
		$cached    = get_transient( $cache_key );
		if ( is_array( $cached ) ) {
			return $cached;
		}

		$forms = get_posts(
			[
				'post_type'      => 'um_form',
				'post_status'    => 'publish',
				'posts_per_page' => -1,
				'orderby'        => 'title',
				'order'          => 'ASC',
				'no_found_rows'  => true,
				'meta_query'     => [
					[
						'key'   => '_um_mode',
						'value' => 'password',
					],
				],
			]
		);

		$opts = [ '' => __( '— UM default —', 'ultimate-member-widgets-for-elementor' ) ];
		foreach ( (array) $forms as $form ) {
			$opts[ (string) $form->ID ] = esc_html( $form->post_title );
		}

		set_transient( $cache_key, $opts, 5 * MINUTE_IN_SECONDS );
		return $opts;
	}
}
