<?php
// phpcs:disable WordPress.DB.PreparedSQL -- WordPress placeholders do not support internal table identifiers.
/**
 * Enhanced Preview Helper Class
 * Provides server-side preview content generation for accurate frontend representation
 */

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

class Instant_Popup_Builder_Enhanced_Preview {

    /**
     * Generate preview content for different popup types
     */
    public static function generate_preview_content($popup_type, $content_data = []) {
        switch ($popup_type) {
            case 'popup_text':
                return self::generate_text_preview($content_data);
            case 'popup_html':
                return self::generate_html_preview($content_data);
            case 'popup_image':
                return self::generate_image_preview($content_data);
            case 'popup_subscription':
                return self::generate_subscription_preview($content_data);
            default:
                return self::generate_default_preview($content_data);
        }
    }

    /**
     * Generate text popup preview
     */
    private static function generate_text_preview($data) {
        $content = isset($data['content']) && is_string($data['content']) ? $data['content'] : '<p>Enter your text content here...</p>';
        $background_selection = isset($data['background_selection']) ? sanitize_key($data['background_selection']) : '';
        $background_color = isset($data['background_color']) ? sanitize_hex_color($data['background_color']) : '';
        $background_color = $background_color ?: '#ffffff';
        $background_image = isset($data['background_image']) ? esc_url_raw($data['background_image']) : '';
        $background_size = isset($data['background_size']) && in_array($data['background_size'], ['cover', 'contain', 'none', 'unset'], true) ? $data['background_size'] : 'cover';
        $background_opacity = isset($data['background_opacity']) ? min(1, max(0, (float) $data['background_opacity'])) : 1;
        $text_color = isset($data['text_color']) ? sanitize_hex_color($data['text_color']) : '';
        $text_color = $text_color ?: '#333333';
        $text_padding_top = isset($data['text_padding_top']) ? min(100, absint($data['text_padding_top'])) : 20;
        $text_padding_right = isset($data['text_padding_right']) ? min(100, absint($data['text_padding_right'])) : 25;
        $text_padding_bottom = isset($data['text_padding_bottom']) ? min(100, absint($data['text_padding_bottom'])) : 20;
        $text_padding_left = isset($data['text_padding_left']) ? min(100, absint($data['text_padding_left'])) : 25;
        $text_border_radius = isset($data['text_border_radius']) ? min(30, absint($data['text_border_radius'])) : 12;
        $text_font_size = isset($data['text_font_size']) ? min(24, max(12, absint($data['text_font_size']))) : 16;
        $text_line_height = isset($data['text_line_height']) ? min(2.0, max(1.2, (float) $data['text_line_height'])) : 1.5;
        $border_enabled = isset($data['border_enabled']) && 'yes' === $data['border_enabled'];
        $border_width = isset($data['border_width']) ? min(40, absint($data['border_width'])) : 1;
        $border_color = isset($data['border_color']) ? sanitize_hex_color($data['border_color']) : '';
        $border_color = $border_color ?: '#111827';
        $width = isset($data['design_width']) ? absint($data['design_width']) : 0;
        $height = isset($data['design_height']) ? absint($data['design_height']) : 0;
        $percentage = isset($data['design_percentage']) ? min(100, max(10, absint($data['design_percentage']))) : 50;
        $percentage_mode = isset($data['design_percentage_toggle']) && 'yes' === $data['design_percentage_toggle'];

        $styles = [
            'position:relative',
            'box-sizing:border-box',
            'overflow:visible',
            'color:' . $text_color,
            'padding:' . $text_padding_top . 'px ' . $text_padding_right . 'px ' . $text_padding_bottom . 'px ' . $text_padding_left . 'px',
            'border-radius:' . $text_border_radius . 'px',
            'font-size:' . $text_font_size . 'px',
            'line-height:' . $text_line_height,
            'max-width:95vw',
            'max-height:85vh',
            'margin:0 auto',
        ];

        if ('image' === $background_selection && $background_image) {
            $styles[] = "background-image:url('" . esc_url($background_image) . "')";
            $styles[] = 'background-position:center center';
            $styles[] = 'background-size:' . $background_size;
            $styles[] = 'background-repeat:no-repeat';
        } else {
            $styles[] = 'background-color:' . ('color' === $background_selection ? $background_color : '#ffffff');
        }
        if ($background_opacity < 1) {
            $styles[] = 'opacity:' . $background_opacity;
        }
        $styles[] = $border_enabled ? 'border:' . $border_width . 'px solid ' . $border_color : 'border:none';
        if ($percentage_mode) {
            $styles[] = 'width:' . $percentage . '%';
        } elseif ($width > 0) {
            $styles[] = 'width:' . $width . 'px';
        } else {
            $styles[] = 'width:min(90%, 600px)';
        }
        if (!$percentage_mode && $height > 0) {
            $styles[] = 'height:auto';
            $styles[] = 'max-height:min(' . $height . 'px, 85vh)';
        }

        return sprintf(
            '<div class="intant-popup-type-text instant-popup-content ipb-text-custom-styled ipb-close-at-right" style="%s">
                <button type="button" class="instant-cross" aria-label="%s"><i class="fa-solid fa-xmark" aria-hidden="true"></i></button>
                <div class="inner_content" style="overflow:auto;max-height:%s;scrollbar-width:thin;">%s</div>
            </div>',
            esc_attr(implode(';', $styles)),
            esc_attr__('Close preview popup', 'instant-popup-builder'),
            esc_attr(!$percentage_mode && $height > 0 ? 'calc(min(' . $height . 'px, 85vh) - ' . ($text_padding_top + $text_padding_bottom) . 'px)' : '100%'),
            wp_kses($content, ipb_get_allowed_html_text_popup_content())
        );
    }

    /**
     * Generate HTML popup preview
     */
    private static function generate_html_preview($data) {
        $content = isset($data['content']) && is_string($data['content']) ? $data['content'] : '<p>Enter your HTML content here...</p>';

        return sprintf(
            '<div class="instant-popup-content" style="background: transparent; padding: 0; max-width: 90vw; max-height: 90vh;">
                <div class="instant-cross" style="position: absolute; top: 10px; right: 10px; cursor: pointer; color: #666; z-index: 1000;">
                    <i class="fa-solid fa-circle-xmark"></i>
                </div>
                <div class="inner_content" style="overflow: visible;">%s</div>
            </div>',
            wp_kses_post(is_string($content) ? $content : '')
        );
    }

    /**
     * Generate image popup preview
     */
    private static function generate_image_preview($data) {
        $image_url = isset($data['image_url']) ? $data['image_url'] : '';

        if (empty($image_url)) {
            return '<div class="instant-popup-content" style="background: #f5f5f5; padding: 50px; text-align: center; border-radius: 8px; max-width: 500px; margin: 0 auto;">
                <p>Upload an image to see preview...</p>
            </div>';
        }

        return sprintf(
            '<div class="instant-popup-content" style="background: transparent; padding: 0; max-width: 90vw; max-height: 90vh;">
                <div class="instant-cross" style="position: absolute; top: 10px; right: 10px; cursor: pointer; color: #fff; z-index: 1000; background: rgba(0,0,0,0.5); border-radius: 50%%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;">
                    <i class="fa-solid fa-times"></i>
                </div>
                <img src="%s" style="width: 100%%; max-width: 800px; height: auto; border-radius: 8px; display: block; margin: 0 auto;" alt="Preview Image" />
            </div>',
            esc_url($image_url)
        );
    }

    /**
     * Generate subscription popup preview
     */
    private static function generate_subscription_preview($data) {
        $title = isset($data['title']) ? $data['title'] : 'Subscribe to Our Newsletter';
        $description = isset($data['description']) ? $data['description'] : 'Get the latest updates and news delivered to your inbox.';
        $button_text = isset($data['button_text']) ? $data['button_text'] : 'Subscribe Now';
        $button_color = isset($data['button_color']) ? $data['button_color'] : '#3b82f6';
        $image_url = isset($data['image_url']) ? $data['image_url'] : '';
        $image_position = isset($data['image_position']) ? $data['image_position'] : 'right';

        $image_section = '';
        if (!empty($image_url)) {
            $image_section = sprintf(
                '<div class="newsletter-image-section" style="flex: 0 0 320px; background: linear-gradient(135deg, #f8f9fa 0%%, #e9ecef 100%%); display: flex; align-items: center; justify-content: center; position: relative; overflow: hidden;">
                    <div class="image-wrapper" style="width: 100%%; height: 100%%; display: flex; align-items: center; justify-content: center;">
                        <img src="%s" alt="Newsletter" class="newsletter-image" style="width: 100%%; height: 100%%; object-fit: cover; object-position: center;" />
                    </div>
                </div>',
                esc_url($image_url)
            );
        }

        $container_class = !empty($image_url) ? 'basic-newsletter-container has-image image-' . $image_position : 'basic-newsletter-container';

        return sprintf(
            '<div class="%s" style="display: flex; background: #ffffff; border-radius: 12px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12); overflow: visible; max-width: 850px; width: 100%%; margin: 0 auto; font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', Arial, sans-serif; min-height: 480px; position: relative;">
                <div class="instant-cross" style="position: absolute; top: 10px; right: 10px; cursor: pointer; color: #666; z-index: 1000; background: rgba(255,255,255,0.9); border-radius: 50%%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;">
                    <i class="fa-solid fa-times"></i>
                </div>
                %s
                <div class="newsletter-content-section" style="flex: 1; display: flex; align-items: center; min-height: 480px; padding: 0;">
                    <div class="content-wrapper" style="width: 100%%; padding: 50px 45px; max-width: 100%%;">
                        <div class="newsletter-header" style="margin-bottom: 35px; text-align: center;">
                            <h2 class="newsletter-title" style="font-size: 32px; font-weight: 700; color: #1a1a1a; margin: 0 0 16px 0; line-height: 1.2; letter-spacing: -0.5px;">%s</h2>
                            <p class="newsletter-description" style="font-size: 16px; color: #6c757d; margin: 0; line-height: 1.5; font-weight: 400;">%s</p>
                        </div>
                        <form class="newsletter-form" style="width: 100%%;">
                            <div class="form-row" style="margin-bottom: 20px;">
                                <label class="form-label" for="preview_first_name" style="display: block; font-size: 14px; font-weight: 600; color: #374151; margin-bottom: 8px; letter-spacing: 0.025em;">Full Name</label>
                                <input type="text" id="preview_first_name" name="first_name" placeholder="Enter your full name" class="form-input" style="width: 100%%; padding: 16px 18px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 16px; font-weight: 400; color: #374151; background: #ffffff; box-sizing: border-box;" readonly>
                            </div>
                            <div class="form-row" style="margin-bottom: 20px;">
                                <label class="form-label" for="preview_email" style="display: block; font-size: 14px; font-weight: 600; color: #374151; margin-bottom: 8px; letter-spacing: 0.025em;">Email Address</label>
                                <input type="email" id="preview_email" name="email_address" placeholder="Enter your email address" class="form-input" style="width: 100%%; padding: 16px 18px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 16px; font-weight: 400; color: #374151; background: #ffffff; box-sizing: border-box;" readonly>
                            </div>
                            <div class="form-row privacy-row" style="margin-bottom: 25px;">
                                <label class="privacy-label" style="display: flex; align-items: flex-start; gap: 12px; cursor: pointer; font-size: 14px; line-height: 1.5; color: #6b7280;">
                                    <input type="checkbox" class="privacy-checkbox" style="appearance: none; width: 18px; height: 18px; border: 2px solid #d1d5db; border-radius: 4px; background: #ffffff; margin: 0; flex-shrink: 0; margin-top: 2px;" disabled>
                                    <span class="privacy-text">I agree to the <a href="#" target="_blank" style="color: #3b82f6; text-decoration: none; font-weight: 500;">Privacy Policy</a></span>
                                </label>
                            </div>
                            <div class="form-row submit-row" style="margin-bottom: 10px; margin-top: 30px;">
                                <button type="button" class="newsletter-submit-btn" style="width: 100%%; background: %s; color: #ffffff; border: none; padding: 18px 24px; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; letter-spacing: 0.025em; text-transform: none;" disabled>%s</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>',
            esc_attr($container_class),
            $image_section,
            esc_html($title),
            esc_html($description),
            esc_attr($button_color),
            esc_html($button_text)
        );
    }

	/**
	 * Decode JSON column that stores a single encoded string (e.g. text/HTML body or image URL).
	 *
	 * @param string $raw Raw DB column value.
	 * @return string
	 */
	private static function decode_content_json_string( $raw ) {
		if ( ! is_string( $raw ) || $raw === '' ) {
			return '';
		}
		$trim = trim( $raw );
		$decoded = json_decode( $trim, true );
		if ( JSON_ERROR_NONE === json_last_error() && is_string( $decoded ) ) {
			return $decoded;
		}
		$decoded_obj = json_decode( $trim );
		if ( JSON_ERROR_NONE === json_last_error() && is_string( $decoded_obj ) ) {
			return $decoded_obj;
		}
		return '';
	}

	/**
	 * Decode design / advance JSON columns to associative arrays.
	 *
	 * @param string $raw Raw JSON string.
	 * @return array<string, mixed>
	 */
	private static function decode_json_object_column( $raw ) {
		if ( ! is_string( $raw ) || $raw === '' ) {
			return [];
		}
		$decoded = json_decode( $raw, true );
		return is_array( $decoded ) ? $decoded : [];
	}

	/**
	 * Build enhanced preview payload from a database row (dashboard list).
	 *
	 * @param object $row Popup row object.
	 * @return array{popup_type: string, content_data: array<string, mixed>}|null Null = use legacy inline modal.
	 */
	public static function build_dashboard_preview_parts( $row ) {
		if ( ! is_object( $row ) || empty( $row->type ) ) {
			return null;
		}
		$type    = (string) $row->type;
		$design  = self::decode_json_object_column( isset( $row->design ) ? (string) $row->design : '' );
		$advance = self::decode_json_object_column( isset( $row->advance ) ? (string) $row->advance : '' );

		switch ( $type ) {
			case 'text':
				$body = self::decode_content_json_string( isset( $row->content ) ? (string) $row->content : '' );
				return [
					'popup_type'   => 'popup_text',
					'content_data' => [
						'content'            => '' !== $body ? $body : '<p></p>',
						'background_selection'=> isset( $design['background_selection'] ) ? (string) $design['background_selection'] : '',
						'background_color'   => isset( $design['background_color'] ) ? (string) $design['background_color'] : '#ffffff',
						'background_image'   => isset( $design['background_image'] ) ? (string) $design['background_image'] : '',
						'background_size'    => isset( $design['back_image_size'] ) ? (string) $design['back_image_size'] : 'cover',
						'background_opacity' => isset( $design['background_selection'] ) && 'image' === $design['background_selection']
							? ( isset( $design['backimage_opacity'] ) ? (float) $design['backimage_opacity'] : 1 )
							: ( isset( $design['backcolor_opacity'] ) ? (float) $design['backcolor_opacity'] : 1 ),
						'text_color'         => isset( $design['text_color'] ) ? (string) $design['text_color'] : '#333333',
						'text_padding_top'   => isset( $design['text_padding_top'] ) ? absint( $design['text_padding_top'] ) : 20,
						'text_padding_right' => isset( $design['text_padding_right'] ) ? absint( $design['text_padding_right'] ) : 25,
						'text_padding_bottom'=> isset( $design['text_padding_bottom'] ) ? absint( $design['text_padding_bottom'] ) : 20,
						'text_padding_left'  => isset( $design['text_padding_left'] ) ? absint( $design['text_padding_left'] ) : 25,
						'text_border_radius' => isset( $design['text_border_radius'] ) ? absint( $design['text_border_radius'] ) : 12,
						'text_font_size'     => isset( $design['text_font_size'] ) ? absint( $design['text_font_size'] ) : 16,
						'text_line_height'   => isset( $design['text_line_height'] ) ? floatval( $design['text_line_height'] ) : 1.5,
						'border_enabled'     => isset( $design['border_enabled'] ) ? (string) $design['border_enabled'] : 'no',
						'border_width'       => isset( $design['border_width'] ) ? absint( $design['border_width'] ) : 1,
						'border_color'       => isset( $design['border_color'] ) ? (string) $design['border_color'] : '#111827',
						'design_width'       => isset( $design['design_width'] ) ? absint( $design['design_width'] ) : 0,
						'design_height'      => isset( $design['design_height'] ) ? absint( $design['design_height'] ) : 0,
						'design_percentage'  => isset( $design['design_percentage'] ) ? absint( $design['design_percentage'] ) : 50,
						'design_percentage_toggle' => isset( $design['design_percentage_toggle'] ) ? (string) $design['design_percentage_toggle'] : 'yes',
					],
				];
			case 'html':
				$body = self::decode_content_json_string( isset( $row->content ) ? (string) $row->content : '' );
				return [
					'popup_type'   => 'popup_html',
					'content_data' => [
						'content' => '' !== $body ? $body : '<p></p>',
					],
				];
			case 'image':
				$url = self::decode_content_json_string( isset( $row->content ) ? (string) $row->content : '' );
				if ( '' === $url && is_string( $row->content ) ) {
					$url = esc_url_raw( trim( $row->content, " \t\n\r\0\x0B\"" ) );
				}
				return [
					'popup_type'   => 'popup_image',
					'content_data' => [
						'image_url' => $url,
					],
				];
			case 'subscription':
				$img = self::decode_content_json_string( isset( $row->content ) ? (string) $row->content : '' );
				if ( '' === $img && ! empty( $row->content ) && is_string( $row->content ) ) {
					$try = json_decode( $row->content );
					if ( is_string( $try ) ) {
						$img = $try;
					}
				}
				$title = '';
				if ( ! empty( $advance['popup_main_title'] ) ) {
					$title = (string) $advance['popup_main_title'];
				} elseif ( isset( $row->title ) ) {
					$title = (string) $row->title;
				}
				return [
					'popup_type'   => 'popup_subscription',
					'content_data' => [
						'title'           => $title,
						'description'     => isset( $advance['popup_description'] ) ? (string) $advance['popup_description'] : '',
						'button_text'     => isset( $advance['button_text'] ) ? (string) $advance['button_text'] : 'Subscribe Now',
						'button_color'    => isset( $advance['button_color'] ) ? (string) $advance['button_color'] : '#3b82f6',
						'image_url'       => $img,
						'image_position'  => isset( $advance['image_position'] ) ? (string) $advance['image_position'] : 'right',
					],
				];
			default:
				return null;
		}
	}

	/**
	 * AJAX: dashboard Preview button — same pipeline as edit-screen enhanced preview, from saved DB row.
	 */
	public static function ajax_dashboard_popup_preview() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'message' => 'Forbidden' ], 403 );
		}
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'enhanced_preview_nonce' ) ) {
			wp_send_json_error( [ 'message' => 'Security check failed' ], 403 );
		}
		$id = isset( $_POST['popup_id'] ) ? absint( wp_unslash( $_POST['popup_id'] ) ) : 0;
		if ( $id < 1 ) {
			wp_send_json_error( [ 'message' => 'Invalid popup' ], 400 );
		}
		global $wpdb;
		$table         = $wpdb->prefix . 'instant_popup_builder';
		$escaped_table = esc_sql( $table );
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$escaped_table}` WHERE id = %d", $id ) );
		if ( ! $row ) {
			wp_send_json_error( [ 'message' => 'Not found' ], 404 );
		}
		$parts = self::build_dashboard_preview_parts( $row );
		if ( null === $parts ) {
			wp_send_json_success(
				[
					'fallback_modal' => true,
					'modal_id'       => 'popup_preview_' . $id,
				]
			);
		}
		$html = self::generate_preview_content( $parts['popup_type'], $parts['content_data'] );
		wp_send_json_success(
			[
				'preview_content' => $html,
				'popup_type'      => $parts['popup_type'],
			]
		);
	}

    /**
     * Generate default preview
     */
    private static function generate_default_preview($data) {
        $content = isset($data['content']) && is_string($data['content']) ? $data['content'] : '<p>Content preview...</p>';

        return sprintf(
            '<div class="instant-popup-content" style="background: #ffffff; padding: 30px; border-radius: 8px; max-width: 500px; margin: 0 auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);">
                <div class="instant-cross" style="position: absolute; top: 10px; right: 10px; cursor: pointer; color: #666;">
                    <i class="fa-solid fa-circle-xmark"></i>
                </div>
                <div class="inner_content">%s</div>
            </div>',
            wp_kses_post(is_string($content) ? $content : '')
        );
    }

    /**
     * AJAX handler for preview content generation
     */
    public static function ajax_generate_preview() {
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => __('Insufficient permissions.', 'instant-popup-builder')], 403);
        }

        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'enhanced_preview_nonce')) {
            wp_die('Security check failed');
        }

        $popup_type = isset($_POST['popup_type']) ? sanitize_text_field(wp_unslash($_POST['popup_type'])) : '';
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Each preview value is sanitized according to its type below.
        $content_data = isset($_POST['content_data']) && is_array($_POST['content_data']) ? wp_unslash($_POST['content_data']) : [];

        // Sanitize content data
        $sanitized_data = [];
        foreach ($content_data as $key => $value) {
            if (is_array($value)) {
                $sanitized_data[$key] = array_map('sanitize_text_field', $value);
            } elseif ('content' === $key && 'popup_text' === $popup_type) {
                $sanitized_data[$key] = ipb_sanitize_text_popup_content((string) $value);
            } else {
                $sanitized_data[$key] = sanitize_text_field($value);
            }
        }

        $preview_content = self::generate_preview_content($popup_type, $sanitized_data);

        wp_send_json_success([
            'preview_content' => $preview_content
        ]);
    }
}

// Register AJAX handlers
add_action('wp_ajax_generate_enhanced_preview', ['Instant_Popup_Builder_Enhanced_Preview', 'ajax_generate_preview']);
add_action('wp_ajax_ipb_dashboard_popup_preview', ['Instant_Popup_Builder_Enhanced_Preview', 'ajax_dashboard_popup_preview']);
