<?php
/**
 * Dealer Directory widget — grid of all dealers.
 *
 * Fetches the dealer CPT and renders one dealer-card template part per
 * dealer inside a CSS grid. Supports column count, max dealers, and
 * inventory-count display toggle.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
	return;
}

use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Typography;
use Elementor\Widget_Base;
use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\PostTypes\DealerPostType;

class DealerDirectoryWidget extends Widget_Base {

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

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

	public function get_icon(): string {
		return 'eicon-folder-o';
	}

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

	public function get_keywords(): array {
		return array( 'dealer', 'directory', 'list' );
	}

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

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

	protected function register_controls(): void {
		$this->start_controls_section(
			'section_query',
			array(
				'label' => __( 'Query', 'trx-auto-dealer' ),
			)
		);

		$this->add_control(
			'limit',
			array(
				'label'   => __( 'Maximum Dealers', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 100,
				'default' => 12,
			)
		);

		$this->add_responsive_control(
			'columns',
			array(
				'label'     => __( 'Columns', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => '3',
				'options'   => array(
					'1' => '1',
					'2' => '2',
					'3' => '3',
					'4' => '4',
				),
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-dealer-directory' => '--trx-ad-dir-cols: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'orderby',
			array(
				'label'   => __( 'Order By', 'trx-auto-dealer' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'title',
				'options' => array(
					'title'      => __( 'Name (A-Z)', 'trx-auto-dealer' ),
					'date'       => __( 'Most Recent', 'trx-auto-dealer' ),
					'menu_order' => __( 'Manual Order', 'trx-auto-dealer' ),
				),
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_visibility',
			array(
				'label' => __( 'Show / Hide Fields', 'trx-auto-dealer' ),
			)
		);

		$visibility = array(
			'show_logo'        => __( 'Logo', 'trx-auto-dealer' ),
			'show_phone'       => __( 'Phone', 'trx-auto-dealer' ),
			'show_email'       => __( 'Email', 'trx-auto-dealer' ),
			'show_address'     => __( 'Address', 'trx-auto-dealer' ),
			'show_website'     => __( 'Website', 'trx-auto-dealer' ),
			'show_hours'       => __( 'Hours', 'trx-auto-dealer' ),
			'show_map'         => __( 'Map', 'trx-auto-dealer' ),
			'show_description' => __( 'Description', 'trx-auto-dealer' ),
			'show_dealer_link' => __( 'Dealer Page Link', 'trx-auto-dealer' ),
		);
		// Default = on for everything (admin disables what they don't want).
		// Description hidden by default since it's optional + verbose.
		$default_off = array( 'show_description' );
		foreach ( $visibility as $key => $label ) {
			$this->add_control(
				$key,
				array(
					'label'        => $label,
					'type'         => Controls_Manager::SWITCHER,
					'default'      => in_array( $key, $default_off, true ) ? '' : 'yes',
					'return_value' => 'yes',
				)
			);
		}

		$this->end_controls_section();

		$this->start_controls_section(
			'section_style',
			array(
				'label' => __( 'Card', 'trx-auto-dealer' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

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

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'card_border',
				'selector' => '{{WRAPPER}} .trx-ad-dealer-card',
			)
		);

		$this->add_responsive_control(
			'card_gap',
			array(
				'label'     => __( 'Card Gap', 'trx-auto-dealer' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => array(
					'px' => array(
						'min' => 0,
						'max' => 60,
					),
				),
				'selectors' => array(
					'{{WRAPPER}} .trx-ad-dealer-directory' => 'gap: {{SIZE}}{{UNIT}};',
				),
			)
		);

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

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'heading_typography',
				'selector' => '{{WRAPPER}} .trx-ad-dealer-card__heading, {{WRAPPER}} .trx-ad-dealer-card__name',
			)
		);

		$this->end_controls_section();
	}

	protected function render(): void {
		$settings = $this->get_settings_for_display();

		$dealers = get_posts(
			array(
				'post_type'      => DealerPostType::POST_TYPE,
				'posts_per_page' => max( 1, (int) ( $settings['limit'] ?? 12 ) ),
				'post_status'    => 'publish',
				'orderby'        => (string) ( $settings['orderby'] ?? 'title' ),
				'order'          => 'title' === ( $settings['orderby'] ?? 'title' ) ? 'ASC' : 'DESC',
				'fields'         => 'ids',
			)
		);

		if ( empty( $dealers ) ) {
			echo '<p>' . esc_html__( 'No dealers found.', 'trx-auto-dealer' ) . '</p>';
			return;
		}

		$cardClass     = 'trx-ad-dealer-card-wrapper';
		$visibilityMap = array(
			'show_logo'        => 'no-logo',
			'show_phone'       => 'no-phone',
			'show_email'       => 'no-email',
			'show_address'     => 'no-address',
			'show_website'     => 'no-website',
			'show_hours'       => 'no-hours',
			'show_map'         => 'no-map',
			'show_description' => 'no-description',
			'show_dealer_link' => 'no-dealer-link',
		);
		foreach ( $visibilityMap as $key => $modifier ) {
			$enabled = 'yes' === ( $settings[ $key ] ?? 'yes' );
			if ( ! $enabled ) {
				$cardClass .= ' trx-ad-dealer-card--' . $modifier;
			}
		}

		$columns = max( 1, min( 4, (int) ( $settings['columns'] ?? 3 ) ) );
		// Use a CSS variable so the responsive control's selector AND the
		// fallback CSS rule both work; the variable also lets a theme
		// override grid-template-columns without specificity wars.
		?>
		<div class="trx-ad-dealer-directory" style="--trx-ad-dir-cols: <?php echo esc_attr( (string) $columns ); ?>;">
			<?php foreach ( $dealers as $dealer_id ) : ?>
				<div class="<?php echo esc_attr( $cardClass ); ?>">
					<?php TemplateLoader::getTemplatePart( 'dealer-card', array( 'dealer_id' => (int) $dealer_id ) ); ?>
				</div>
			<?php endforeach; ?>
		</div>
		<?php
	}
}
