<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Icons_Manager;
use Sifency\Traits\Sifency_Animation_Controls; 
use Sifency\Traits\Sifency_Animation_Manager;  

class Sifency_Widget_Digital_Downloads extends Widget_Base {
	use Sifency_Animation_Controls;

	public function get_name() { return 'sifency-digital-downloads'; }
	public function get_title() { return esc_html__( 'Product Downloads', 'sifency-addons' ); }
	public function get_icon() { return 'eicon-meta-data'; }
	public function get_categories() { return [ 'sifency-digital-components' ]; }
	public function get_keywords() { return [ 'download', 'file', 'product', 'repeater', 'meta', 'dynamic', 'sifency' ]; }

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

		// --- Style Tab: List Items ---
		$this->start_controls_section( 'section_list_style', [ 'label' => esc_html__( 'List Items', 'sifency-addons' ), 'tab' => Controls_Manager::TAB_STYLE ] );
		$this->add_control( 'item_bg_color', [ 'label' => 'Background', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-download-item' => 'background-color: {{VALUE}};' ] ] );
		$this->add_control( 'item_border_color', [ 'label' => 'Border Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-download-item' => 'border-bottom-color: {{VALUE}};' ] ] );
		$this->add_responsive_control( 'item_padding', [ 'label' => 'Padding', 'type' => Controls_Manager::DIMENSIONS, 'selectors' => [ '{{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', [ 'label' => esc_html__( 'Text & Info', 'sifency-addons' ), 'tab' => Controls_Manager::TAB_STYLE ] );
		$this->add_control( 'heading_file_name', [ 'label' => 'File Name', 'type' => Controls_Manager::HEADING ] );
		$this->add_control( 'file_name_color', [ 'label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-download-name' => 'color: {{VALUE}};' ] ] );
		$this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'file_name_typography', 'selector' => '{{WRAPPER}} .sifency-download-name' ] );
		
		$this->add_control( 'heading_file_info', [ 'label' => 'File Info (Size/Type)', 'type' => Controls_Manager::HEADING, 'separator' => 'before' ] );
		$this->add_control( 'file_info_color', [ 'label' => 'Color', 'type' => Controls_Manager::COLOR, 'selectors' => [ '{{WRAPPER}} .sifency-download-info' => 'color: {{VALUE}};' ] ] );
		$this->add_group_control( Group_Control_Typography::get_type(), [ 'name' => 'file_info_typography', 'selector' => '{{WRAPPER}} .sifency-download-info' ] );
		$this->end_controls_section();

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

		$this->add_sifency_animation_controls();
	}

    protected function render() {
		$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 = [
					[ 'file_name' => 'Main Product File (Uploaded)', 'file_upload' => '', 'file_link' => '' ],
					[ 'file_name' => 'Documentation (External Link)', 'file_upload' => '', 'file_link' => 'https://example.com/docs.pdf' ],
					[ 'file_name' => 'License Agreement (.txt)', 'file_upload' => '', 'file_link' => '' ],
				];
			} else {
				return;
			}
		}

		$animation_manager = new Sifency_Animation_Manager( $settings );
		$animation_attrs   = $animation_manager->get_wrapper_attributes( [] );

		?>
		<div 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 = '#'; // Default to a safe fallback
					$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'], [ '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'; // Default icon
		}
		
		$icon_map = [
			'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'; // Fallback for unknown types
	}
}