<?php
/**
 * Shortcode handler for [100prints] fallback rendering.
 *
 * @package    100Prints
 */

class Hundred_Prints_Shortcode {

	/**
	 * Render shortcode output.
	 */
	public function render_shortcode( $atts ) {
		$args = shortcode_atts( [
			'template'      => '',
			'button_label'  => 'Download Document',
			'button_icon'   => '',
			'show_preview'  => '0',
			'require_login' => '0',
		], $atts, '100prints' );

		$template_id = hundred_prints_sanitize_template_id( $args['template'] );
		if ( empty( $template_id ) ) {
			return '<p style="color:red; font-size:12px;">[100Prints: Missing template ID]</p>';
		}

		// Resolve template details to determine if cloud/bundled
		$template_service = new Hundred_Prints_Template_Service();
		$template = $template_service->get_template( $template_id );
		if ( ! $template || is_wp_error( $template ) ) {
			return '<p style="color:red; font-size:12px;">[100Prints: Template not found]</p>';
		}

		$source = isset( $template['source'] ) ? $template['source'] : 'bundled';
		$settings = hundred_prints_get_settings();
		$template_name = isset( $template['name'] ) ? sanitize_text_field( $template['name'] ) : $template_id;

		// Construct variable map from registry-owned fallback rules.
		if ( isset( $template['sample_data']['headers'] ) && is_array( $template['sample_data']['headers'] ) ) {
			$variables = $template['sample_data']['headers'];
		} else {
			$variables = isset( $template['variables'] ) && is_array( $template['variables'] ) ? $template['variables'] : [];
		}

		$variable_map = hundred_prints_get_variable_source_registry()->get_default_variable_map( $variables );

		$config = [
			'templateId'     => $template_id,
			'templateSource' => $source,
			'variableMap'    => $variable_map,
			'variables'      => [],
			'buttonLabel'    => sanitize_text_field( $args['button_label'] ),
			'showPreview'    => filter_var( $args['show_preview'], FILTER_VALIDATE_BOOLEAN ),
			'requireLogin'   => filter_var( $args['require_login'], FILTER_VALIDATE_BOOLEAN ),
			'outputFormat'   => $settings['default_format'],
			'renderQuality'  => $settings['default_quality'],
			'renderSide'     => $settings['default_side'],
			'templateName'   => $template_name,
			'outputFilename' => hundred_prints_format_filename(
				$settings['filename_pattern'],
				[
					'template_name' => $template_name,
					'template_id'   => $template_id,
				]
			),
		];

		$resolver = new Hundred_Prints_Payload_Resolver();
		foreach ( $resolver->resolve( $variable_map, get_the_ID() ) as $key => $value ) {
			$config['variables'][ sanitize_text_field( $key ) ] = is_scalar( $value ) || null === $value ? sanitize_text_field( (string) $value ) : sanitize_text_field( wp_json_encode( $value ) );
		}

		// Ensure visitor assets (scripts & styles) are enqueued
		$block_loader = new Hundred_Prints_Block_Loader();
		$block_loader->force_enqueue_frontend_assets();

		// Renders identical block structure to ensure frontend.js handles it seamlessly
		ob_start();
		?>
		<div class="wp-block-100prints-document" data-hundredp-config="<?php echo esc_attr( wp_json_encode( $config ) ); ?>" style="margin: 20px 0;">
			<?php if ( $config['showPreview'] ) : ?>
				<div class="hundredp-preview-wrap"></div>
			<?php endif; ?>
			
			<button class="hundredp-download-btn" type="button">
				<?php if ( ! empty( $args['button_icon'] ) && $args['button_icon'] !== 'none' ) : ?>
					<span class="dashicons dashicons-<?php echo esc_attr( sanitize_key( $args['button_icon'] ) ); ?>" aria-hidden="true"></span>
				<?php endif; ?>
				<span><?php echo esc_html( $config['buttonLabel'] ); ?></span>
			</button>
		</div>
		<?php
		return ob_get_clean();
	}
}
