<?php
/**
 * Widget Name: WooCommerce Login
 * Description: Renders the WooCommerce login form (optionally with the register
 *              form) for logged-out visitors, a customizable welcome + logout for
 *              logged-in users, an optional post-login redirect, deep field/button
 *              styling and multiple styles.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.4.0
 */

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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;

/**
 * Class Captwiki_Woo_Login
 *
 * @since 1.4.0
 */
class Captwiki_Woo_Login extends Widget_Base {

	/**
	 * Get widget name.
	 *
	 * @since 1.4.0
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-woo-login';
	}

	/**
	 * Get widget title.
	 *
	 * @since 1.4.0
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'WooCommerce Login', 'captain-widgets-kit' );
	}

	/**
	 * Get widget icon.
	 *
	 * @since 1.4.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-lock-user captwiki-el-logo';
	}

	/**
	 * Get widget categories.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	public function get_categories(): array {
		return array( 'captwiki-woo-commerce' );
	}

	/**
	 * Get widget keywords.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'woocommerce', 'woo', 'login', 'register', 'sign in', 'account', 'form', 'captain-widgets-kit' );
	}

	/**
	 * Disable Elementor's default inner wrapper.
	 *
	 * @since 1.4.0
	 * @return bool
	 */
	public function has_widget_inner_wrapper(): bool {
		return ! \Elementor\Plugin::$instance->experiments->is_feature_active( 'e_optimized_markup' );
	}

	/**
	 * Available visual styles.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Classic', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Card', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Bordered', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Underline Fields', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Soft', 'captain-widgets-kit' ),
			'style-6' => esc_html__( 'Style 6 – Split', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Register controls.
	 *
	 * @since 1.4.0
	 */
	protected function register_controls(): void {
		$this->register_content_controls();
		$this->register_box_style_controls();
		$this->register_text_style_controls();
		$this->register_field_style_controls();
		$this->register_button_style_controls();
	}

	/**
	 * Content tab controls.
	 *
	 * @since 1.4.0
	 */
	private function register_content_controls(): void {

		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Login', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'widget_style',
			array(
				'label'   => esc_html__( 'Style', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'style-1',
				'options' => $this->captwiki_style_options(),
			)
		);

		$this->add_control(
			'form_type',
			array(
				'label'   => esc_html__( 'Form', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'login',
				'options' => array(
					'login'          => esc_html__( 'Login Only', 'captain-widgets-kit' ),
					'login_register' => esc_html__( 'Login + Register', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'show_title',
			array(
				'label'        => esc_html__( 'Show Title', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'Hide', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array( 'form_type' => 'login' ),
			)
		);

		$this->add_control(
			'title_text',
			array(
				'label'     => esc_html__( 'Title', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => esc_html__( 'Login', 'captain-widgets-kit' ),
				'condition' => array(
					'form_type'  => 'login',
					'show_title' => 'yes',
				),
			)
		);

		$this->add_control(
			'redirect_type',
			array(
				'label'   => esc_html__( 'After Login', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'default',
				'options' => array(
					'default' => esc_html__( 'Default (stay / My Account)', 'captain-widgets-kit' ),
					'current' => esc_html__( 'Current Page', 'captain-widgets-kit' ),
					'custom'  => esc_html__( 'Custom URL', 'captain-widgets-kit' ),
				),
				'condition' => array( 'form_type' => 'login' ),
			)
		);

		$this->add_control(
			'redirect_url',
			array(
				'label'         => esc_html__( 'Redirect URL', 'captain-widgets-kit' ),
				'type'          => Controls_Manager::URL,
				'show_external' => false,
				'placeholder'   => esc_url( home_url( '/' ) ),
				'condition'     => array(
					'form_type'     => 'login',
					'redirect_type' => 'custom',
				),
			)
		);

		$this->add_control(
			'logged_in_heading',
			array(
				'label'     => esc_html__( 'Logged-In State', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::HEADING,
				'separator' => 'before',
			)
		);

		$this->add_control(
			'logged_in_action',
			array(
				'label'   => esc_html__( 'When Logged In', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'message',
				'options' => array(
					'message' => esc_html__( 'Show Welcome + Logout', 'captain-widgets-kit' ),
					'hide'    => esc_html__( 'Hide Widget', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'welcome_text',
			array(
				'label'       => esc_html__( 'Welcome Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Welcome back, {name}!', 'captain-widgets-kit' ),
				'description' => esc_html__( 'Use {name} for the display name.', 'captain-widgets-kit' ),
				'condition'   => array( 'logged_in_action' => 'message' ),
			)
		);

		$this->add_control(
			'logout_text',
			array(
				'label'     => esc_html__( 'Logout Button Text', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => esc_html__( 'Log out', 'captain-widgets-kit' ),
				'condition' => array( 'logged_in_action' => 'message' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Box style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_box_style_controls(): void {

		$wrap = '{{WRAPPER}} .captwiki-login__inner';

		$this->start_controls_section(
			'section_box_style',
			array(
				'label' => esc_html__( 'Form Box', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_responsive_control(
			'box_max_width',
			array(
				'label'      => esc_html__( 'Max Width', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', '%' ),
				'range'      => array(
					'px' => array( 'min' => 280, 'max' => 900 ),
					'%'  => array( 'min' => 30, 'max' => 100 ),
				),
				'selectors'  => array(
					$wrap => 'max-width: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'box_bg',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $wrap => 'background-color: {{VALUE}};' ),
			)
		);

		$this->add_responsive_control(
			'box_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					$wrap => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'box_border',
				'selector' => $wrap,
			)
		);

		$this->add_responsive_control(
			'box_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%' ),
				'selectors'  => array(
					$wrap => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'box_shadow',
				'selector' => $wrap,
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Title & label style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_text_style_controls(): void {

		$title  = '{{WRAPPER}} .captwiki-login__title, {{WRAPPER}} .captwiki-login h2';
		$label  = '{{WRAPPER}} .captwiki-login label';

		$this->start_controls_section(
			'section_text_style',
			array(
				'label' => esc_html__( 'Title & Labels', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'title_color',
			array(
				'label'     => esc_html__( 'Title Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $title => 'color: {{VALUE}};' ),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'title_typography',
				'selector' => $title,
			)
		);

		$this->add_control(
			'label_color',
			array(
				'label'     => esc_html__( 'Label Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'separator' => 'before',
				'selectors' => array( $label => 'color: {{VALUE}};' ),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'label_typography',
				'selector' => $label,
			)
		);

		$this->add_control(
			'link_color',
			array(
				'label'     => esc_html__( 'Link Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'separator' => 'before',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-login a' => 'color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Field style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_field_style_controls(): void {

		$field = '{{WRAPPER}} .captwiki-login input:not([type="checkbox"]):not([type="radio"]):not([type="submit"]):not([type="button"])';

		$this->start_controls_section(
			'section_field_style',
			array(
				'label' => esc_html__( 'Fields', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'field_text_color',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $field => 'color: {{VALUE}};' ),
			)
		);

		$this->add_control(
			'field_bg',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $field => 'background-color: {{VALUE}};' ),
			)
		);

		$this->add_control(
			'field_focus_color',
			array(
				'label'     => esc_html__( 'Focus Border', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $field . ':focus' => 'border-color: {{VALUE}}; outline: none;' ),
			)
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'      => 'field_border',
				'selector'  => $field,
				'separator' => 'before',
			)
		);

		$this->add_responsive_control(
			'field_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px' ),
				'selectors'  => array(
					$field => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'field_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					$field => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Button style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_button_style_controls(): void {

		$btn = '{{WRAPPER}} .captwiki-login .button, {{WRAPPER}} .captwiki-login button[type="submit"], {{WRAPPER}} .captwiki-login .woocommerce-form-login__submit, {{WRAPPER}} .captwiki-login__logout';

		$this->start_controls_section(
			'section_button_style',
			array(
				'label' => esc_html__( 'Button', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'btn_full_width',
			array(
				'label'        => esc_html__( 'Full Width', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'no',
				'selectors'    => array(
					$btn => 'width: 100%; display: block; text-align: center;',
				),
			)
		);

		$this->start_controls_tabs( 'login_btn_tabs' );

		$this->start_controls_tab( 'login_btn_normal', array( 'label' => esc_html__( 'Normal', 'captain-widgets-kit' ) ) );

		$this->add_control(
			'login_btn_color',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $btn => 'color: {{VALUE}};' ),
			)
		);

		$this->add_control(
			'login_btn_bg',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $btn => 'background-color: {{VALUE}};' ),
			)
		);

		$this->end_controls_tab();

		$this->start_controls_tab( 'login_btn_hover', array( 'label' => esc_html__( 'Hover', 'captain-widgets-kit' ) ) );

		$this->add_control(
			'login_btn_color_hover',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $btn . ':hover' => 'color: {{VALUE}};' ),
			)
		);

		$this->add_control(
			'login_btn_bg_hover',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( $btn . ':hover' => 'background-color: {{VALUE}};' ),
			)
		);

		$this->end_controls_tab();

		$this->end_controls_tabs();

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'      => 'login_btn_typography',
				'selector'  => $btn,
				'separator' => 'before',
			)
		);

		$this->add_responsive_control(
			'login_btn_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%' ),
				'selectors'  => array(
					$btn => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'login_btn_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					$btn => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Resolve the configured redirect URL.
	 *
	 * @since 1.4.0
	 * @param array $settings Widget settings.
	 * @return string
	 */
	private function captwiki_get_redirect( array $settings ): string {

		$type = ! empty( $settings['redirect_type'] ) ? $settings['redirect_type'] : 'default';

		if ( 'current' === $type ) {
			return get_permalink() ? get_permalink() : home_url( add_query_arg( null, null ) );
		}

		if ( 'custom' === $type && ! empty( $settings['redirect_url']['url'] ) ) {
			return $settings['redirect_url']['url'];
		}

		return '';
	}

	/**
	 * Output an editor-only notice.
	 *
	 * @since 1.4.0
	 * @param string $message Notice text.
	 */
	private function captwiki_render_editor_notice( string $message ): void {

		if ( ! \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
			return;
		}

		echo '<div class="captwiki-login captwiki-login--notice"><p>' . esc_html( $message ) . '</p></div>';
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.4.0
	 */
	protected function render(): void {

		if ( ! class_exists( 'WooCommerce' ) || ! function_exists( 'woocommerce_login_form' ) ) {
			$this->captwiki_render_editor_notice( esc_html__( 'WooCommerce is required for the WooCommerce Login widget.', 'captain-widgets-kit' ) );
			return;
		}

		$settings = $this->get_settings_for_display();

		$allowed_styles = array_keys( $this->captwiki_style_options() );
		$style          = ! empty( $settings['widget_style'] ) && in_array( $settings['widget_style'], $allowed_styles, true ) ? $settings['widget_style'] : 'style-1';

		wp_enqueue_style(
			'captwiki-woo-login-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/woo-login/captwiki-woo-login-' . $style . '.css',
			array( 'captwiki-woo-login' ),
			CAPTWIKI_VERSION
		);

		$form_type = ! empty( $settings['form_type'] ) ? $settings['form_type'] : 'login';

		$wrapper_classes = array(
			'captwiki-login',
			'captwiki-' . $style,
			'captwiki-login--' . ( 'login_register' === $form_type ? 'duo' : 'single' ),
			'captwiki-widget-' . $this->get_id(),
		);

		echo '<div class="' . esc_attr( implode( ' ', $wrapper_classes ) ) . '">';
		echo '<div class="captwiki-login__inner">';

		// Logged-in state.
		if ( is_user_logged_in() ) {

			if ( ! empty( $settings['logged_in_action'] ) && 'hide' === $settings['logged_in_action'] ) {
				$this->captwiki_render_editor_notice( esc_html__( 'You are logged in — this widget is hidden on the live site.', 'captain-widgets-kit' ) );
				echo '</div></div>';
				return;
			}

			$user    = wp_get_current_user();
			$welcome = ! empty( $settings['welcome_text'] ) ? $settings['welcome_text'] : esc_html__( 'Welcome back, {name}!', 'captain-widgets-kit' );
			$welcome = str_replace( '{name}', $user->display_name, $welcome );
			$logout  = ! empty( $settings['logout_text'] ) ? $settings['logout_text'] : esc_html__( 'Log out', 'captain-widgets-kit' );

			echo '<div class="captwiki-login__welcome">';
			echo '<p class="captwiki-login__welcome-text">' . esc_html( $welcome ) . '</p>';
			echo '<a class="button captwiki-login__logout" href="' . esc_url( wp_logout_url( get_permalink() ? get_permalink() : home_url( '/' ) ) ) . '">' . esc_html( $logout ) . '</a>';
			echo '</div>';

			echo '</div></div>';
			return;
		}

		// Logged-out: render the form(s).
		if ( 'login_register' === $form_type ) {
			// Outputs the login + register columns (register only if enabled in WC).
			wc_get_template( 'myaccount/form-login.php' );
		} else {
			$redirect = $this->captwiki_get_redirect( $settings );

			if ( ! empty( $settings['show_title'] ) && 'yes' === $settings['show_title'] ) {
				$title = ! empty( $settings['title_text'] ) ? $settings['title_text'] : esc_html__( 'Login', 'captain-widgets-kit' );
				echo '<h2 class="captwiki-login__title">' . esc_html( $title ) . '</h2>';
			}

			echo '<div class="captwiki-login__form">';
			woocommerce_login_form(
				array(
					'redirect' => $redirect ? $redirect : '',
				)
			);
			echo '</div>';
		}

		echo '</div>'; // inner.
		echo '</div>'; // wrapper.
	}
}
