<?php
/**
 * Visual Builder for Giveaways
 *
 * Adds a "Visual Builder" button on the giveaway edit page that opens
 * a full-screen overlay with settings on the left and live preview on the right.
 *
 * @package SimpleGiveaways
 * @since 2.49.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class GiveASAP_Visual_Builder
 */
class GiveASAP_Visual_Builder {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'add_meta_boxes', array( $this, 'add_builder_button_metabox' ), 5 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_footer', array( $this, 'render_overlay_template' ) );


        // Include the preview REST controller
        require_once GASAP_ROOT . '/includes/admin/class-giveasap-preview-rest.php';
	}

	/**
	 * Add metabox with Visual Builder button
	 */
	public function add_builder_button_metabox() {
		add_meta_box(
			'giveasap_visual_builder_button',
			__( 'Visual Builder', 'giveasap' ),
			array( $this, 'render_button_metabox' ),
			'giveasap',
			'side',
			'high'
		);
	}

	/**
	 * Render the button metabox
	 *
	 * @param WP_Post $post
	 */
	public function render_button_metabox( $post ) {
		// A new post (auto-draft) has no saved settings yet — the preview
		// cannot render it (empty schedule/settings meta) until it is saved.
		if ( ! $this->is_builder_available( $post ) ) {
			?>
			<button type="button" id="giveasap-open-visual-builder" class="button button-hero button-primary" disabled="disabled">
				<span class="dashicons dashicons-welcome-view-site"></span>
				<?php _e( 'Open Visual Builder', 'giveasap' ); ?>
			</button>
			<p class="description">
				<?php _e( 'Save as draft to use the visual builder.', 'giveasap' ); ?>
			</p>
			<?php
			return;
		}
		?>
		<button type="button" id="giveasap-open-visual-builder" class="button button-hero button-primary">
			<span class="dashicons dashicons-welcome-view-site"></span>
			<?php _e( 'Open Visual Builder', 'giveasap' ); ?>
		</button>
		<p class="description">
			<?php _e( 'Open the visual builder to customize and preview your giveaway.', 'giveasap' ); ?>
		</p>
		<?php
	}

	/**
	 * The builder needs a saved giveaway: an auto-draft has an ID but no
	 * saved settings meta, which the preview cannot render.
	 *
	 * @param WP_Post|null $post
	 * @return bool
	 */
	private function is_builder_available( $post ) {
		return $post && $post->ID && 'auto-draft' !== $post->post_status;
	}

	/**
	 * Enqueue scripts and styles for visual builder
	 *
	 * @param string $hook
	 */
	public function enqueue_scripts( $hook ) {
		$screen = get_current_screen();

		if ( ! $screen || 'giveasap' !== $screen->id ) {
			return;
		}

		// Enqueue WordPress media for image uploads
		wp_enqueue_media();
		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );

		// Enqueue visual builder CSS
		wp_enqueue_style(
			'giveasap-visual-builder',
			GASAP_URI . 'assets/dist/css/visual-builder.css',
			array(),
			'2.49.0'
		);


		// Enqueue visual builder JS
		wp_enqueue_script(
			'giveasap-visual-builder',
			GASAP_URI . 'assets/js/visual-builder.js',
			array( 'jquery', 'wp-color-picker', 'wp-util' ),
			'2.49.0',
			true
		);

		// Localize data
		$post = get_post();
		wp_localize_script(
			'giveasap-visual-builder',
			'giveasapVisualBuilder',
			array(
				'giveawayID'     => $post ? $post->ID : 0,
				'nonce'          => wp_create_nonce( 'giveasap_builder_save' ),
				'iframeUrl'      => admin_url( 'admin.php' ),
				'settings'       => $this->get_builder_settings( $post ? $post->ID : 0 ),
				'syncManifest'   => $this->get_sync_manifest( $post ? $post->ID : 0 ),
			)
		);
	}

	/**
	 * Get sync manifest used by the visual builder JavaScript.
	 *
	 * @param int $post_id Giveaway post ID.
	 * @return array
	 */
	private function get_sync_manifest( $post_id ) {
		$manifest = array(
			'background_color' => array(
				'adapter' => 'color',
			),
			'background_image' => array(
				'adapter' => 'image',
			),
			'logo' => array(
				'adapter' => 'image',
			),
			'logo_link' => array(
				'adapter' => 'url',
			),
			'page_layout' => array(
				'adapter'   => 'select',
				'transform' => 'page_layout_checkbox_enum',
			),
			'prize_name' => array(
				'adapter' => 'text',
			),
			'prize_value' => array(
				'adapter' => 'text',
			),
			'winners' => array(
				'adapter' => 'number',
			),
			'prizes_layout' => array(
				'adapter' => 'select',
			),
			'type' => array(
				'adapter' => 'select',
			),
			'giveaway_page' => array(
				'adapter' => 'url',
			),
		);

		return apply_filters( 'giveasap_visual_builder_sync_manifest', $manifest, $post_id );
	}

	/**
	 * Get settings for the visual builder
	 *
	 * @param int $post_id
	 * @return array
	 */
	public function get_builder_settings( $post_id ) {
		$settings = array();

		// General settings
		$settings['type'] = get_post_meta( $post_id, 'giveasap_type', true );
		$settings['giveaway_page'] = get_post_meta( $post_id, 'sg_giveaway_page', true );

		// Prize settings
		$prize_settings = get_post_meta( $post_id, 'giveasap_prize', true );
		if ( is_array( $prize_settings ) ) {
			$settings['prize_name'] = isset( $prize_settings['prize'] ) ? $prize_settings['prize'] : '';
			$settings['prize_value'] = isset( $prize_settings['value'] ) ? $prize_settings['value'] : '';
			$settings['winners'] = isset( $prize_settings['winners'] ) ? $prize_settings['winners'] : '1';
			$settings['prizes_layout'] = isset( $prize_settings['layout'] ) ? $prize_settings['layout'] : 'vertical';
		}

		// Display settings
		$display_settings = get_post_meta( $post_id, 'giveasap_display', true );
		if ( is_array( $display_settings ) ) {
			$settings['background_color'] = isset( $display_settings['background_color'] ) ? $display_settings['background_color'] : '';
			$settings['background_image'] = isset( $display_settings['background_image'] ) ? $display_settings['background_image'] : '';
			$settings['logo'] = isset( $display_settings['logo'] ) ? $display_settings['logo'] : '';
			$settings['logo_link'] = isset( $display_settings['logo_link'] ) ? $display_settings['logo_link'] : '';
			$settings['page_layout'] = ( isset( $display_settings['page_layout'] ) && '1' === (string) $display_settings['page_layout'] ) ? 'show_header' : 'hide_header';
		}

		return $settings;
	}

	/**
	 * Render the overlay template in admin footer
	 */
	public function render_overlay_template() {
		$screen = get_current_screen();

		if ( ! $screen || 'giveasap' !== $screen->id ) {
			return;
		}

		$post = get_post();
		if ( ! $this->is_builder_available( $post ) ) {
			return;
		}

		$settings = $this->get_builder_settings( $post->ID );
		?>
		<div id="giveasap-visual-builder-overlay" class="giveasap-builder-overlay" style="display: none;">
			<div class="giveasap-builder-header">
                <img width="48px" src="<?php echo esc_url( trailingslashit( GASAP_URI ) . 'assets/images/logo-color.svg'); ?>" />

				<div class="giveasap-builder-actions">
                    <div class="giveasap-builder-header-notice">Beta Version. If you encounter issues, use the classic view.</div>
					<button type="button" id="giveasap-builder-save" class="button button-primary">
						<?php _e( 'Save Changes', 'giveasap' ); ?>
					</button>
					<button type="button" id="giveasap-builder-close" class="button">
						<?php _e( 'Close', 'giveasap' ); ?>
					</button>
				</div>
			</div>

			<div class="giveasap-builder-content">

				<div class="giveasap-builder-sidebar">
                    <?php do_action( 'giveasap_visual_builder_sidebar', $post ); ?>
				</div>
                <div class="giveasap-builder-sidebar-options">
                    <?php do_action( 'giveasap_visual_builder_sidebar_options', $post ); ?>
                </div>

				<div class="giveasap-builder-preview">
					<div class="giveasap-builder-preview-header">
						<h3><?php _e( 'Live Preview', 'giveasap' ); ?></h3>
                        <div class="giveasap-builder-preview-header-actions">

                            <span class="giveasap-preview-loading" style="display: none;">
                                <span class="spinner is-active"></span>
                                <?php _e( 'Updating...', 'giveasap' ); ?>
                            </span>
                            <div class="giveasap-preview-tabs">
                                <button type="button" class="giveasap-preview-tab active" data-preview-step="1">
                                    <?php _e( 'Visitor', 'giveasap' ); ?>
                                </button>
                                <button type="button" class="giveasap-preview-tab" data-preview-step="2">
                                    <?php _e( 'Subscribed', 'giveasap' ); ?>
                                </button>
                            </div>
                        </div>
					</div>
					<div class="giveasap-builder-preview-frame-wrapper">
						<iframe id="giveasap-builder-iframe" name="giveasap-preview-frame" src="" frameborder="0"></iframe>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

    protected function old_code() {
        ?>
        <h3><?php _e( 'Display Settings', 'giveasap' ); ?></h3>

        <div class="giveasap-field-group">
            <label><?php _e( 'Background Color', 'giveasap' ); ?></label>
            <input type="text" name="background_color" class="giveasap-color-picker"
                   data-giveasap-sync-key="background_color"
                   data-giveasap-adapter="color"
                   value="<?php echo esc_attr( isset( $settings['background_color'] ) ? $settings['background_color'] : '' ); ?>"
                   data-default-color=""/>
        </div>

        <div class="giveasap-field-group">
            <label><?php _e( 'Background Image', 'giveasap' ); ?></label>
            <div class="giveasap-media-uploader" data-field="background_image">
                <input type="hidden" name="background_image" data-giveasap-sync-key="background_image" data-giveasap-adapter="image" value="<?php echo esc_attr( isset( $settings['background_image'] ) ? $settings['background_image'] : '' ); ?>" />
                <div class="giveasap-media-preview">
                    <?php if ( ! empty( $settings['background_image'] ) ) :
                        $img_src = wp_get_attachment_image_url( $settings['background_image'], 'thumbnail' );
                        if ( $img_src ) : ?>
                            <img src="<?php echo esc_url( $img_src ); ?>" alt="" />
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <button type="button" class="button giveasap-upload-media">
                    <?php _e( 'Select Image', 'giveasap' ); ?>
                </button>
                <button type="button" class="button giveasap-remove-media <?php echo empty( $settings['background_image'] ) ? 'hidden' : ''; ?>">
                    <?php _e( 'Remove', 'giveasap' ); ?>
                </button>
            </div>
        </div>

        <div class="giveasap-field-group">
            <label><?php _e( 'Logo', 'giveasap' ); ?></label>
            <div class="giveasap-media-uploader" data-field="logo">
                <input type="hidden" name="logo" data-giveasap-sync-key="logo" data-giveasap-adapter="image" value="<?php echo esc_attr( isset( $settings['logo'] ) ? $settings['logo'] : '' ); ?>" />
                <div class="giveasap-media-preview">
                    <?php if ( ! empty( $settings['logo'] ) ) :
                        $img_src = wp_get_attachment_image_url( $settings['logo'], 'thumbnail' );
                        if ( $img_src ) : ?>
                            <img src="<?php echo esc_url( $img_src ); ?>" alt="" />
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <button type="button" class="button giveasap-upload-media">
                    <?php _e( 'Select Logo', 'giveasap' ); ?>
                </button>
                <button type="button" class="button giveasap-remove-media <?php echo empty( $settings['logo'] ) ? 'hidden' : ''; ?>">
                    <?php _e( 'Remove', 'giveasap' ); ?>
                </button>
            </div>
        </div>

        <div class="giveasap-field-group">
            <label for="logo_link"><?php _e( 'Logo Link URL', 'giveasap' ); ?></label>
            <input type="url" name="logo_link" id="logo_link"
                   data-giveasap-sync-key="logo_link"
                   data-giveasap-adapter="url"
                   value="<?php echo esc_url( isset( $settings['logo_link'] ) ? $settings['logo_link'] : '' ); ?>" />
        </div>

        <div class="giveasap-field-group">
            <label for="page_layout"><?php _e( 'Page Layout', 'giveasap' ); ?></label>
            <select name="page_layout" id="page_layout" data-giveasap-sync-key="page_layout" data-giveasap-adapter="select" data-giveasap-transform="page_layout_checkbox_enum">
                <option value="show_header" <?php selected( isset( $settings['page_layout'] ) ? $settings['page_layout'] : 'show_header', 'show_header' ); ?>>
                    <?php _e( 'Show Header & Footer', 'giveasap' ); ?>
                </option>
                <option value="hide_header" <?php selected( isset( $settings['page_layout'] ) ? $settings['page_layout'] : '', 'hide_header' ); ?>>
                    <?php _e( 'Hide Header & Footer', 'giveasap' ); ?>
                </option>
            </select>
        </div>

        <h3><?php _e( 'Prize Settings', 'giveasap' ); ?></h3>

        <div class="giveasap-field-group">
            <label for="prize_name"><?php _e( 'Prize Name', 'giveasap' ); ?></label>
            <input type="text" name="prize_name" id="prize_name"
                   data-giveasap-sync-key="prize_name"
                   data-giveasap-adapter="text"
                   value="<?php echo esc_attr( isset( $settings['prize_name'] ) ? $settings['prize_name'] : '' ); ?>" />
        </div>

        <div class="giveasap-field-group">
            <label for="prize_value"><?php _e( 'Prize Value', 'giveasap' ); ?></label>
            <input type="text" name="prize_value" id="prize_value"
                   data-giveasap-sync-key="prize_value"
                   data-giveasap-adapter="text"
                   value="<?php echo esc_attr( isset( $settings['prize_value'] ) ? $settings['prize_value'] : '' ); ?>" />
        </div>

        <div class="giveasap-field-group">
            <label for="winners"><?php _e( 'Number of Winners', 'giveasap' ); ?></label>
            <input type="number" name="winners" id="winners" min="1"
                   data-giveasap-sync-key="winners"
                   data-giveasap-adapter="number"
                   value="<?php echo esc_attr( isset( $settings['winners'] ) ? $settings['winners'] : '1' ); ?>" />
        </div>

        <div class="giveasap-field-group">
            <label for="prizes_layout"><?php _e( 'Prizes Layout', 'giveasap' ); ?></label>
            <select name="prizes_layout" id="prizes_layout" data-giveasap-sync-key="prizes_layout" data-giveasap-adapter="select">
                <option value="vertical" <?php selected( isset( $settings['prizes_layout'] ) ? $settings['prizes_layout'] : 'vertical', 'vertical' ); ?>>
                    <?php _e( 'Vertical List', 'giveasap' ); ?>
                </option>
                <option value="slider" <?php selected( isset( $settings['prizes_layout'] ) ? $settings['prizes_layout'] : '', 'slider' ); ?>>
                    <?php _e( 'Slider', 'giveasap' ); ?>
                </option>
            </select>
        </div>

        <h3><?php _e( 'General Settings', 'giveasap' ); ?></h3>

        <div class="giveasap-field-group">
            <label for="type"><?php _e( 'Giveaway Type', 'giveasap' ); ?></label>
            <select name="type" id="type" data-giveasap-sync-key="type" data-giveasap-adapter="select">
                <?php foreach ( giveasap_get_giveaway_types() as $key => $label ) : ?>
                    <option value="<?php echo esc_attr( $key ); ?>" <?php selected( isset( $settings['type'] ) ? $settings['type'] : 'simple', $key ); ?>>
                        <?php echo esc_html( $label ); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="giveasap-field-group">
            <label for="giveaway_page"><?php _e( 'Main Giveaway Page URL', 'giveasap' ); ?></label>
            <input type="url" name="giveaway_page" id="giveaway_page"
                   data-giveasap-sync-key="giveaway_page"
                   data-giveasap-adapter="url"
                   value="<?php echo esc_url( isset( $settings['giveaway_page'] ) ? $settings['giveaway_page'] : '' ); ?>" />
        </div>
        <?php
    }
}

new GiveASAP_Visual_Builder();
