<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
 * W2PShop - Data Presets handler
 */

final class W2PShopDataPresetsHandler {
	public string $data_presets_table_name = 'w2pshop_data_presets';
	public W2PShopDbHelper $db_helper;

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

	public function init(): void {
		// W2PShop Hooks
		add_action( 'w2pshop_loaded', array( $this, 'w2pshop_loaded' ) );
	}

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

    /**
	 * Checks if the AI Data Preset based on historical data 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_historical_data' ) );
	}

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

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

		if ( W2PSHOPCORE_VERSION !== $w2shop_handler_db_version ) {

			$sql = 'id BIGINT(20) UNSIGNED AUTO_INCREMENT NOT NULL,
                    reference_key NVARCHAR(50) COLLATE utf8_unicode_ci NOT NULL,
					type NVARCHAR(20) COLLATE utf8_unicode_ci NOT NULL,
					cust_historical_data_presets LONGTEXT COLLATE utf8_unicode_ci NOT NULL,
                    cust_preview LONGTEXT COLLATE utf8_unicode_ci NULL,
					linked_product_name NVARCHAR(20) COLLATE utf8_unicode_ci NULL,
					linked_user BIGINT(50) UNSIGNED NULL,
					updated_at DATETIME COLLATE utf8_unicode_ci NOT NULL,
					PRIMARY KEY (id),
					KEY reference_key (reference_key)';

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

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

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

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

    /**
	 * Saves historical data from order details
	 *
	 * @param object $w2pshop_product_data Contains custom order meta for W2P Shop.
	 *
	 * @return void
	 */
	public function save_historical_data_from_order_details( mixed $w2pshop_product_data ): void {
		$keys = array_column($w2pshop_product_data, 'key');
		$pdfeditor_uid_index = array_search('pdfeditor_unique_id', $keys);
		$linked_product_id = ($pdfeditor_uid_index !== false) ? $w2pshop_product_data[$pdfeditor_uid_index]->value : '';

		$customer_preview_index = array_search('pdfeditor_thumbnail', $keys);
		$customer_preview = ($customer_preview_index !== false) ? $w2pshop_product_data[$customer_preview_index]->value : '';

		$customer_data_index = array_search('pdfeditor_data', $keys);
		$customer_data = ($customer_data_index !== false) ? $w2pshop_product_data[$customer_data_index]->value : '';

		$saved_data = array(
			'reference_key'         		=> $linked_product_id,
			'type'             				=> 'pdfeditor',
			'cust_historical_data_presets'	=> $customer_data,
			'cust_preview'					=> $customer_preview,
			'linked_product_name' 			=> '',
			'linked_user'       			=> get_current_user_id(),
			'updated_at'        			=> gmdate( 'Y-m-d H:i:s' ),
		);

		$customer_save_historical_index = array_search('pdfeditor_save_historical_data', $keys);
		$customer_save_historical_data = ($customer_save_historical_index !== false) ? $w2pshop_product_data[$customer_save_historical_index]->value : '';
		if ($customer_save_historical_data === 'yes') {
			$this->db_helper->insert_record( $this->data_presets_table_name, $saved_data );
		}
	}

    /**
	 * Decodes the customer saved data.
	 *
	 * @param array $get_all_historical_saved_records The array with historical data saved in a database.
	 *
	 * @return array|null Returns the array with decoded user data. 
	 */
	public function decode_presets( array $get_all_historical_saved_records ) : array|null {
		if ( ! empty( $get_all_historical_saved_records ) ) {
			$decoded_records_array = array();
			foreach( $get_all_historical_saved_records as $value ) {
				$preset = $value;
				$preset->cust_historical_data_presets = json_decode( html_entity_decode( base64_decode( $preset->cust_historical_data_presets ) ) );
				$decoded_records_array[] = $preset;
			}
			return $decoded_records_array;
		}
		return null;
	}

}