<?php

/**
 * The plugin elementor addons.
 *
 * @link       https://themeatelier.net/
 * @since      1.0.0
 *
 * @package    domain_for_sale
 * @subpackage domain_for_sale/Admin/GutenbergBlock
 * @author     ThemeAtelier <themeatelierbd@gmail.com>
 */

namespace ThemeAtelier\DomainForSale\Admin\GutenbergBlock;

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

/**
 * Gutenberg Block Initializer.
 */
class Gutenberg_Block_Init
{

	/**
	 * Script and style suffix
	 *
	 * @since 2.5.3
	 * @access protected
	 * @var string
	 */
	protected $suffix;
	/**
	 * Custom Gutenberg Block Initializer.
	 */
	public function __construct()
	{
		$this->suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG || defined('WP_DEBUG') && WP_DEBUG ? '' : '.min';
		add_action('plugins_loaded', array($this, 'domain_for_sale_plugin_loaded'));

		add_action('init', array($this, 'dfs_gutenberg_shortcode_block'));
		add_action('enqueue_block_editor_assets', array($this, 'dfs_block_editor_assets'));
	}

	/**
	 * Register category for Testimonial blocks
	 */
	public function domain_for_sale_plugin_loaded()
	{
		if (version_compare($GLOBALS['wp_version'], '5.7', '<')) {
			add_filter('block_categories', array($this, 'domain_for_sale_block_category'));
		} else {
			add_filter('block_categories_all', array($this, 'domain_for_sale_block_category'));
		}
	}

	/**
	 * Method to register testimonial blocks category
	 *
	 * @param $categories
	 *
	 * @return $categories array
	 */
	public function domain_for_sale_block_category($categories)
	{
		return array_merge(
			array(
				array(
					'slug'  => 'domain-for-sale',
					'title' => __('Domain For Sale', 'domain-for-sale'),
				),
			),
			$categories
		);
	}

	/**
	 * Register block editor script for backend.
	 */
	public function dfs_block_editor_assets()
	{
		wp_enqueue_script(
			'domain-for-sale-shortcode-block',
			plugins_url('/GutenbergBlock/build/index.js', __DIR__),
			array('jquery', 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-components'),
			DOMAIN_FOR_SALE_VERSION,
			true
		);

		/**
		 * Register block editor css file enqueue for backend.
		 */
		wp_enqueue_style('ico-font');
		wp_enqueue_style('sweetalert2');
		wp_enqueue_style('domain-for-sale-style');

		$domain_for_sale_posts = new \WP_Query(
			array(
				'post_type'      => 'dfs_template',
				'posts_per_page' => -1,
			)
		);
		$post_ids                  = wp_list_pluck($domain_for_sale_posts->posts, 'ID');
		$enqueue_fonts             = array();

		$domain_for_salee_google_font = true;
		foreach ($post_ids as $domain_for_sale_id) {

			// Include dynamic style file.
			$template_options = get_post_meta($domain_for_sale_id, 'dfs_template_options', true);

			if ($domain_for_salee_google_font) {
				// Google fonts.
				$body_typo              = isset($template_options['body_typo']) ? $template_options['body_typo'] : '';
				$domain_name_typo                  = isset($template_options['domain_name_typo']) ? $template_options['domain_name_typo'] : '';
				$sale_title_typo                   = isset($template_options['sale_title_typo']) ? $template_options['sale_title_typo'] : '';
				$dfs_form_title                   = isset($template_options['dfs_form_title']) ? $template_options['dfs_form_title'] : '';
				$template_options                 = get_post_meta($domain_for_sale_id, 'domain_for_sale_view_options', true);
				$all_fonts                        = array();
				$domain_for_sale_typography   = array();
				$domain_for_sale_typography[] = $body_typo;
				$domain_for_sale_typography[] = $domain_name_typo;
				$domain_for_sale_typography[] = $sale_title_typo;
				$domain_for_sale_typography[] = $dfs_form_title;
				$domain_for_sale_typography[] = isset($template_options['read_more_typography']) ? $template_options['read_more_typography'] : array(
					'font-family'        => '',
					'font-weight'        => '600',
					'subset'             => '',
					'font-size'          => '12',
					'tablet-font-size'   => '12',
					'mobile-font-size'   => '10',
					'line-height'        => '18',
					'tablet-line-height' => '18',
					'mobile-line-height' => '16',
					'letter-spacing'     => '0',
					'text-align'         => 'left',
					'text-transform'     => 'uppercase',
					'type'               => '',
					'unit'               => 'px',
				);

				if (! empty($domain_for_sale_typography)) {
					foreach ($domain_for_sale_typography as $font) {
						if (isset($font['font-family']) && isset($font['type']) && 'google' === $font['type']) {
							$variant     = (isset($font['font-weight']) && '' !== $font['font-weight']) ? ':' . $font['font-weight'] : '';
							$all_fonts[] = $font['font-family'] . $variant;
						}
					}
				}
				if ($all_fonts) {
					$enqueue_fonts[] = $all_fonts;
				}
			}
		}

		// Enqueue Google fonts.
		if ($domain_for_salee_google_font && ! empty($enqueue_fonts)) {
			wp_enqueue_style('domain-for-sale-google-fonts', esc_url(add_query_arg('family', rawurlencode(implode('|', array_merge(...$enqueue_fonts))), '//fonts.googleapis.com/css')), array(), DOMAIN_FOR_SALE_VERSION, false);
		}
	}

	/**
	 * Testimonials Shortcode list.
	 *
	 * @return array
	 */
	public function dfs_post_list()
	{
		$shortcodes = get_posts(
			array(
				'post_type'      => 'dfs_template',
				'post_status'    => 'publish',
				'posts_per_page' => -1,
			)
		);

		if (count($shortcodes) < 1) {
			return array();
		}

		return array_map(
			function ($shortcode) {
				return (object) array(
					'id'    => absint($shortcode->ID),
					'title' => esc_html($shortcode->post_title),
				);
			},
			$shortcodes
		);
	}

	/**
	 * Register Gutenberg shortcode block.
	 */
	public function dfs_gutenberg_shortcode_block()
	{
		/**
		 * Register block editor js file enqueue for backend.
		 */
		wp_register_script(
			'domain-for-sale-gb',
			DOMAIN_FOR_SALE_URL . '/src/Admin/GutenbergBlock/assets/gutenberg-block.js',
			array('wp-blocks', 'wp-element', 'wp-editor', 'jquery'),
			DOMAIN_FOR_SALE_VERSION,
			true
		);
		wp_register_style('template_editor_css', DOMAIN_FOR_SALE_URL . '/src/Admin/GutenbergBlock/build/style-index.css', array(), DOMAIN_FOR_SALE_VERSION, 'all');

		// Localize script
		wp_localize_script(
			'domain-for-sale-gb',
			'confirmation',
			array(
				'ajax_url'      => admin_url('admin-ajax.php'),
				'nonce'         => wp_create_nonce('domain_for_sale_email_nonce'),
				'loadScript'    => DOMAIN_FOR_SALE_URL . '/src/Frontend/assets/js/domain-for-sale-script.js',
				'link'          => esc_url(admin_url('post-new.php?post_type=dfs_template')),
				'shortCodeList' => $this->dfs_post_list(),
			)
		);

		/**
		 * Register Gutenberg block on server-side.
		 */
		if (!\WP_Block_Type_Registry::get_instance()->is_registered('create-block/domain-for-sale-template')) {
		register_block_type(
			'create-block/domain-for-sale-template',
			array(
				'title'           => __('Domain For Sale Template', 'domain-for-sale'),
				'description'     => __('A block to insert Domain For Sale templates.', 'domain-for-sale'),
				'category'        => 'domain-for-sale',
				'icon'            => 'admin-site',
				'editorStyle'     => 'file:./build/index.css',
				'style'           => 'file:./build/style-index.css',
				'attributes'      => array(
					'shortcode'        => array(
						'type'    => 'string',
						'default' => '0',
					),
					'shortcodeContent' => array(
						'type'    => 'boolean',
						'default' => true,
					),
					'is_admin'         => array(
						'type'    => 'boolean',
						'default' => is_admin(),
					),
					'preview'            => array(
						'type'    => 'boolean',
						'default' => false,
					),
				),
				'editor_script'   	=> 'domain-for-sale-gb',
				'editor_style'    	=> array('template_editor_css'),
				'render_callback' 	=> array($this, 'domain_for_sale_render_shortcode'),
				'example'  => array(
					'attributes' => array(
						'preview' => true,
					),
				)
			)
		);
	}
	}

	public function domain_for_sale_render_shortcode($attributes)
	{
		$class_name = !empty($attributes['className']) ? $attributes['className'] : '';

		// Regular outpu	t for frontend
		if (! $attributes['is_admin']) {
			return '<div class="' . esc_attr($class_name) . '">'
				. do_shortcode('[domain_for_sale id="' . $attributes['shortcode'] . '"]')
				. '</div>';
		}

		// Display edit button in admin
		$edit_page_link = get_edit_post_link(sanitize_text_field($attributes['shortcode']));
		return '<div id="' . uniqid() . '" class="' . esc_attr($class_name) . '">'
			. '<a href="' . esc_url($edit_page_link) . '" target="_blank" class="domain_for_sale_block_edit_button">'
			. esc_html__('Edit View', 'domain-for-sale') . '</a>'
			. do_shortcode('[domain_for_sale id="' . $attributes['shortcode'] . '"]')
			. '</div>';
	}
}
