<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
use Elementor\Widget_Base;
use Sifency\Classes\Sifency_Addons_Widget_Base;
use Sifency\Classes\Sifency_Themebuilder_Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Icons_Manager;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Addons_Help_Controls;
class Sifency_Widget_Digital_Downloads extends Sifency_Themebuilder_Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Help_Controls;

	protected function get_allowed_template_types() {
		return 'digital';
	}
	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'     => 'sifency-digital-downloads',
			'title'    => 'Product Downloads',
			'icon'     => 'eicon-meta-data',
			'category' => array( 'sifency-digital-components' ),
			'keywords' => array( 'download', 'file', 'product', 'repeater', 'meta', 'dynamic', 'sifency' ),
		);}

	protected function register_controls() {
		// --- Content Tab: List Settings ---
		$this->start_controls_section( 'section_list_content', array( 'label' => esc_html__( 'List Settings', 'sifency-addons' ) ) );
		$this->add_control(
			'show_file_icon',
			array(
				'label'   => 'Show File Icon',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->add_control(
			'show_file_size',
			array(
				'label'   => 'Show File Size',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->add_control(
			'show_file_type',
			array(
				'label'   => 'Show File Type',
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'no',
			)
		);
		$this->add_control(
			'download_icon',
			array(
				'label'   => esc_html__( 'Download Icon', 'sifency-addons' ),
				'type'    => Controls_Manager::ICONS,
				'default' => array(
					'value'   => 'fas fa-download',
					'library' => 'fa-solid',
				),
			)
		);
		$this->end_controls_section();
		$this->add_sifency_addons_help_controls();

		// --- Style Tab: List Items ---
		$this->start_controls_section(
			'section_list_style',
			array(
				'label' => esc_html__( 'List Items', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);
		$this->add_control(
			'item_bg_color',
			array(
				'label'     => 'Background',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-download-item' => 'background-color: {{VALUE}};' ),
			)
		);
		$this->add_control(
			'item_border_color',
			array(
				'label'     => 'Border Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-download-item' => 'border-bottom-color: {{VALUE}};' ),
			)
		);
		$this->add_responsive_control(
			'item_padding',
			array(
				'label'     => 'Padding',
				'type'      => Controls_Manager::DIMENSIONS,
				'selectors' => array( '{{WRAPPER}} .sifency-download-item' => 'padding: {{TOP}}px {{RIGHT}}px {{BOTTOM}}px {{LEFT}}px;' ),
			)
		);
		$this->end_controls_section();

		// --- Style Tab: Text & Info ---
		$this->start_controls_section(
			'section_text_style',
			array(
				'label' => esc_html__( 'Text & Info', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);
		$this->add_control(
			'heading_file_name',
			array(
				'label' => 'File Name',
				'type'  => Controls_Manager::HEADING,
			)
		);
		$this->add_control(
			'file_name_color',
			array(
				'label'     => 'Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-download-name' => 'color: {{VALUE}};' ),
			)
		);
		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'file_name_typography',
				'selector' => '{{WRAPPER}} .sifency-download-name',
			)
		);

		$this->add_control(
			'heading_file_info',
			array(
				'label'     => 'File Info (Size/Type)',
				'type'      => Controls_Manager::HEADING,
				'separator' => 'before',
			)
		);
		$this->add_control(
			'file_info_color',
			array(
				'label'     => 'Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-download-info' => 'color: {{VALUE}};' ),
			)
		);
		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'file_info_typography',
				'selector' => '{{WRAPPER}} .sifency-download-info',
			)
		);
		$this->end_controls_section();

		// --- Style Tab: Icon ---
		$this->start_controls_section(
			'section_icon_style',
			array(
				'label' => esc_html__( 'Icons', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);
		$this->add_control(
			'icon_color',
			array(
				'label'     => 'Color',
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .sifency-download-icon i' => 'color: {{VALUE}};' ),
			)
		);
		$this->add_responsive_control(
			'icon_size',
			array(
				'label'     => 'Size',
				'type'      => Controls_Manager::SLIDER,
				'selectors' => array( '{{WRAPPER}} .sifency-download-icon i' => 'font-size: {{SIZE}}px;' ),
			)
		);
		$this->end_controls_section();
		$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();

		$download_list = sifency_get_field( 'digital_files' );

		if ( empty( $download_list ) ) {
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				$download_list = array(
					array(
						'file_name'   => 'Main Product File (Uploaded)',
						'file_upload' => '',
						'file_link'   => '',
					),
					array(
						'file_name'   => 'Documentation (External Link)',
						'file_upload' => '',
						'file_link'   => 'https://example.com/docs.pdf',
					),
					array(
						'file_name'   => 'License Agreement (.txt)',
						'file_upload' => '',
						'file_link'   => '',
					),
				);
			} else {
				return;
			}
		}
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );
		$animation_attrs   = $animation_manager->get_wrapper_attributes( array() ); ?>
		<div id="<?php echo esc_attr ( $wrapper_id ); ?>" class="sifency-downloads-wrapper" <?php echo $animation_attrs; // phpcs:ignore ?>>
			<div class="sifency-downloads-list">
				<?php
				foreach ( $download_list as $item ) :
					if ( empty( $item['file_name'] ) ) {
						continue;
					}

					$file_url    = '#';
					$file_id     = $item['file_upload'] ?? '';
					$is_external = false;

					if ( ! empty( $file_id ) ) {
						$file_url = wp_get_attachment_url( $file_id );
					} elseif ( ! empty( $item['file_link'] ) ) {
						$file_url    = $item['file_link'];
						$is_external = true;
					}

					if ( '#' === $file_url ) {
						continue;
					}

					?>
					<div class="sifency-download-item">
						<?php if ( 'yes' === $settings['show_file_icon'] ) : ?>
							<div class="sifency-download-icon">
								<i class="<?php echo esc_attr( $this->get_file_icon_class( $file_id, $file_url ) ); ?>"></i>
							</div>
						<?php endif; ?>
						
						<div class="sifency-download-details">
							<span class="sifency-download-name"><?php echo esc_html( $item['file_name'] ); ?></span>
							<?php if ( ( 'yes' === $settings['show_file_size'] && ! $is_external ) || 'yes' === $settings['show_file_type'] ) : ?>
								<div class="sifency-download-info">
									<?php
									if ( 'yes' === $settings['show_file_type'] ) {
										$file_ext = pathinfo( $file_url, PATHINFO_EXTENSION );
										if ( $file_ext ) {
											echo '<span class="sifency-download-file-type">' . esc_html( strtoupper( $file_ext ) ) . '</span>';
										}
									}
									if ( 'yes' === $settings['show_file_size'] && ! $is_external && $file_id ) {
										echo '<span class="sifency-download-file-size">' . esc_html( sifency_get_formatted_attachment_size( $file_id ) ) . '</span>';
									}
									?>
								</div>
							<?php endif; ?>
						</div>

						<a href="<?php echo esc_url( $file_url ); ?>" 
							class="sifency-download-button" 
							<?php echo $is_external ? 'target="_blank" rel="noopener noreferrer"' : 'download'; ?>>
							<?php Icons_Manager::render_icon( $settings['download_icon'], array( 'aria-hidden' => 'true' ) ); ?>
						</a>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Helper function to determine a Font Awesome icon class based on file type.
	 * Can derive type from attachment ID or a URL.
	 *
	 * @param int    $attachment_id
	 * @param string $file_url
	 * @return string
	 */
	protected function get_file_icon_class( $attachment_id = 0, $file_url = '' ) {
		$extension = '';
		if ( $attachment_id ) {
			$mime_type = get_post_mime_type( $attachment_id );
			if ( $mime_type ) {
				$parts     = explode( '/', $mime_type );
				$extension = end( $parts );
			}
		} elseif ( $file_url ) {
			$extension = strtolower( pathinfo( $file_url, PATHINFO_EXTENSION ) );
		}

		if ( ! $extension ) {
			return 'fas fa-file';
		}

		$icon_map = array(
			'image'      => 'fas fa-file-image',
			'jpg'        => 'fas fa-file-image',
			'jpeg'       => 'fas fa-file-image',
			'png'        => 'fas fa-file-image',
			'gif'        => 'fas fa-file-image',
			'audio'      => 'fas fa-file-audio',
			'mp3'        => 'fas fa-file-audio',
			'wav'        => 'fas fa-file-audio',
			'video'      => 'fas fa-file-video',
			'mp4'        => 'fas fa-file-video',
			'mov'        => 'fas fa-file-video',
			'pdf'        => 'fas fa-file-pdf',
			'word'       => 'fas fa-file-word',
			'doc'        => 'fas fa-file-word',
			'docx'       => 'fas fa-file-word',
			'excel'      => 'fas fa-file-excel',
			'xls'        => 'fas fa-file-excel',
			'xlsx'       => 'fas fa-file-excel',
			'powerpoint' => 'fas fa-file-powerpoint',
			'ppt'        => 'fas fa-file-powerpoint',
			'pptx'       => 'fas fa-file-powerpoint',
			'archive'    => 'fas fa-file-archive',
			'zip'        => 'fas fa-file-archive',
			'rar'        => 'fas fa-file-archive',
			'code'       => 'fas fa-file-code',
			'html'       => 'fas fa-file-code',
			'css'        => 'fas fa-file-code',
			'js'         => 'fas fa-file-code',
			'text'       => 'fas fa-file-alt',
			'txt'        => 'fas fa-file-alt',
		);

		foreach ( $icon_map as $type => $icon ) {
			if ( strpos( $extension, $type ) !== false ) {
				return $icon;
			}
		}

		return 'fas fa-file';
	}
}
