<?php
/**
 * Dynamic rendering for the 100Prints Document block.
 */

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

if ( class_exists( 'Hundred_Prints_Block_Loader' ) ) {
	$block_loader = new Hundred_Prints_Block_Loader();
	$block_loader->force_enqueue_frontend_assets();
}

$template_id = isset( $attributes['templateId'] ) ? sanitize_text_field( $attributes['templateId'] ) : '';
$settings = function_exists( 'hundred_prints_get_settings' ) ? hundred_prints_get_settings() : [];
if ( empty( $template_id ) ) {
	echo '<div style="padding:20px; border: 2px dashed red; color: red;">100Prints Block: No Template Selected. Attributes: ' . esc_html( wp_json_encode( $attributes ) ) . '</div>';
	return;
}

$allowed_formats = [ 'pdf', 'png' ];
$allowed_quality = [ 'draft', 'standard', 'high', 'ultra' ];
$allowed_sides = [ 'front', 'back', 'both' ];

$output_format = isset( $attributes['outputFormat'] ) ? sanitize_key( $attributes['outputFormat'] ) : ( $settings['default_format'] ?? 'pdf' );
$render_quality = isset( $attributes['renderQuality'] ) ? sanitize_key( $attributes['renderQuality'] ) : ( $settings['default_quality'] ?? 'high' );
$render_side = isset( $attributes['renderSide'] ) ? sanitize_key( $attributes['renderSide'] ) : ( $settings['default_side'] ?? 'both' );

$output_format = in_array( $output_format, $allowed_formats, true ) ? $output_format : ( $settings['default_format'] ?? 'pdf' );
$render_quality = in_array( $render_quality, $allowed_quality, true ) ? $render_quality : ( $settings['default_quality'] ?? 'high' );
$render_side = in_array( $render_side, $allowed_sides, true ) ? $render_side : ( $settings['default_side'] ?? 'both' );

$config = [
	'templateId'     => $template_id,
	'templateSource' => isset( $attributes['templateSource'] ) ? sanitize_key( $attributes['templateSource'] ) : 'bundled',
	'buttonLabel'    => isset( $attributes['buttonLabel'] ) ? sanitize_text_field( $attributes['buttonLabel'] ) : 'Download Document',
	'showPreview'    => isset( $attributes['showPreview'] ) ? (bool) $attributes['showPreview'] : false,
	'requireLogin'   => isset( $attributes['requireLogin'] ) ? (bool) $attributes['requireLogin'] : false,
	'outputFormat'   => $output_format,
	'renderQuality'  => $render_quality,
	'renderSide'     => $render_side,
	'outputFilename' => isset( $attributes['outputFilename'] ) && $attributes['outputFilename'] !== '' ? sanitize_text_field( $attributes['outputFilename'] ) : ( $settings['filename_pattern'] ?? '{template_name}_{date}' ),
	'variables'      => [],
];

$expires = time() + 3600; // 1 hour expiry
$config['expires'] = $expires;
$config['signature'] = hash_hmac( 'sha256', $template_id . '|' . $expires . '|fetch', wp_salt( 'auth' ) );
$config['logSignature'] = hash_hmac( 'sha256', $template_id . '|' . $expires . '|log', wp_salt( 'auth' ) );

$template_name = $template_id;
$template_variable_count = 0;
if ( class_exists( 'Hundred_Prints_Template_Service' ) ) {
	$template_service = new Hundred_Prints_Template_Service();
	$template_data = $template_service->get_template( $template_id );
	if ( is_array( $template_data ) ) {
		$template_name = isset( $template_data['name'] ) ? sanitize_text_field( $template_data['name'] ) : $template_name;
		
		// Unwrap cloud templates which nest the document inside 'template_data'
		$doc = isset( $template_data['template_data'] ) ? $template_data['template_data'] : $template_data;
		
		if ( isset( $doc['sample_data']['headers'] ) && is_array( $doc['sample_data']['headers'] ) ) {
			$template_variable_count = count( $doc['sample_data']['headers'] );
		} elseif ( isset( $doc['variables'] ) && is_array( $doc['variables'] ) ) {
			$template_variable_count = count( $doc['variables'] );
		}
	}
}

$config['templateName'] = $template_name;
$config['variableCount'] = $template_variable_count;
$config['outputFilename'] = hundred_prints_format_filename(
	$config['outputFilename'],
	[
		'template_name' => $template_name,
		'template_id'   => $template_id,
		'post_title'    => get_the_ID() ? get_the_title( get_the_ID() ) : '',
		'post_id'       => get_the_ID() ?: '',
	]
);

// Resolve variables based on mapping
$variable_map = isset( $attributes['variableMap'] ) && is_array( $attributes['variableMap'] ) ? $attributes['variableMap'] : [];
$post_id = get_the_ID();

// Include the raw variableMap in config for the frontend to process manual inputs
$config['variableMap'] = $variable_map;

$stringify_value = static function ( $value ) {
	if ( is_scalar( $value ) || null === $value ) {
		return sanitize_text_field( (string) $value );
	}

	return sanitize_text_field( wp_json_encode( $value ) );
};

if ( class_exists( 'Hundred_Prints_Payload_Resolver' ) ) {
	$resolver = new Hundred_Prints_Payload_Resolver();
	foreach ( $resolver->resolve( $variable_map, $post_id ) as $key => $value ) {
		$config['variables'][ sanitize_text_field( $key ) ] = $stringify_value( $value );
	}
}

$preset = isset( $attributes['appearancePreset'] ) ? $attributes['appearancePreset'] : 'inherit';
$classes = [
	'hp-block-document',
	'hp-appearance--' . $preset,
];

$wrapper_attributes = get_block_wrapper_attributes( [
	'class' => implode( ' ', $classes ),
	'data-hundredp-config' => wp_json_encode( $config ),
] );

$button_variant = ! empty( $attributes['buttonVariant'] ) ? sanitize_key( $attributes['buttonVariant'] ) : 'primary';
$button_width = ! empty( $attributes['buttonWidth'] ) ? sanitize_key( $attributes['buttonWidth'] ) : 'auto';
$button_icon = ! empty( $attributes['buttonIcon'] ) && $attributes['buttonIcon'] !== 'none' ? sanitize_key( $attributes['buttonIcon'] ) : '';

// Parse button width class
$btn_classes = [ 'hundredp-block-btn' ];
if ( ! empty( $attributes['buttonWidth'] ) && $attributes['buttonWidth'] === 'full' ) {
	$btn_classes[] = 'hundredp-btn-full';
}
// Parse button variant class
$btn_classes[] = 'hundredp-btn-' . $button_variant;

// Check if there are manual inputs
$has_manual_inputs = false;
foreach ( $variable_map as $mapping ) {
	if ( isset( $mapping['source'] ) && in_array( $mapping['source'], [ 'manual', 'manual_visitor_input' ], true ) ) {
		$has_manual_inputs = true;
		break;
	}
}

ob_start();
?>
<div <?php echo $wrapper_attributes; ?>>
	<div class="hundredp-document-card">
		<?php if ( $config['showPreview'] ) : ?>
			<div class="hundredp-preview-summary-card">
				<div class="hundredp-preview-canvas">
					<div class="hundredp-sdk-mount-point hundredp-frontend-preview-wrap">
						<div class="hundredp-preview-loading"><?php esc_html_e( 'Preview opens before download.', '100prints' ); ?></div>
					</div>
				</div>
				<div class="hundredp-card-title-row">
					<span class="dashicons dashicons-media-document" aria-hidden="true"></span>
					<h4><?php echo esc_html( $template_name ); ?></h4>
				</div>
				<div class="hundredp-card-meta-grid">
					<div>
						<strong><?php esc_html_e( 'Format', '100prints' ); ?></strong>
						<?php echo esc_html( strtoupper( $config['outputFormat'] ) ); ?>
					</div>
					<div>
						<strong><?php esc_html_e( 'Variables mapped', '100prints' ); ?></strong>
						<?php echo esc_html( count( $config['variables'] ) . ' / ' . $template_variable_count ); ?>
					</div>
				</div>
			</div>
		<?php endif; ?>

		<form class="hundredp-manual-inputs-form"></form>

		<div class="hundredp-button-group">
			<?php if ( ! empty( $attributes['showPreviewButton'] ) ) : ?>
				<button class="hundredp-preview-btn <?php echo esc_attr( implode( ' ', $btn_classes ) ); ?>" type="button">
					<?php esc_html_e( 'Preview Document', '100prints' ); ?>
				</button>
			<?php endif; ?>
			
			<?php 
			$btn_style = '';
			if ( ! empty( $attributes['buttonColor'] ) ) {
				$color = sanitize_hex_color( $attributes['buttonColor'] );
				if ( $color ) {
					// We set both variables to the same color to ensure it overrides defaults.
					// Alternatively, the user can use standard CSS filters on hover in the future.
					$btn_style = sprintf( '--hundredp-accent: %1$s; --hundredp-accent-hover: %1$s;', esc_attr( $color ) );
				}
			}
			?>
			<button class="hundredp-download-btn <?php echo esc_attr( implode( ' ', $btn_classes ) ); ?>" type="button" <?php echo $btn_style ? 'style="' . $btn_style . '"' : ''; ?>>
				<?php if ( $button_icon ) : ?>
					<span class="dashicons dashicons-<?php echo esc_attr( $button_icon ); ?>" aria-hidden="true"></span>
				<?php endif; ?>
				<span><?php echo esc_html( $config['buttonLabel'] ); ?></span>
			</button>
		</div>
	</div>
</div>
<?php
echo ob_get_clean();
