<?php

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Widget_Base;
use ThemeREX\AutoDealer\Forms\FormConfig;
use ThemeREX\AutoDealer\Forms\FormRenderer;

/**
 * Listing Form widget — configurable contact/inquiry form.
 *
 * @package ThemeREX\AutoDealer
 */
// Bail if Elementor isn't loaded — prevents a fatal during PSR-4 autoload
// when this file is included on a site that doesn't have Elementor active.
if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
	return;
}

class ListingFormWidget extends Widget_Base {

	public function get_name(): string {
		return 'trx_ad_listing_form';
	}

	public function get_title(): string {
		return __( 'Listing Form', 'trx-auto-dealer' );
	}

	public function get_icon(): string {
		return 'eicon-form-horizontal';
	}

	public function get_categories(): array {
		return array( 'trx-auto-dealer' );
	}

	public function get_style_depends(): array {
		return array( 'trx-ad-frontend', 'trx-ad-widget-listing-form' );
	}

	public function get_script_depends(): array {
		return array( 'trx-ad-frontend', 'trx-ad-widget-listing-form' );
	}

	protected function register_controls(): void {
		// Content.
		$this->start_controls_section(
			'section_content',
			array(
				'label' => __( 'Content', 'trx-auto-dealer' ),
			)
		);

		$this->add_control(
			'form_id',
			array(
				'label'   => __( 'Form', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::SELECT,
				'options' => FormConfig::getOptions(),
				'default' => 'inquiry',
			)
		);

		$this->add_control(
			'vehicle_id',
			array(
				'label'       => __( 'Vehicle', 'trx-auto-dealer' ),
				'type'        => Controls_Manager::SELECT2,
				'options'     => WidgetHelpers::vehicleOptions( __( '— Use current vehicle —', 'trx-auto-dealer' ) ),
				'default'     => '',
				'description' => __( 'Leave empty to bind to the current single-listing post.', 'trx-auto-dealer' ),
				'label_block' => true,
			)
		);

		$this->add_control(
			'show_title',
			array(
				'label'        => __( 'Show Title', 'trx-auto-dealer' ),
				'type'         => Controls_Manager::SWITCHER,
				'default'      => 'yes',
				'return_value' => 'yes',
			)
		);

		$this->add_control(
			'title',
			array(
				'label'     => __( 'Title', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => __( 'Inquire About This Vehicle', 'trx-auto-dealer' ),
				'condition' => array( 'show_title' => 'yes' ),
			)
		);

		$this->end_controls_section();

		// Style: Title.
		$this->start_controls_section(
			'section_style_title',
			array(
				'label'     => __( 'Title', 'trx-auto-dealer' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'show_title' => 'yes' ),
			)
		);

		$this->add_control(
			'title_color',
			array(
				'label'     => __( 'Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form-title' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'title_typography',
				'selector' => '{{WRAPPER}} .trx-ad-form-title',
			)
		);

		$this->add_responsive_control(
			'title_spacing',
			array(
				'label'     => __( 'Bottom Spacing', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min' => 0,
						'max' => 40,
					),
				),
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form-title' => 'margin-bottom: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();

		// Style: Labels.
		$this->start_controls_section(
			'section_style_labels',
			array(
				'label' => __( 'Labels', 'trx-auto-dealer' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'label_color',
			array(
				'label'     => __( 'Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form__label' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'label_typography',
				'selector' => '{{WRAPPER}} .trx-ad-form__label',
			)
		);

		$this->end_controls_section();

		// Style: Inputs.
		$this->start_controls_section(
			'section_style_inputs',
			array(
				'label' => __( 'Inputs', 'trx-auto-dealer' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'input_color',
			array(
				'label'     => __( 'Text Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form__input, {{WRAPPER}} .trx-ad-form__textarea, {{WRAPPER}} .trx-ad-form__select' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'input_bg',
			array(
				'label'     => __( 'Background', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form__input, {{WRAPPER}} .trx-ad-form__textarea, {{WRAPPER}} .trx-ad-form__select' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'input_border_color',
			array(
				'label'     => __( 'Border Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form__input, {{WRAPPER}} .trx-ad-form__textarea, {{WRAPPER}} .trx-ad-form__select' => 'border-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'input_border_radius',
			array(
				'label'      => __( 'Border Radius', 'trx-auto-dealer' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px' ),
				'selectors'  => array(
					'{{WRAPPER}} .trx-ad-form__input, {{WRAPPER}} .trx-ad-form__textarea, {{WRAPPER}} .trx-ad-form__select' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'input_typography',
				'selector' => '{{WRAPPER}} .trx-ad-form__input, {{WRAPPER}} .trx-ad-form__textarea, {{WRAPPER}} .trx-ad-form__select',
			)
		);

		$this->end_controls_section();

		// Style: Button.
		$this->start_controls_section(
			'section_style_button',
			array(
				'label' => __( 'Button', 'trx-auto-dealer' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'btn_color',
			array(
				'label'     => __( 'Text Color', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form__submit' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'btn_bg',
			array(
				'label'     => __( 'Background', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form__submit' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'btn_hover_bg',
			array(
				'label'     => __( 'Hover Background', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form__submit:hover' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'btn_border_radius',
			array(
				'label'      => __( 'Border Radius', 'trx-auto-dealer' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px' ),
				'selectors'  => array(
					'{{WRAPPER}} .trx-ad-form__submit' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'btn_padding',
			array(
				'label'      => __( 'Padding', 'trx-auto-dealer' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .trx-ad-form__submit' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'btn_typography',
				'selector' => '{{WRAPPER}} .trx-ad-form__submit',
			)
		);

		$this->add_control(
			'btn_full_width',
			array(
				'label'     => __( 'Full Width', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::SWITCHER,
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-form__submit' => 'width: 100%;',
				),
			)
		);

		$this->end_controls_section();
	}

	protected function render(): void {
		$settings = $this->get_settings_for_display();
		$post_id  = (int) ( $settings['vehicle_id'] ?? 0 );
		if ( $post_id <= 0 ) {
			$post_id = (int) $this->getPreviewPostId();
		}

		$formId    = $settings['form_id'] ?? 'inquiry';
		$showTitle = ( $settings['show_title'] ?? 'yes' ) === 'yes';
		$title     = $settings['title'] ?? '';

		if ( $showTitle && '' !== $title ) {
			echo '<h2 class="trx-ad-form-title">' . esc_html( $title ) . '</h2>';
		}

		echo wp_kses( FormRenderer::render( $formId, $post_id ? (int) $post_id : 0 ), \ThemeREX\AutoDealer\allowedHtml() );
	}

	/**
	 * @return int|false
	 */
	private function getPreviewPostId() {
		if ( ! \Elementor\Plugin::$instance->editor->is_edit_mode() && ! \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
			return get_the_ID();
		}

		$preview_id = \Elementor\Plugin::$instance->documents->get_current()
			? \Elementor\Plugin::$instance->documents->get_current()->get_settings( 'preview_id' )
			: 0;

		if ( $preview_id && 'trx_ad_listing' === get_post_type( $preview_id ) ) {
			return (int) $preview_id;
		}

		$posts = get_posts(
			array(
				'post_type'      => 'trx_ad_listing',
				'posts_per_page' => 1,
				'post_status'    => 'publish',
				'fields'         => 'ids',
			)
		);

		return ! empty( $posts ) ? (int) $posts[0] : false;
	}
}
