<?php

/**
 * W2PShop -saved data handler
 */

defined( 'ABSPATH' ) || exit;


final class W2PShopSavedDataHandler {
	public string $saved_data_table_name = 'w2pshop_saved_data';
	public W2PShopDbHelper $db_helper;

	public function __construct() {
		$this->db_helper = new W2PShopDbHelper();
	}

	public function init(): void {
		// WordPress Hooks
		add_action( 'init', array( $this, 'init_handler' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'init_scripts' ) );

		// W2PShop Hooks
		add_action( 'w2pshop_loaded', array( $this, 'w2pshop_loaded' ) );

		// Ajax Actions
		add_action( 'wp_ajax_w2pshop_save_design_data', array( $this, 'save_design_data' ) );
		add_action( 'wp_ajax_nopriv_w2pshop_save_design_data', array( $this, 'save_design_data' ) );
		add_action( 'wp_ajax_w2pshop_delete_saved_design', array( $this, 'delete_saved_design' ) );
		add_action( 'wp_ajax_nopriv_w2pshop_delete_saved_design', array( $this, 'delete_saved_design' ) );

		// Shortcode Registration
		add_shortcode( 'w2pshop_saved_data', array( $this, 'w2pshop_saved_data_shortcode' ) );

		// WooCommerce Hooks
		add_filter( 'woocommerce_account_menu_items', array( $this, 'woocommerce_account_menu_items' ), 10, 1 );
		add_filter( 'woocommerce_get_query_vars', array( $this, 'woocommerce_get_query_vars' ), 10, 1 );
		add_filter( 'woocommerce_endpoint_w2pshop-saved-designs_title', array( $this, 'woocommerce_endpoint_w2pshop_saved_designs_title' ), 10, 3 );
		add_action( 'woocommerce_account_w2pshop-saved-designs_endpoint', array( $this, 'woocommerce_account_saved_designs_endpoint_content' ), 10, 1 );
	}

	public function w2pshop_loaded(): void {
		$this->init_db();
	}

	public function init_handler(): void {
		add_rewrite_endpoint( 'w2pshop-saved-designs', EP_ROOT | EP_PAGES );
		// Ensure rewrite rules are flushed at least once per plugin version so the endpoint resolves.
		$rewrite_flag = get_option( 'w2pshop_saved_designs_rewrite_flushed', '' );
		if ( $rewrite_flag !== W2PSHOPCORE_VERSION ) {
			flush_rewrite_rules( false );
			update_option( 'w2pshop_saved_designs_rewrite_flushed', W2PSHOPCORE_VERSION );
		}
	}

	public function init_scripts(): void {
		wp_register_style(
			'w2pshop_saved_designs_css',
			W2PSHOP_PLUGIN_URL . '/assets/css/w2pshop-saved-designs-styles.css',
			array(),
			W2PSHOPCORE_VERSION
		);

		if ( is_wc_endpoint_url( 'w2pshop-saved-designs' ) ) {
			wp_enqueue_style( 'w2pshop_saved_designs_css' );
			
			// Enqueue saved designs JavaScript with dependencies (including SweetAlert)
			wp_enqueue_script(
				'w2pshop_saved_design_js',
				W2PSHOP_PLUGIN_URL . '/assets/js/w2pshop-saved-design.js',
				array( 'jquery', 'w2pshop_common_js', 'w2pshop_swal2_js' ),
				W2PSHOPCORE_VERSION,
				true
			);
			
			// Localize the nonce for delete functionality
			wp_localize_script(
				'w2pshop_saved_design_js',
				'w2pshop_saved_data_nonce',
				array( wp_create_nonce( 'w2pshop_saved_data_action' ) )
			);
		}
	}

	/**
	 * Checks if the save design feature is enabled.
	 *
	 * @return bool Returns true if the feature is enabled, false otherwise.
	 */
	public function is_enabled(): bool {
		return ! empty( W2PShopSettings::get_setting( 'w2pshop_core_saved_data' ) );
	}

	/**
	 * Initialize/upgrade database
	 *
	 * @return void
	 */
	public function init_db(): void {
		global $wpdb, $charset_collate;
		$table_name = $wpdb->prefix . $this->saved_data_table_name;

		$w2shop_handler_db_version = ( is_multisite() ) ?
			get_site_option( 'w2pshop_saved_data_handler_db_version', '' ) :
			get_option( 'w2pshop_saved_data_handler_db_version', '' );

		if ( W2PSHOPCORE_VERSION !== $w2shop_handler_db_version ) {

			$sql = 'id BIGINT(20) UNSIGNED AUTO_INCREMENT NOT NULL,
					saved_key NVARCHAR(50) COLLATE utf8_unicode_ci NOT NULL,
					type NVARCHAR(20) COLLATE utf8_unicode_ci NOT NULL,
					cust_data LONGTEXT COLLATE utf8_unicode_ci NOT NULL,
					linked_product_id BIGINT(50) UNSIGNED NOT NULL,
					linked_user BIGINT(50) UNSIGNED NULL,
					updated_at DATETIME COLLATE utf8_unicode_ci NOT NULL,
					PRIMARY KEY  (id),
					KEY saved_key (saved_key),
					KEY linked_product_id (linked_product_id)';

			dbDelta( "CREATE TABLE {$table_name} ({$sql}){$charset_collate};" );

			( is_multisite() ) ?
				update_site_option( 'w2pshop_saved_data_handler_db_version', W2PSHOPCORE_VERSION ) :
				update_option( 'w2pshop_saved_data_handler_db_version', W2PSHOPCORE_VERSION);
		}
	}

	/**
	 * Return records by linked user id
	 *
	 * @param string $user_id WordPress's user id
	 *
	 * @return array | null
	 */
	public function get_by_linked_user( string $user_id ) {
		return $this->db_helper->get_results( $this->saved_data_table_name, array( 'linked_user' => $user_id ), OBJECT );
	}

	/**
	 * Retrieves a single row from the saved data table based on the given saved key and linked user.
	 *
	 * @param string $saved_key The saved key to search for.
	 * @param string $linked_user The linked user to search for.
	 *
	 * @return object|null Returns the first row matching the given saved key and linked user, or null if no match is found.
	 */
	public function get_by_key_and_user( string $saved_key, string $linked_user ) {
		$results = $this->db_helper->get_results(
			$this->saved_data_table_name,
			array(
				'saved_key'   => $saved_key,
				'linked_user' => $linked_user,
			),
			OBJECT
		);

		if ( ! empty( $results ) ) {
			return $results[0];
		}
		return null;
	}

	/**
	 * Retrieves the unassigned saved design by the given key.
	 *
	 * @param string $saved_key The key of the saved data.
	 * @return object|null The unassigned saved design or null if not found.
	 */
	public function get_unassigned_by_key( string $saved_key ) {
		$results = $this->db_helper->get_results(
			$this->saved_data_table_name,
			array(
				'saved_key'   => $saved_key,
				'linked_user' => '0',
			),
			OBJECT
		);

		if ( ! empty( $results ) ) {
			return $results[0];
		}
		return null;
	}

	/**
	 * Inserts or updates a record in the database.
	 *
	 * @param string $type The type of the record.
	 * @param string $cust_data The custom data.
	 * @param int $linked_product_id The ID of the linked product.
	 * @param string $saved_key The saved key (optional).
	 *
	 * @return array The saved data.
	 */
	public function insert_update_record( string $type, string $cust_data, int $linked_product_id, string $saved_key = '' ): array {
		$linked_user = '';
		if ( is_user_logged_in() ) {
			$linked_user = get_current_user_id();
		}

		$saved_data = ( ! empty( $saved_key ) && ! empty( $linked_user ) ) ? $this->get_by_key_and_user( $saved_key, $linked_user ) : null;

		if ( empty( $saved_data ) ) {
			// This is a new record
			$saved_key  = W2PShopUtil::generate_unique_id();
			$saved_data = array(
				'saved_key'         => $saved_key,
				'type'              => $type,
				'cust_data'         => $cust_data,
				'linked_product_id' => $linked_product_id,
				'linked_user'       => $linked_user,
				'updated_at'        => gmdate( 'Y-m-d H:i:s' ),
			);
			$this->db_helper->insert_record( $this->saved_data_table_name, $saved_data );
		} else {
			// Update existing record
			$saved_data->type              = $type;
			$saved_data->cust_data         = $cust_data;
			$saved_data->linked_product_id = $linked_product_id;
			$saved_data->linked_user       = $linked_user;
			$saved_data->updated_at        = gmdate( 'Y-m-d H:i:s' );
			$this->db_helper->update_record( $this->saved_data_table_name, (array) $saved_data, array( 'saved_key' => $saved_key ) );
		}

		return (array) $saved_data;
	}

	/**
	 *  Delete a record from database table
	 *
	 * @param string $saved_key
	 * @param string $linked_user
	 *
	 * @return bool
	 */
	public function delete_record( string $saved_key, string $linked_user ): bool {
		if ( ! empty( $saved_key ) && ! empty( $linked_user ) ) {
			$this->db_helper->delete_record(
				$this->saved_data_table_name,
				array(
					'saved_key'   => $saved_key,
					'linked_user' => $linked_user,
				)
			);
			return true;
		}
		return false;
	}

	/**
	 * Deletes a saved design.
	 *
	 * @param string $saved_key The saved key.
	 *
	 * @return mixed The saved key if successful, false otherwise.
	 */
	public function delete_saved_design ( string $saved_key = '' ) {
		check_ajax_referer('w2pshop_saved_data_action', 'security');
		
		if ( ! is_user_logged_in() ) {
			wp_send_json( array( 
				'success' => false,
				'message' => 'User not logged in'
			) );
		}
		
		$saved_key = ( isset( $_REQUEST['saved_key'] ) ) ? sanitize_text_field( wp_unslash($_REQUEST['saved_key'] )) : $saved_key;
		
		if ( empty( $saved_key ) ) {
			wp_send_json( array( 
				'success' => false,
				'message' => 'Invalid saved key'
			) );
		}
		
		$current_user_id = get_current_user_id();
		$delete_design = $this->delete_record( $saved_key, $current_user_id );
		
		if ( $delete_design ) {
			wp_send_json( array( 'success' => true ) ); 
		}
		
		wp_send_json( array( 
			'success' => false,
			'message' => 'Failed to delete record'
		) ); 
	}

	/**
	 * Saves the design data.
	 *
	 * @param string $type The type of data to save.
	 * @param string $cust_data The custom data to save.
	 * @param int $linked_product_id The ID of the linked product.
	 * @param string $saved_key The saved key.
	 *
	 * @return mixed The saved key if successful, false otherwise.
	 */
	public function save_design_data( string $type = '', string $cust_data = '', int $linked_product_id = 0, string $saved_key = '' ) {
		check_ajax_referer('w2pshop_saved_data_action', 'security');
		$type              = isset( $_REQUEST['type'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['type'] ) ) : $type;
		// Preserve exact bytes for JSON/base64 payloads
		$cust_data         = isset( $_REQUEST['cust_data'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['cust_data'] ) ) : $cust_data;
		$linked_product_id = isset( $_REQUEST['linked_product_id'] ) ? absint( wp_unslash( $_REQUEST['linked_product_id'] ) ) : $linked_product_id;
		$saved_key         = isset( $_REQUEST['saved_key'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['saved_key'] ) ) : $saved_key;

		if ( ! empty( $type ) && ! empty( $cust_data ) && ! empty( $linked_product_id ) ) {
			$saved_data = $this->insert_update_record( $type, $cust_data, $linked_product_id, $saved_key );
			if ( is_ajax() ) {
				wp_send_json(
					array(
						'success'   => true,
						'saved_key' => $saved_data['saved_key'],
					)
				);
			} else {
				return $saved_data['saved_key'];
			}
		}

		if ( is_ajax() ) {
			wp_send_json( array( 'success' => false ) );
		}
		return false;
	}

	/**
	 * Generates a shortcode for displaying saved data.
	 *
	 * @param mixed $atts array of attributes for the shortcode. Default is an empty array.
	 * @param string|null $content The content inside the shortcode tags. Default is null.
	 * @param string $tag The name of the shortcode. Default is an empty string.
	 *
	 * @return string Shortcode output.
	 */
	public function w2pshop_saved_data_shortcode( $atts, string $content = null, string $tag = '' ): string {
		wp_enqueue_style( 'w2pshop_saved_designs_css' );
		
		// Enqueue saved designs JavaScript with dependencies (including SweetAlert)
		wp_enqueue_script(
			'w2pshop_saved_design_js',
			W2PSHOP_PLUGIN_URL . '/assets/js/w2pshop-saved-design.js',
			array( 'jquery', 'w2pshop_common_js', 'w2pshop_swal2_js' ),
			W2PSHOPCORE_VERSION,
			true
		);
		
		// Localize the nonce for delete functionality
		wp_localize_script(
			'w2pshop_saved_design_js',
			'w2pshop_saved_data_nonce',
			array( wp_create_nonce( 'w2pshop_saved_data_action' ) )
		);

		// normalize attribute keys, lowercase
		$atts = array_change_key_case( (array) $atts, CASE_LOWER );

		// override default attributes with user attributes
		$w2pshop_atts = shortcode_atts(
			array(
				'title' => 'Saved Designs',
				'type'  => 'all',
			),
			$atts,
			$tag
		);

		// We will ignore $content as we will generate based on $w2pshop_atts.
		if ( ! is_user_logged_in() ) {
			return '<div class="w2pshop-saved-data">You must be logged in to view this page.</div>';
		}

		return $this->get_saved_designs_grid_html();
	}

	/**
	 * Adds a new menu item to the WooCommerce account menu.
	 *
	 * @param array $items An array of menu items.
	 *
	 * @return array The updated array of menu items.
	 */
	public function woocommerce_account_menu_items( $items ): array {
		// Check to see if this feature is enabled before continuing.
		if ( ! $this->is_enabled() ) {
			return $items; }

		$menu_item = array( 'w2pshop-saved-designs' => __( 'My Saved Designs', 'web-to-print-shop-core' ) );

		// Find the position of the key
		$position = array_search( 'orders', array_keys( $items ), true );

		// Check if the key was found
		if ( false !== $position ) {

			// Split the array into two parts and add the new item in between
			return array_merge(
				array_slice( $items, 0, $position + 1 ),
				$menu_item,
				array_slice( $items, $position + 1 )
			);
		} else {
			$items[] = $menu_item;
			return $items;
		}
	}

	/**
	 * Adds a new query variable to the list of WooCommerce query variables.
	 *
	 * @param array $vars The list of WooCommerce query variables.
	 * @return array The updated list of WooCommerce query variables.
	 */
	public function woocommerce_get_query_vars( $vars ): array {
		$vars['w2pshop-saved-designs'] = 'w2pshop-saved-designs';
		return $vars;
	}

	/**
	 * Modifies the title of the WooCommerce endpoint for saved designs.
	 *
	 * @param string $title The original title.
	 * @param string $endpoint The endpoint being accessed.
	 * @param string $action The action being performed.
	 *
	 * @return string The modified title.
	 */
	public function woocommerce_endpoint_w2pshop_saved_designs_title( $title, $endpoint, $action ): string {
		// Check if the main query is for the endpoint and in the main loop
		if ( is_wc_endpoint_url( 'w2pshop-saved-designs' ) && in_the_loop() ) {
			$title = __( 'My Saved Designs', 'web-to-print-shop-core' );
		}
		return $title;
	}

	/**
	 * Renders the content for the saved design's endpoint.
	 *
	 * @return void
	 */
	public function woocommerce_account_saved_designs_endpoint_content(): void {
		echo wp_kses_post( $this->get_saved_designs_grid_html() );
	}

	/**
	 * Retrieves the uDraw designer data from the given saved custom data object.
	 *
	 * @param object $saved_custom_data The saved custom data object.
	 * @return mixed The uDraw designer data or null if not found.
	 */
	public function get_udraw_designer_data( object $saved_custom_data ) {
		// Try v6 key first
		$val = $this->get_saved_data_item_by_property( $saved_custom_data, 'udraw_designer_data' );

		// Try legacy v5 keys if not found
		if ( is_null( $val ) ) {
			foreach ( array( 'udraw_data', 'udraw_design_data' ) as $legacyKey ) {
				$val = $this->get_saved_data_item_by_property( $saved_custom_data, $legacyKey );
				if ( ! is_null( $val ) ) { break; }
			}
		}

		if ( is_null( $val ) ) { return null; }

		// Try base64(JSON)
		$decoded = base64_decode( (string) $val, true );
		if ( $decoded !== false && $decoded !== '' ) {
			$obj = json_decode( $decoded );
			if ( is_object( $obj ) ) { return $obj; }
		}

		// Try raw JSON
		$obj = json_decode( is_string( $val ) ? $val : wp_json_encode( $val ) );
		return is_object( $obj ) ? $obj : null;
	}

	public function get_pdfeditor_data( object $saved_custom_data ) {
		$pdfeditor_data = $this->get_saved_data_item_by_property( $saved_custom_data, 'pdfeditor_data' );
		if ( ! is_null( $pdfeditor_data ) ) {
			return json_decode( base64_decode( $pdfeditor_data ) );
		}
		return null;
	}

	/**
	 * Retrieves the saved design data from the request.
	 *
	 * @return mixed|null The saved design data if the request contains a 'saved_design_key' parameter and the user is logged in, otherwise null.
	 */
	public function get_saved_design_data_from_request() {
		// Allow loading a saved design when a user is logged in and a key is provided.
		// If a nonce is provided, it must be valid; if no nonce is provided, allow it (direct link from My Account, etc.).
		if ( isset( $_REQUEST['saved_design_key'] ) && is_user_logged_in() ) {
			$nonce = isset( $_REQUEST['w2pshop_nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['w2pshop_nonce'] ) ) : '';
			if ( $nonce !== '' && ! wp_verify_nonce( $nonce, 'w2pshop_saved_data_action' ) ) {
				return null; // Explicit nonce provided but invalid.
			}
			return $this->get_by_key_and_user( sanitize_text_field( wp_unslash( $_REQUEST['saved_design_key'] ) ), get_current_user_id() );
		}
		return null;
	}

	/**
	 * Retrieves a saved data item by a specified property.
	 *
	 * @param object $saved_custom_data The saved custom data object.
	 * @param string $property The property to search for.
	 * @return mixed|null The value of the property if found, null otherwise.
	 */
	public function get_saved_data_item_by_property( object $saved_custom_data, string $property ) {
		if ( ! property_exists( $saved_custom_data, 'type' ) ||
			! property_exists( $saved_custom_data, 'cust_data' ) ) {
			return null;
		}

		// Handle both JSON string and array formats (cust_data may be stored in either format)
		if ( is_string( $saved_custom_data->cust_data ) ) {
			$custom_data = json_decode( html_entity_decode( $saved_custom_data->cust_data ) );
		} elseif ( is_array( $saved_custom_data->cust_data ) || is_object( $saved_custom_data->cust_data ) ) {
			$custom_data = $saved_custom_data->cust_data;
		} else {
			return null;
		}

		if ( ! is_array( $custom_data ) && ! is_object( $custom_data ) ) {
			return null;
		}

		foreach ( $custom_data as $custom_data_item ) {
			if ( is_object( $custom_data_item ) && property_exists( $custom_data_item, 'key' ) && $custom_data_item->key === $property ) {
				return $custom_data_item->value;
			}
		}
		return null;
	}

	/**
	 * Retrieves the default URL for the saved designs in the user's account.
	 *
	 * @return string The URL for the saved designs in the user's account.
	 */
	public function get_my_saved_design_default_url(): string {
		$myaccount_page_id = wc_get_page_id( 'myaccount' );

		if ( $myaccount_page_id && -1 !== $myaccount_page_id ) {
			return add_query_arg( array( 'w2pshop-saved-designs' => 'true' ), get_permalink( $myaccount_page_id ) );
		}

		return home_url() . '/?w2pshop-saved-designs';
	}

	/**
	 * Retrieves the HTML for the saved designs as a grid.
	 * Enqueues the JS if a design is found; returns pre-formated HTML.
	 * @return string
	 */
	private function get_saved_designs_grid_html(): string {
		// Enqueue saved designs JavaScript with dependencies (including SweetAlert)
		wp_enqueue_script(
			'w2pshop_saved_design_js',
			W2PSHOP_PLUGIN_URL . '/assets/js/w2pshop-saved-design.js',
			array( 'jquery', 'w2pshop_common_js', 'w2pshop_swal2_js' ),
			W2PSHOPCORE_VERSION,
			true
		);
		
		// Check for unassigned saved data
		if ( $this->check_for_unassigned_saved_design() ) {
			wp_localize_script(
				'w2pshop_saved_design_js',
				'w2pshopDesignData',
				array( 'showSuccess' => true )
			);
		}
		// Check if the user has any saved data.
		$saved_data = $this->get_by_linked_user( get_current_user_id() );
		if ( empty( $saved_data ) ) {
			return '<div class="w2pshop-saved-data">You have no saved designs.</div>';
		} else {
			$displayed_count    = 0;
			$grid_html          = '<div class="w2pshop-saved-designs-grid">';

			// Load in uDraw Api class if it's loaded into WordPress.
			$udraw_api          = ( class_exists( 'UdrawApi' ) ) ? new UdrawApi() : null;
			$udraw_base_api_url = ( ! is_null( $udraw_api ) ) ? $udraw_api->base_api_url : '';

			foreach ( $saved_data as $saved_data_item ) {
				$product = wc_get_product( $saved_data_item->linked_product_id );
				// If the product was deleted/unavailable, skip this design instead of fatalling.
				if ( ! $product ) {
					continue;
				}

				$product_name = $product->get_name();
				$product_url  = add_query_arg( array( 'saved_design_key' => $saved_data_item->saved_key ), $product->get_permalink() );
				$design_url   = add_query_arg(
					array(
						'saved_design_key' => $saved_data_item->saved_key,
						'designer'         => 'true',
					),
					$product->get_permalink()
				);

				if ( 'udraw' === $saved_data_item->type ) {
					$udraw_data = $this->get_udraw_designer_data( $saved_data_item );
					if ( is_null( $udraw_data ) ) {
						continue; }

					$preview_fields = array( 'preview', 'preview_url', 'thumbnail', 'thumb' );
					$preview = '';
					foreach ( $preview_fields as $field ) {
						if ( isset( $udraw_data->$field ) && $udraw_data->$field !== '' ) {
							$preview = (string) $udraw_data->$field;
							break;
						}
					}
					$preview = trim( $preview );
					if ( preg_match( '#^https?://#i', $preview ) ) {
						$preview_image = $preview;
					} else {
						$preview_image = $udraw_base_api_url . $preview;
					}
				} elseif ( 'pdfeditor' === $saved_data_item->type ) {
					$pdfeditor_data = $this->get_pdfeditor_data( $saved_data_item );
					if ( is_null( $pdfeditor_data ) ) {
						continue; }
					$preview_image = $this->get_saved_data_item_by_property( $saved_data_item, 'pdfeditor_thumbnail' );
				} else {
					continue; // Type is currently not supported.
				}

				$grid_html       .= $this->get_saved_designs_grid_html_item( $product_name, $preview_image, $product_url, $design_url, $saved_data_item->saved_key );
				++$displayed_count;
			}

			if ( 0 === $displayed_count ) {
				return '<div class="w2pshop-saved-data">You have no saved designs.</div>';
			}

			$html  = '<div class="w2pshop-saved-data">You have ' . $displayed_count . ' saved designs.</div>';
			$html .= $grid_html . '</div>';
			return $html;
		}
	}

	private function get_saved_designs_grid_html_item( $product_name, $preview_image, $product_url, $design_url, $saved_design_key ): string
    {
        $product_name_esc     = esc_html( $product_name );
        $preview_image_esc    = esc_url( $preview_image );
        $product_url_esc      = esc_url( $product_url );
        $design_url_esc       = esc_url( $design_url );
        $saved_design_key_esc = esc_attr( $saved_design_key );
		$html  = '<div class="w2pshop-saved-design-item">';
		$html .= '    <div class="w2pshop-saved-design-title">' . $product_name_esc . '</div>';
		$html .= '    <div class="w2pshop-saved-design-image">';
		$html .= '        <img src="' . $preview_image_esc . '" alt="Design">';
		$html .= '    </div>';
		$html .= '    <div class="w2pshop-saved-design-links">';
		$html .= '        <a class="load-product" href="' . $product_url_esc . '">Load Product</a> | ';
		$html .= '        <a class="load-design" href="' . $design_url_esc . '">Load Design</a> | ';
		$html .= '        <a class="delete-saved-design" href="#" rel="nofollow" data-saved-design-key="' . $saved_design_key_esc . '">Delete Design</a>';
		$html .= '    </div>';
		$html .= '</div>';
		return $html;
	}

	/**
	 * Checks if there is an unassigned saved design and updates it if found.
	 *
	 * @return bool Returns true if an unassigned saved design is found and updated, false otherwise.
	 */
	private function check_for_unassigned_saved_design(): bool {
		// Check if the cookie is set
		if ( isset( $_COOKIE['w2pshop_save_design_key'] ) && is_user_logged_in() ) {
			$w2pshop_saved_design_key = sanitize_text_field( wp_unslash($_COOKIE['w2pshop_save_design_key']));

			// Attempt to load in saved design that has not been assigned to a user yet and matches the saved key.
			$saved_design = $this->get_unassigned_by_key( sanitize_text_field( wp_unslash($w2pshop_saved_design_key) ) );
			if ( ! is_null( $saved_design ) ) {
				// If the saved design exists, update it.
				$saved_design->linked_user = get_current_user_id();
				$this->db_helper->update_record( $this->saved_data_table_name, (array) $saved_design, array( 'saved_key' => $saved_design->saved_key ) );
				return true;
			}
		}

		return false;
	}
}
