<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Image_Size;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;
use Elementor\Utils;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Help_Controls;
use Sifency\Classes\Sifency_Addons_Widget_Base;
class Sifency_Addons_Widget_How_To extends Sifency_Addons_Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-schema',
			'title'          => 'Sifency Schema',
			'icon'           => 'eicon-code',
			'category'       => 'sifency-advance-widgets',
			'keywords'       => array( 'schema', 'json-ld', 'structured data' ),
			'style_depends'  => array( 'sifency-scheme-style', 'sifency-icons' ),
			'script_depends' => array( 'sifency-scheme-script' ),
		);}
	protected function register_controls() {
		$this->start_controls_section(
			'section_config',
			array(
				'label' => esc_html__( 'Configuration', 'sifency-addons' ),
			)
		);
		$this->add_control(
			'layout_mode',
			array(
				'label'   => esc_html__( 'Layout Mode', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'list',
				'options' => array(
					'list'      => esc_html__( 'Standard List', 'sifency-addons' ),
					'cards'     => esc_html__( 'Step Cards (Grid)', 'sifency-addons' ),
					'accordion' => esc_html__( 'Accordion Steps', 'sifency-addons' ),
				),
			)
		);
		$this->add_control(
			'output_schema',
			array(
				'label'       => esc_html__( 'Output JSON-LD Schema?', 'sifency-addons' ),
				'type'        => Controls_Manager::SWITCHER,
				'default'     => 'yes',
				'description' => esc_html__( 'Automatically injects Google-compliant schema code into the page.', 'sifency-addons' ),
			)
		);

		$this->end_controls_section();

		// --- MAIN INFO ---
		$this->start_controls_section(
			'section_main_info',
			array( 'label' => esc_html__( 'Introduction', 'sifency-addons' ) )
		);
		$this->add_control(
			'title',
			array(
				'label'       => 'How-to Title',
				'type'        => Controls_Manager::TEXT,
				'default'     => 'How to Tie a Tie',
				'label_block' => true,
			)
		);
		$this->add_control(
			'description',
			array(
				'label'   => 'Description',
				'type'    => Controls_Manager::TEXTAREA,
				'default' => 'A step-by-step guide to tying a perfect knot.',
			)
		);
		$this->add_control(
			'main_image',
			array(
				'label' => 'Main Image',
				'type'  => Controls_Manager::MEDIA,
			)
		);

		$this->end_controls_section();

		// --- META DATA (Time/Cost) ---
		$this->start_controls_section(
			'section_meta',
			array( 'label' => esc_html__( 'Time & Cost (Meta)', 'sifency-addons' ) )
		);
		$this->add_control(
			'time_days',
			array(
				'label'   => 'Days',
				'type'    => Controls_Manager::NUMBER,
				'default' => 0,
			)
		);
		$this->add_control(
			'time_hours',
			array(
				'label'   => 'Hours',
				'type'    => Controls_Manager::NUMBER,
				'default' => 0,
			)
		);
		$this->add_control(
			'time_mins',
			array(
				'label'   => 'Minutes',
				'type'    => Controls_Manager::NUMBER,
				'default' => 5,
			)
		);

		$this->add_control( 'hr_cost', array( 'type' => Controls_Manager::DIVIDER ) );

		$this->add_control(
			'cost',
			array(
				'label'   => 'Estimated Cost',
				'type'    => Controls_Manager::NUMBER,
				'default' => 0,
			)
		);
		$this->add_control(
			'currency',
			array(
				'label'       => 'Currency (ISO 4217)',
				'type'        => Controls_Manager::TEXT,
				'default'     => 'USD',
				'placeholder' => 'USD, EUR, GBP',
			)
		);

		$this->end_controls_section();

		// --- TOOLS & SUPPLIES ---
		$this->start_controls_section(
			'section_tools',
			array( 'label' => esc_html__( 'Tools & Supplies', 'sifency-addons' ) )
		);

		$repeater_tools = new Repeater();
		$repeater_tools->add_control(
			'item_name',
			array(
				'label' => 'Name',
				'type'  => Controls_Manager::TEXT,
			)
		);

		$this->add_control(
			'tools',
			array(
				'label'       => esc_html__( 'Tools Used', 'sifency-addons' ),
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater_tools->get_controls(),
				'title_field' => '{{{ item_name }}}',
				'default'     => array( array( 'item_name' => 'Hammer' ), array( 'item_name' => 'Nails' ) ),
			)
		);
		$this->add_control(
			'supplies',
			array(
				'label'       => esc_html__( 'Supplies / Materials', 'sifency-addons' ),
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater_tools->get_controls(),
				'title_field' => '{{{ item_name }}}',
				'default'     => array( array( 'item_name' => 'Wood' ), array( 'item_name' => 'Glue' ) ),
			)
		);

		$this->end_controls_section();

		// --- STEPS ---
		$this->start_controls_section(
			'section_steps',
			array( 'label' => esc_html__( 'Instructions (Steps)', 'sifency-addons' ) )
		);

		$repeater_steps = new Repeater();

		$repeater_steps->add_control(
			'step_title',
			array(
				'label'   => 'Step Title',
				'type'    => Controls_Manager::TEXT,
				'default' => 'Step 1',
			)
		);
		$repeater_steps->add_control(
			'step_desc',
			array(
				'label'   => 'Instructions',
				'type'    => Controls_Manager::WYSIWYG,
				'default' => 'Detailed instructions for this step.',
			)
		);
		$repeater_steps->add_control(
			'step_image',
			array(
				'label' => 'Step Image',
				'type'  => Controls_Manager::MEDIA,
			)
		);
		$repeater_steps->add_control(
			'step_url',
			array(
				'label' => 'Step URL (Optional)',
				'type'  => Controls_Manager::URL,
			)
		);

		$this->add_control(
			'steps',
			array(
				'label'       => esc_html__( 'Steps', 'sifency-addons' ),
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater_steps->get_controls(),
				'default'     => array(
					array( 'step_title' => 'Prepare the surface' ),
					array( 'step_title' => 'Apply the material' ),
				),
				'title_field' => '{{{ step_title }}}',
			)
		);

		$this->end_controls_section();
		$this->add_sifency_addons_help_controls();
		$this->start_controls_section(
			'style_steps',
			array(
				'label' => 'Steps',
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);
		$this->add_control(
			'step_bg',
			array(
				'label'     => 'Step Background',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-howto-step' => 'background-color: {{VALUE}};' ),
			)
		);
		$this->add_responsive_control(
			'step_gap',
			array(
				'label'     => 'Gap Between Steps',
				'type'      => Controls_Manager::SLIDER,
				'selectors' => array( '{{WRAPPER}} .sifency-howto-steps-container' => 'gap: {{SIZE}}px;' ),
			)
		);
		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'step_title_typo',
				'label'    => 'Step Title Typo',
				'selector' => '{{WRAPPER}} .sifency-howto-step-title',
			)
		);
		$this->add_control(
			'step_number_color',
			array(
				'label'     => 'Number Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-howto-step-count' => 'color: {{VALUE}};' ),
			)
		);
		$this->add_control(
			'step_number_bg',
			array(
				'label'     => 'Number BG',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-howto-step-count' => 'background-color: {{VALUE}};' ),
			)
		);
		$this->end_controls_section();

		$this->add_sifency_addons_image_style_controls(
			array(
				'prefix'       => 'image_style_',
				'label'        => 'Image',
				'selector'     => '.sifency-howto-main-img img',
				'exclude'      => array( 'shadow', 'filters', 'opacity', 'transition', 'tabs' ),
				'color_only'   => true,
				'condition'    => array( 'main_image[url]!' => '' ),
				'show_overlay' => false,
			)
		);

		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'heading_style_',
				'label'      => 'Main Title',
				'selector'   => '.sifency-howto-title',
				'exclude'    => array( 'shadow', 'stroke', 'transition', 'tabs', 'bg', 'radius' ),
				'color_only' => true,
				'condition'  => array( 'title!' => '' ),
			)
		);

		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'content_style_',
				'label'      => 'Description',
				'selector'   => '.sifency-howto-desc',
				'color_only' => true,
				'exclude'    => array( 'shadow', 'stroke', 'transition', 'tabs', 'bg', 'radius' ),
				'condition'  => array( 'description!' => '' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'meta_style_',
				'label'      => 'Meta Style',
				'selector'   => '.sifency-meta-item',
				'color_only' => true,
				'exclude'    => array( 'shadow', 'stroke', 'transition', 'tabs', 'bg', 'radius' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'metarial_heading_style_',
				'label'      => 'Metarial Heading',
				'selector'   => '.sifency-mat-title',
				'color_only' => true,
				'exclude'    => array( 'shadow', 'stroke', 'transition', 'tabs', 'bg', 'radius' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'metarial_content_style_',
				'label'      => 'Metarial Content',
				'selector'   => '.sifency-mat-col ul li',
				'color_only' => true,
				'exclude'    => array( 'shadow', 'stroke', 'transition', 'tabs', 'bg', 'radius' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'step_title_style_',
				'label'      => 'Step Title',
				'color_only' => true,
				'selector'   => '.sifency-howto-step-title',
				'exclude'    => array( 'shadow', 'box_model', 'stroke', 'transition', 'tabs' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'step_content_style_',
				'label'      => 'Step Content',
				'selector'   => '.sifency-howto-step-text',
				'color_only' => true,
				'exclude'    => array( 'shadow', 'stroke', 'transition', 'tabs', 'bg', 'radius', 'border' ),
			)
		);
		$this->add_Sifency_Addons_Animation_Controls();
	}

	protected function render_dom( array $context ) {
		$wrapper_id        = esc_attr( $context['dom_id'] );
		$settings          = $this->get_settings_for_display();
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );

		if ( 'yes' === $settings['output_schema'] ) {
			$iso_duration = 'P';
			if ( $settings['time_days'] ) {
				$iso_duration .= $settings['time_days'] . 'D';
			}
			if ( $settings['time_hours'] || $settings['time_mins'] ) {
				$iso_duration .= 'T';
				if ( $settings['time_hours'] ) {
					$iso_duration .= $settings['time_hours'] . 'H';
				}
				if ( $settings['time_mins'] ) {
					$iso_duration .= $settings['time_mins'] . 'M';
				}
			}

			$tools_array = array();
			foreach ( $settings['tools'] as $tool ) {
				$tools_array[] = array(
					'@type' => 'HowToTool',
					'name'  => $tool['item_name'],
				);
			}

			$supplies_array = array();
			foreach ( $settings['supplies'] as $supply ) {
				$supplies_array[] = array(
					'@type' => 'HowToSupply',
					'name'  => $supply['item_name'],
				);
			}

			$steps_array = array();
			foreach ( $settings['steps'] as $index => $step ) {
				$step_data = array(
					'@type' => 'HowToStep',
					'name'  => $step['step_title'],
					'text'  => wp_strip_all_tags( $step['step_desc'] ),
					'url'   => $step['step_url']['url'] ?? '',
				);
				if ( ! empty( $step['step_image']['url'] ) ) {
					$step_data['image'] = $step['step_image']['url'];
				}
				$steps_array[] = $step_data;
			}

			$schema = array(
				'@context'    => 'http://schema.org',
				'@type'       => 'HowTo',
				'name'        => $settings['title'],
				'description' => wp_strip_all_tags( $settings['description'] ),
				'totalTime'   => $iso_duration,
				'tool'        => $tools_array,
				'supply'      => $supplies_array,
				'step'        => $steps_array,
			);

			if ( ! empty( $settings['main_image']['url'] ) ) {
				$schema['image'] = array(
					'@type' => 'ImageObject',
					'url'   => $settings['main_image']['url'],
				);
			}

			if ( ! empty( $settings['cost'] ) ) {
				$schema['estimatedCost'] = array(
					'@type'    => 'MonetaryAmount',
					'currency' => $settings['currency'],
					'value'    => $settings['cost'],
				);
			}

			echo '<script type="application/ld+json">' . wp_json_encode( $schema ) . '</script>';
		}

		// --- 2. RENDER VISUAL HTML ---
		$this->add_render_attribute( 'wrapper', 'class', 'sifency-howto-wrapper' );
		$this->add_render_attribute( 'wrapper', 'class', 'sifency-howto-layout-' . $settings['layout_mode'] );

		?>
		<div id="<?php echo esc_attr( $wrapper_id ); ?>" <?php echo wp_kses_post( $this->get_render_attribute_string( 'wrapper' ) ); ?>>
			
			<!-- Header -->
			<div class="sifency-howto-header">
				<?php if ( ! empty( $settings['main_image']['url'] ) ) : ?>
					<div class="sifency-howto-main-img">
						<img src="<?php echo esc_url( $settings['main_image']['url'] ); ?>" alt="<?php echo esc_attr( $settings['title'] ); ?>">
					</div>
				<?php endif; ?>
				
				<h2 class="sifency-howto-title"><?php echo esc_html( $settings['title'] ); ?></h2>
				<div class="sifency-howto-desc"><?php echo wp_kses_post( $settings['description'] ); ?></div>

				<!-- Meta -->
				<div class="sifency-howto-meta">
					<?php if ( $settings['time_days'] || $settings['time_hours'] || $settings['time_mins'] ) : ?>
						<div class="sifency-meta-item">
							<i class="eicon-clock-o"></i> 
							<span>
								<?php
								if ( ! empty( $settings['time_days'] ) ) {
									echo esc_html( $settings['time_days'] ) . 'd ';
								}

								if ( ! empty( $settings['time_hours'] ) ) {
									echo esc_html( $settings['time_hours'] ) . 'h ';
								}

								if ( ! empty( $settings['time_mins'] ) ) {
									echo esc_html( $settings['time_mins'] ) . 'm';
								}
								?>
							</span>
						</div>
					<?php endif; ?>

					<?php if ( ! empty( $settings['cost'] ) ) : ?>
						<div class="sifency-meta-item">
							<i class="eicon-wallet"></i>
							<span><?php echo esc_html( $settings['cost'] . ' ' . $settings['currency'] ); ?></span>
						</div>
					<?php endif; ?>
				</div>
			</div>

			<!-- Tools & Supplies -->
			<?php if ( ! empty( $settings['tools'] ) || ! empty( $settings['supplies'] ) ) : ?>
			<div class="sifency-howto-materials">
				<?php if ( ! empty( $settings['tools'] ) ) : ?>
					<div class="sifency-mat-col">
						<h4 class="sifency-mat-title">Tools</h4>
						<ul>
							<?php
							foreach ( $settings['tools'] as $tool ) {
								echo '<li>' . esc_html( $tool['item_name'] ) . '</li>';}
							?>
						</ul>
					</div>
				<?php endif; ?>

				<?php if ( ! empty( $settings['supplies'] ) ) : ?>
					<div class="sifency-mat-col">
						<h4 class="sifency-mat-title">Supplies</h4>
						<ul>
							<?php
							foreach ( $settings['supplies'] as $supply ) {
								echo '<li>' . esc_html( $supply['item_name'] ) . '</li>';}
							?>
						</ul>
					</div>
				<?php endif; ?>
			</div>
			<?php endif; ?>

			<!-- Steps Container -->
			<div class="sifency-howto-steps-container">
				<?php
				foreach ( $settings['steps'] as $index => $step ) :
					$step_num = $index + 1;
					?>
					<div class="sifency-howto-step">
						<div class="sifency-howto-step-header">
							<span class="sifency-howto-step-count"><?php echo esc_html( $step_num ); ?></span>
							<h3 class="sifency-howto-step-title"><?php echo esc_html( $step['step_title'] ); ?></h3>
							<?php if ( 'accordion' === $settings['layout_mode'] ) : ?>
								<i class="sifency-toggle-icon eicon-plus"></i>
							<?php endif; ?>
						</div>

						<div class="sifency-howto-step-content">
							<?php if ( ! empty( $step['step_image']['url'] ) ) : ?>
								<img src="<?php echo esc_url( $step['step_image']['url'] ); ?>" alt="Step <?php echo esc_attr( $step_num ); ?>">
							<?php endif; ?>
							<div class="sifency-howto-step-text">
								<?php echo wp_kses_post( $step['step_desc'] ); ?>
							</div>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

		</div>
		<?php
	}
}
