<?php

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

if ( !is_admin() ) {
    return;
}

class Newsx_Core_Customizer_Importer {
	/**
	 * Import customizer from a DAT file, generated by the Customizer Export/Import plugin.
	 */
	public static function import() {
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field(wp_unslash($_POST['nonce'])), 'newsx-core-admin' ) || !current_user_can('manage_options') ) {
            wp_send_json_error( 'Invalid nonce' );
            return;
        }

		$template = isset( $_POST['template'] ) ? $_POST['template'] : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
		$templateType = isset( $_POST['template_type'] ) ? $_POST['template_type'] : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
    
        // Ensure DAT file exists
		if ( $templateType === 'pro' && defined('NEWSX_CORE_PRO_VERSION') && newsx_core_pro_fs()->can_use_premium_code() ) {
			$import_file_path = NEWSX_CORE_PRO_PATH . 'admin/import/data/'. sanitize_file_name(wp_unslash($template)) .'/demo.dat';
		} else {
			$import_file_path = NEWSX_CORE_PATH . 'admin/import/data/'. sanitize_file_name(wp_unslash($template)) .'/demo.dat';
		}
        if ( ! file_exists( $import_file_path ) ) {
            wp_send_json_error( 'DAT file not found.' );
            return;
        }

		// Try to import the customizer settings.
		$results = self::import_customizer_options( $import_file_path );

        if ( is_wp_error( $results ) ) {
            wp_send_json_error( 'Customizer Import Failed.' );
        }
    }

	/**
	 * Imports Customizer Options.
	 */
	public static function import_customizer_options( $import_file_path ) {
		// Setup global vars.
		global $wp_customize;

		// Setup internal vars.
		$template = get_template();

		// Make sure we have an import file.
		if ( ! file_exists( $import_file_path ) ) {
			return new \WP_Error(
				'missing_cutomizer_import_file',
				sprintf( /* translators: %s - file path */
					esc_html__( 'Error: The customizer import file is missing! File path: %s', 'news-magazine-x-core' ),
					$import_file_path
				)
			);
		}

		// Get the upload data.
		$raw = Newsx_Core_Helpers::get_data_from_file( $import_file_path );

		// Make sure we got the data.
		if ( is_wp_error( $raw ) ) {
			return $raw;
		}

		$data = unserialize( $raw , [ 'allowed_classes' => false ] );

		// Data checks.
		if ( ! is_array( $data ) && ( ! isset( $data['template'] ) || ! isset( $data['mods'] ) ) ) {
			return new \WP_Error(
				'customizer_import_data_error',
				esc_html__( 'Error: The customizer import file is not in a correct format. Please make sure to use the correct customizer import file.', 'news-magazine-x-core' )
			);
		}
		if ( $data['template'] !== $template ) {
			return new \WP_Error(
				'customizer_import_wrong_theme',
				esc_html__( 'Error: The customizer import file is not suitable for current theme. You can only import customizer settings for the same theme or a child theme.', 'news-magazine-x-core' )
			);
		}

		// Import images.
		$data['mods'] = self::import_customizer_images( $data['mods'] );

        global $wp_customize;

		// Import custom options.
		if ( isset( $data['options'] ) ) {
			// Require modified customizer options class.
			if ( ! class_exists( '\WP_Customize_Setting' ) ) {
				require_once ABSPATH . 'wp-includes/class-wp-customize-setting.php';
			}

			// Require the customizer option class.
			require_once NEWSX_CORE_PATH . 'admin/import/importers/class-newsx-core-customizer-option.php';

			$upload_dir = wp_upload_dir();

			// Loop through the options and import them.
			foreach ( $data['options'] as $key => $value ) {
				// Replace any external URLs with local upload directory path
				if ('string' === gettype($value)) {
					// Extract the uploads path from the external URL if it exists
					if (preg_match('|/wp-content/uploads/|', $value)) {
						$value = preg_replace(
							'|https?://[^/]+/[^/]+/wp-content/uploads/(?:sites/\d+/)?|',
							$upload_dir['baseurl'] . '/',
							$value
						);
					}
				}
				
				// Create a new WP_Customize_Setting instance
				$setting = new Newsx_Core_Customizer_Option( $wp_customize, $key, array(
					'default'    => '',
					'type'       => 'option', // Can also be 'theme_mod' if applicable
					'capability' => 'edit_theme_options',
				) );
		
				// Use the update() method directly to save the value
				$setting->import( $value );
			}

			// Loop through the mods and save the mods.
			foreach ( $data['mods'] as $key => $value ) {
				set_theme_mod( $key, $value );
			}
		}
	}

	/**
	 * Helper function: Customizer import - imports images for settings saved as mods.
	 */
	private static function import_customizer_images( $mods ) {
		foreach ( $mods as $key => $val ) {
			if ( self::customizer_is_image_url( $val ) ) {
				$data = self::customizer_sideload_image( $val );
				if ( ! is_wp_error( $data ) ) {
					$mods[ $key ] = $data->url;

					// Handle header image controls.
					if ( isset( $mods[ $key . '_data' ] ) ) {
						$mods[ $key . '_data' ] = $data;
						update_post_meta( $data->attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() );
					}
				}
			}
		}

		return $mods;
	}

	/**
	 * Helper function: Customizer import
	 * Taken from the core media_sideload_image function and
	 * modified to return an array of data instead of html.
	 */
	private static function customizer_sideload_image( $file ) {
		$data = new \stdClass();

		if ( ! function_exists( 'media_handle_sideload' ) ) {
			require_once( ABSPATH . 'wp-admin/includes/media.php' );
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
		}
		if ( ! empty( $file ) ) {
			// Set variables for storage, fix file filename for query strings.
			preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
			$file_array = array();
			$file_array['name'] = basename( $matches[0] );

			// Download file to temp location.
			$file_array['tmp_name'] = download_url( $file );

			// If error storing temporarily, return the error.
			if ( is_wp_error( $file_array['tmp_name'] ) ) {
				return $file_array['tmp_name'];
			}

			// Do the validation and storage stuff.
			$id = media_handle_sideload( $file_array, 0 );

			// If error storing permanently, unlink.
			if ( is_wp_error( $id ) ) {
				wp_delete_file( $file_array['tmp_name'] );
				return $id;
			}

			// Build the object to return.
			$meta                = wp_get_attachment_metadata( $id );
			$data->attachment_id = $id;
			$data->url           = wp_get_attachment_url( $id );
			$data->thumbnail_url = wp_get_attachment_thumb_url( $id );
			$data->height        = $meta['height'];
			$data->width         = $meta['width'];
		}

		return $data;
	}

	/**
	 * Checks to see whether a string is an image url or not.
	 */
	private static function customizer_is_image_url( $string = '' ) {
		if ( is_string( $string ) ) {
			if ( preg_match( '/\.(jpg|jpeg|png|gif)/i', $string ) ) {
				return true;
			}
		}

		return false;
	}
}
