<?php

namespace RadiusTheme\RadiusBooking\Elementor\Widgets;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use RadiusTheme\RadiusBooking\Controllers\ServiceController;

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

class AppointmentFormWidget extends Widget_Base {

	public function get_name() {
		return 'rtrb_appointment_form';
	}

	public function get_title() {
		return esc_html__( 'Appointment Form', 'radius-booking' );
	}

	public function get_icon() {
		return 'rtrb-icon-booking';
	}

	public function get_categories() {
		return array( 'radius-booking' );
	}

	public function get_keywords() {
		return array( 'appointment', 'booking', 'form', 'schedule', 'radius' );
	}

	/**
	 * Build a flat list of services for the Elementor SELECT control.
	 *
	 * @return array [ '' => 'None', service_id => 'Category — Service Name', ... ]
	 */
	private function get_services_options() {
		$options = array( '' => esc_html__( 'None', 'radius-booking' ) );

		try {
			$categories = ( new ServiceController() )->fetchAllServices();

			if ( is_array( $categories ) ) {
				foreach ( $categories as $category ) {
					if ( empty( $category['services'] ) ) {
						continue;
					}
					$cat_name = $category['name'] ?? __( 'Uncategorized', 'radius-booking' );

					foreach ( $category['services'] as $service ) {
						$options[ $service['id'] ] = $cat_name . ' — ' . $service['name'];
					}
				}
			}
		} catch ( \Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
			// Silently fail — dropdown will only show "None".
		}

		return $options;
	}

	/**
	 * Build a map of service_id => [ staff_user_id => 'Staff Name', ... ]
	 * and a flat list of all unique staff members.
	 *
	 * @return array{options: array, map: array}
	 */
	private function get_staff_data() {
		$options = array( '' => esc_html__( 'None', 'radius-booking' ) );
		$map     = array();

		try {
			$categories = ( new ServiceController() )->fetchAllServices();

			if ( is_array( $categories ) ) {
				foreach ( $categories as $category ) {
					if ( empty( $category['services'] ) ) {
						continue;
					}

					foreach ( $category['services'] as $service ) {
						if ( empty( $service['staff'] ) ) {
							continue;
						}

						$service_staff = array();

						foreach ( $service['staff'] as $staff ) {
							$staff_id = $staff['id'];
							$name     = $staff['name'] ?? __( 'Staff', 'radius-booking' );

							$options[ $staff_id ] = $name;
							$service_staff[]      = $staff_id;
						}

						$map[ $service['id'] ] = $service_staff;
					}
				}
			}
		} catch ( \Exception $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
			// Silently fail.
		}

		return array(
			'options' => $options,
			'map'     => $map,
		);
	}

	protected function register_controls() {
		$staff_data = $this->get_staff_data();

		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Settings', 'radius-booking' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'info_notice',
			array(
				'type'            => Controls_Manager::RAW_HTML,
				'raw'             => esc_html__( 'This widget renders the Appointment Booking Form. Customize the form appearance from Radius Booking > Settings > Form Customization.', 'radius-booking' ),
				'content_classes' => 'elementor-panel-alert elementor-panel-alert-info',
			)
		);

		$this->add_control(
			'modal',
			array(
				'label'        => esc_html__( 'Display as Modal', 'radius-booking' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'radius-booking' ),
				'label_off'    => esc_html__( 'No', 'radius-booking' ),
				'return_value' => 'true',
				'default'      => '',
				'description'  => esc_html__( 'Show a "Book Now" button that opens the form in a modal popup.', 'radius-booking' ),
			)
		);

		$this->add_control(
			'button_text',
			array(
				'label'       => esc_html__( 'Button Text', 'radius-booking' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => '',
				'description' => esc_html__( 'Override the "Book Now" button label. Leave empty to use the global setting.', 'radius-booking' ),
				'condition'   => array(
					'modal' => 'true',
				),
			)
		);

		$this->add_control(
			'flow',
			array(
				'label'       => esc_html__( 'Selection Flow', 'radius-booking' ),
				'type'        => Controls_Manager::SELECT,
				'default'     => 'service_first',
				'options'     => array(
					'service_first' => esc_html__( 'Service first, then Staff', 'radius-booking' ),
					'staff_first'   => esc_html__( 'Staff first, then Service', 'radius-booking' ),
				),
				'description' => esc_html__( 'Order in which the customer selects the service and staff member on the first step.', 'radius-booking' ),
			)
		);

		$this->add_control(
			'service_id',
			array(
				'label'          => esc_html__( 'Pre-select Service', 'radius-booking' ),
				'type'           => Controls_Manager::SELECT2,
				'default'        => '',
				'options'        => $this->get_services_options(),
				'label_block'    => true,
				'select2options' => array( 'placeholder' => esc_html__( 'Search services...', 'radius-booking' ) ),
				'description'    => esc_html__( 'Pre-select a specific service. Leave as "None" for no pre-selection.', 'radius-booking' ),
			)
		);

		$this->add_control(
			'staff_id',
			array(
				'label'          => esc_html__( 'Pre-select Staff', 'radius-booking' ),
				'type'           => Controls_Manager::SELECT2,
				'default'        => '',
				'options'        => $staff_data['options'],
				'label_block'    => true,
				'select2options' => array( 'placeholder' => esc_html__( 'Search staff...', 'radius-booking' ) ),
				'description'    => esc_html__( 'Pre-select a specific staff member. Only staff assigned to the selected service will take effect.', 'radius-booking' ),
			)
		);

		// Hidden control to store the service → staff mapping for the editor JS.
		$this->add_control(
			'_staff_map',
			array(
				'type'    => Controls_Manager::HIDDEN,
				'default' => wp_json_encode( $staff_data['map'] ),
			)
		);

		$this->end_controls_section();

		$this->register_button_style_controls();
	}

	/**
	 * Style-tab controls for the modal "Book Now" trigger button.
	 *
	 * @return void
	 */
	private function register_button_style_controls() {
		$btn = '{{WRAPPER}} .rtrb-shortcode-modal-trigger';

		$this->start_controls_section(
			'section_style_button',
			array(
				'label'     => esc_html__( 'Modal Button', 'radius-booking' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array(
					'modal' => 'true',
				),
			)
		);

		$this->add_responsive_control(
			'button_align',
			array(
				'label'     => esc_html__( 'Alignment', 'radius-booking' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'left'   => array(
						'title' => esc_html__( 'Left', 'radius-booking' ),
						'icon'  => 'eicon-text-align-left',
					),
					'center' => array(
						'title' => esc_html__( 'Center', 'radius-booking' ),
						'icon'  => 'eicon-text-align-center',
					),
					'right'  => array(
						'title' => esc_html__( 'Right', 'radius-booking' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'default'   => 'left',
				'selectors' => array(
					'{{WRAPPER}} .rtrb-shortcode-modal-wrapper' => 'text-align: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'button_full_width',
			array(
				'label'        => esc_html__( 'Full Width', 'radius-booking' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'radius-booking' ),
				'label_off'    => esc_html__( 'No', 'radius-booking' ),
				'return_value' => 'yes',
				'default'      => '',
				'selectors'    => array(
					$btn => 'display: block; width: 100%;',
				),
			)
		);

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

		$this->start_controls_tabs( 'button_style_tabs' );

		$this->start_controls_tab(
			'button_tab_normal',
			array(
				'label' => esc_html__( 'Normal', 'radius-booking' ),
			)
		);

		$this->add_control(
			'button_text_color',
			array(
				'label'     => esc_html__( 'Text Color', 'radius-booking' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => array(
					$btn => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'button_bg_color',
			array(
				'label'     => esc_html__( 'Background Color', 'radius-booking' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#0040ff',
				'selectors' => array(
					$btn => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'button_tab_hover',
			array(
				'label' => esc_html__( 'Hover', 'radius-booking' ),
			)
		);

		$this->add_control(
			'button_text_color_hover',
			array(
				'label'     => esc_html__( 'Text Color', 'radius-booking' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$btn . ':hover, ' . $btn . ':focus' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'button_bg_color_hover',
			array(
				'label'     => esc_html__( 'Background Color', 'radius-booking' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$btn . ':hover, ' . $btn . ':focus' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'button_border_color_hover',
			array(
				'label'     => esc_html__( 'Border Color', 'radius-booking' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$btn . ':hover, ' . $btn . ':focus' => 'border-color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_tab();

		$this->end_controls_tabs();

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

		$this->add_responsive_control(
			'button_border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'radius-booking' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%', 'em' ),
				'default'    => array(
					'top'      => 8,
					'right'    => 8,
					'bottom'   => 8,
					'left'     => 8,
					'unit'     => 'px',
					'isLinked' => true,
				),
				'selectors'  => array(
					$btn => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'button_padding',
			array(
				'label'      => esc_html__( 'Padding', 'radius-booking' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em', '%' ),
				'default'    => array(
					'top'      => 12,
					'right'    => 28,
					'bottom'   => 12,
					'left'     => 28,
					'unit'     => 'px',
					'isLinked' => false,
				),
				'selectors'  => array(
					$btn => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'button_margin',
			array(
				'label'      => esc_html__( 'Margin', 'radius-booking' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em', '%' ),
				'selectors'  => array(
					$btn => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

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

		$this->end_controls_section();
	}

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

		$shortcode_atts = '';

		if ( ! empty( $settings['modal'] ) ) {
			$shortcode_atts .= ' modal="true"';
		}

		if ( ! empty( $settings['button_text'] ) ) {
			$shortcode_atts .= ' button_text="' . esc_attr( $settings['button_text'] ) . '"';
		}

		$flow = isset( $settings['flow'] ) && 'staff_first' === $settings['flow'] ? 'staff_first' : 'service_first';
		if ( 'staff_first' === $flow ) {
			$shortcode_atts .= ' flow="staff_first"';
		}

		$service_id = ! empty( $settings['service_id'] ) ? absint( $settings['service_id'] ) : 0;
		$staff_id   = ! empty( $settings['staff_id'] ) ? absint( $settings['staff_id'] ) : 0;

		// Validate that the selected staff is actually assigned to the selected service.
		if ( $service_id && $staff_id ) {
			$staff_map     = json_decode( $settings['_staff_map'] ?? '{}', true );
			$valid_staff   = $staff_map[ $service_id ] ?? array();

			if ( ! in_array( $staff_id, $valid_staff, true ) ) {
				$staff_id = 0;
			}
		}

		if ( $service_id ) {
			$shortcode_atts .= ' service_id="' . $service_id . '"';
		}

		if ( $staff_id ) {
			$shortcode_atts .= ' staff_id="' . $staff_id . '"';
		}

		echo do_shortcode( '[radius_booking_form' . $shortcode_atts . ']' );
	}
}
