<?php

namespace TotalThemeCore;

defined( 'ABSPATH' ) || exit;

/**
 * WPBakery.
 */
final class WPBakery {

	/**
	 * Init.
	 */
	public static function init() {
		add_action( 'vc_load_default_params', [ self::class, 'register_params' ] );

		if ( is_admin() || totalthemecore_call_static( 'WPBakery\Helpers', 'is_frontend_edit_mode' ) ) {
			add_filter( 'vc_get_editor_locale', [ self::class, '_filter_editor_locale' ] );
			add_action( 'vc_base_register_admin_css', [ self::class, 'register_editor_css' ] );
			add_action( 'vc_backend_editor_enqueue_js_css', [ self::class, 'enqueue_editor_scripts' ] );
			add_action( 'vc_frontend_editor_enqueue_js_css', [ self::class, 'enqueue_editor_scripts' ] );
			add_action( 'admin_footer', [ self::class, '_insert_icon_modal' ] );
			add_action( 'wp_ajax_vcex_params', [ self::class, '_vcex_params_ajax_callback' ] );
		}
	}

	/**
	 * Hooks into vc_get_editor_locale to add new strings.
	 */
	public static function _filter_editor_locale( $locale ) {
		$locale['vcex_edit_this_template'] = esc_html__( 'Edit this Template', 'total-theme-core' );
		return $locale;
	}

	/**
	 * Registers custom params.
	 */
	public static function register_params(): void {
		if ( function_exists( 'vc_add_shortcode_param' ) ) {
			require_once TTC_PLUGIN_DIR_PATH . 'inc/wpbakery/add-params.php';
		}
	}

	/**
	 * Register CSS editor scripts.
	 */
	public static function register_editor_css(): void {
		wp_register_style(
			'totalthemecore-admin-wpbakery-params',
			totalthemecore_get_css_file( 'admin/wpbakery/params' ),
			[],
			TTC_VERSION
		);
	}

	/**
	 * Enqueue editor scripts.
	 */
	public static function enqueue_editor_scripts(): void {
		wp_enqueue_style( 'wpex-chosen' );
		wp_enqueue_script( 'wpex-chosen' );

		if ( function_exists( 'totaltheme_call_static' ) ) {
			totaltheme_call_static( 'Helpers\Icon_Select', 'enqueue_scripts' );
		}

		wp_enqueue_style( 'totaltheme-components' );
		wp_enqueue_script( 'totaltheme-components' );

		// Must load after chosen for overrides to work.
		wp_enqueue_style( 'totalthemecore-admin-wpbakery-params' );

		wp_enqueue_script(
			'totalthemecore-admin-wpbakery-vc-atts',
			totalthemecore_get_js_file( 'admin/wpbakery/vc-atts' ),
			[ 'jquery' ],
			TTC_VERSION,
			true
		);

		wp_localize_script(
			'totalthemecore-admin-wpbakery-vc-atts',
			'totalthemecore_admin_wpbakery_vc_atts_params',
			[
				/**
				 * Filters the list of dynamic variables (replace_vars) available for auto suggestion
				 * in the WPBakery editor.
				 *
				 * We can't apply the 'totaltheme/replace_vars/vars' filter because it uses a callback
				 * for the value, not a label. Instead we use "totaltheme/replace_vars/choices" which is consistent
				 * with our naming conventions for select fields.
				 */
				'replace_vars_list' => (array) apply_filters(
					'totaltheme/replace_vars/choices',
					[
						'home_url'                => esc_html__( 'Home URL', 'total-theme-core' ),
						'current_url'             => esc_html__( 'Current URL', 'total-theme-core' ),
						'post_id'                 => esc_html__( 'Post ID', 'total-theme-core' ),
						'post_rating'             => esc_html__( 'Post Rating', 'total-theme-core' ),
						'post_author'             => esc_html__( 'Post Author', 'total-theme-core' ),
						'post_date'               => esc_html__( 'Post Date', 'total-theme-core' ),
						'post_modified'           => esc_html__( 'Post Modified', 'total-theme-core' ),
						'post_title'              => esc_html__( 'Post Title', 'total-theme-core' ),
						'post_slug'               => esc_html__( 'Post Slug', 'total-theme-core' ),
						'post_subheading'         => esc_html__( 'Post Subheading', 'total-theme-core' ),
						'post_excerpt'            => esc_html__( 'Post Excerpt', 'total-theme-core' ),
						'post_content'            => esc_html__( 'Post Content', 'total-theme-core' ),
						'post_type_name'          => esc_html__( 'Post Type Name', 'total-theme-core' ),
						'post_type_singular_name' => esc_html__( 'Post Type Singular Name', 'total-theme-core' ),
						'title'                   => esc_html__( 'Title', 'total-theme-core' ),
						'taxonomy'                => esc_html__( 'Taxonomy', 'total-theme-core' ),
						'term_id'                 => esc_html__( 'Term ID', 'total-theme-core' ),
						'term_name'               => esc_html__( 'Term Name', 'total-theme-core' ),
						'term_description'        => esc_html__( 'Term Description', 'total-theme-core' ),
						'permalink'               => esc_html__( 'Permalink', 'total-theme-core' ),
						'category'                => esc_html__( 'Category', 'total-theme-core' ),
						'category_link'           => esc_html__( 'Category Link', 'total-theme-core' ),
						'primary_term_id'         => esc_html__( 'Primary Term ID', 'total-theme-core' ),
						'paged'                   => esc_html__( 'Paged', 'total-theme-core' ),
						'post_count'              => esc_html__( 'Post Count', 'total-theme-core' ),
						'card_icon'               => esc_html__( 'Card Icon', 'total-theme-core' ),
						'card_running_count'      => esc_html__( 'Card Running Count', 'total-theme-core' ),
						'cf_FIELD_NAME'           => esc_html__( 'Custom Field', 'total-theme-core' ),
						'icon_ICON_NAME'          => esc_html__( 'Icon', 'total-theme-core' ),
						'acf_FIELD_KEY'           => esc_html__( 'Advanced Custom Field', 'total-theme-core' ),
						'acf_option_FIELD_KEY'    => esc_html__( 'Advanced Custom Field Option', 'total-theme-core' ),
					]
				),
			]
		);
	}

	/**
	 * Inserts the icon select modal into the page for use with the vcex_select_icon param type.
	 */
	public static function _insert_icon_modal(): void {
		if ( ( did_action( 'vc_backend_editor_render' ) || did_action( 'vc_frontend_editor_render' ) )
			&& function_exists( 'totaltheme_call_static' )
		) {
			totaltheme_call_static( 'Helpers\Icon_Select', 'render_modal' );
		}
	}

	/**
	 * Ajax callback for vcex params.
	 */
	public static function _vcex_params_ajax_callback() {
		check_ajax_referer( 'vcex_params_ajax', 'nonce' );

		if ( empty( $_POST['action'] ) ) {
			return;
		}

		$task = sanitize_text_field( wp_unslash( $_POST['task'] ) );
		$data = [];

		if ( 'refresh_choices' === $task
			&& class_exists( 'TotalThemeCore\Vcex\Setting_Choices' )
		) {
			$choices = ! empty( $_POST['choices'] ) ? sanitize_text_field( wp_unslash( $_POST['choices'] ) ) : '';
			if ( $choices ) {
				$param_settings = ! empty( $_POST['paramSettings'] ) ? sanitize_text_field( wp_unslash( $_POST['paramSettings'] ) ) : '';
				if ( $param_settings ) {
					$param_settings = json_decode( $param_settings, true );
				}
				$get_choices = (new \TotalThemeCore\Vcex\Setting_Choices( $choices, $param_settings))->get_choices();
				foreach ( $get_choices as $choice_k => $choice_v ) {
					if ( is_array( $choice_v ) ) {
						$sub_choices = $choice_v['choices'] ?? $choice_v['options'] ?? [];
						$label = $choice_v['label'] ?? $choice_k;
						$group = [
							'optgroup' => $label,
							'options'  => [],
						];
						foreach ( $sub_choices as $sub_k => $sub_v ) {
							$group['options'][] = [ $sub_k => $sub_v ];
						}
						$data[] = $group;
					} else {
						$data[] = [ $choice_k => $choice_v ];
					}
				}
			}
		}

		wp_send_json( $data );
	}

	/**
	 * Add editor form scripts.
	 */
	public static function add_editor_form_scripts(): void {
		_deprecated_function( __METHOD__, 'Total Theme Core 1.8.7' );
	}

}
