<?php
/*
Plugin Name: Divi Advanced Tabs
Plugin URI:  https://www.divigear.com/product/divi-advanced-tabs/
Description: Divi Advanced Tabs for creating attractive tab design with most advanced features.
Version:     1.0.7
Author:      DiviGear
Author URI:  https://www.divigear.com/
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: dgat-advanced-tabs
Domain Path: /languages
*/

/**
 * define version and dir paths
 * 
 */
if(!defined('DGAT_VERSION')) {
	define('DGAT_VERSION','1.0.7');
}
if(!defined('DGAT_MAIN_DIR')) {
	define('DGAT_MAIN_DIR', __DIR__);
}
if(!defined('DGAT_MAIN_FILE_PATH')) {
	define('DGAT_MAIN_FILE_PATH', __FILE__);
}
if(!defined('DGAT_CORE_DIR_PATH')) {
	define('DGAT_CORE_DIR_PATH', plugin_dir_path( __FILE__ ) . 'core/');
}
if(!defined('DGAT_PUBLIC_DIR')) {
	define('DGAT_PUBLIC_DIR', trailingslashit(plugin_dir_url(__FILE__)) );
}
if(!defined('DGAT_ASSETS_DIR')) {
	define('DGAT_ASSETS_DIR', trailingslashit(plugin_dir_url(__FILE__)) . 'assets/');
}
if(!defined('DGAT_ASSETS_DIR_PATH')) {
	define('DGAT_ASSETS_DIR_PATH', plugin_dir_path( __FILE__ ) . 'assets/');
}

/**
 * license dashboard
 */
if(file_exists(DGAT_CORE_DIR_PATH . 'init.php')) {
	require_once (__DIR__ . '/core/init.php');
}


/**
 * Register front-end scripts and styles
 *
 * @since 1.0.0
 */
add_action('wp_enqueue_scripts', 'dg_enqueue_scripts');
function dg_enqueue_scripts() {
	// lib scripts
	wp_register_script( 'dgat-animejs', DGAT_ASSETS_DIR . 'js/lib/anime.js', array('jquery'), DGAT_VERSION , true );
	wp_register_script( 'dgat-sticky-script', DGAT_ASSETS_DIR . 'js/lib/hc-sticky.js', array('jquery'), DGAT_VERSION , true );
  
	// custom scripts
	wp_register_script( 'dgat-tabs', DGAT_ASSETS_DIR . 'js/dg-tabs.js', array('jquery', 'dgat-sticky-script'), DGAT_VERSION , true );

	wp_register_style( 'dgat-builder-styles', DGAT_ASSETS_DIR . 'css/dg-builder.css', array(), DGAT_VERSION );
	wp_enqueue_style('dgat-builder-styles');
}

/**
 * Register admin scripts and styles
 *
 * @since 1.0.0
 */
add_action('admin_enqueue_scripts', 'dg_admin_enqueue_scripts');
function dg_admin_enqueue_scripts() {

	$screen = get_current_screen();

	// custom styles
	wp_register_style( 'dgat-builder-styles', DGAT_ASSETS_DIR . 'css/dg-builder.css', array(), DGAT_VERSION );
	wp_enqueue_style('dgat-builder-styles');

	if (isset($screen->base) && $screen->id === 'edit-et_pb_layout') {
		wp_register_style( 'dgat-shortcode-copy-style', DGAT_ASSETS_DIR . 'css/dg-shortcode-copy.css', array(), DGAT_VERSION );
		wp_enqueue_style('dgat-shortcode-copy-style');

		wp_register_script( 'dgat-shortcode-copy-script', DGAT_ASSETS_DIR . 'js/dg-shortcode-copy.js', array(), DGAT_VERSION, true );
		wp_enqueue_script('dgat-shortcode-copy-script');
	}
}

if ( ! function_exists( 'dg_initialize_extension' ) ):
/**
 * Creates the extension's main class instance.
 *
 * @since 1.0.0
 */
function dg_initialize_extension() {
	require_once plugin_dir_path( __FILE__ ) . 'includes/AdvancedTabModule.php';
}
add_action( 'divi_extensions_init', 'dg_initialize_extension' );
endif;


// Create New Admin Column
add_filter( 'manage_et_pb_layout_posts_columns', 'dgat_shortcode_create_shortcode_column', 5 );
function dgat_shortcode_create_shortcode_column( $columns ) {
    $columns['dgat_shortcode_id'] = __( 'Shortcode', 'dg_avbanced_tab');
    return $columns;
}
// Display Shortcode
add_action( 'manage_et_pb_layout_posts_custom_column', 'dgat_shortcode_content', 5, 2 );
function dgat_shortcode_content ( $column, $id ) {
    if( 'dgat_shortcode_id' == $column ) {
        $value = sprintf('[dgat_layout_shortcode id="%1$s"]', esc_attr( $id ));
        ?>
        <div class="dgat-shortcode-wrapper">
            <p class="dgat-shortcode-copy"><?php echo esc_html($value); ?></p>
            <p class="dgat-cpy-tooltip">Click to copy</p>
        </div>
        <?php
    }
}
// Function to show the module
function dgat_module_shortcode_callback($atts) {
	$atts = shortcode_atts(array('id' => ''), $atts);
	return do_shortcode('[et_pb_section global_module="'.  esc_attr($atts['id']).'"][/et_pb_section]');	
}
add_shortcode('dgat_layout_shortcode', 'dgat_module_shortcode_callback');


/**
 * Filter through the selector and remove the wrapper if any
 * 
 * @param String $selector the css selector
 * @param String $function_name
 */
add_filter('et_pb_set_style_selector', 'dgat_remove_css_selector_wrapper', 99999, 2);
function dgat_remove_css_selector_wrapper($selector, $function_name) {
	//when Builder plugin not active
	if ( ! df_is_divi_builder_plugin_active() && strpos($selector, 'dgat_') ) {
        $selector = str_replace( '.et-db ', "", $selector );
        $selector = str_replace( '#et-boc ', "", $selector );
        $selector = str_replace( '.et-l ', "", $selector );
	}
	
    return $selector;
}

if ( ! function_exists( 'df_is_divi_builder_plugin_active' ) ):
	/**
	 * Returns boolean if the Divi Builder Plugin active in the current WordPress installation
	 *
	 * @return boolean
	 * @since 1.0.0
	 */
	function df_is_divi_builder_plugin_active() {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			include_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		return is_plugin_active( 'divi-builder/divi-builder.php' );
	}
endif;

/**
 * Render Divi library item
 * 
 */
function dg_render_library_layout($id) {
    $module_slugs = ET_Builder_Element::get_module_slugs_by_post_type();
    $uuid = uniqid();
    // TODO: This array could be cached as it never changes (unlike the replacements which need the uuid)
    $map_to_regex = function ($value) {return '/' . $value . '_(\d+)(_tb_footer|)(,|\.|:| |")/';};
    $regex = array_map($map_to_regex, $module_slugs);

    $map_to_replacements = function ($value) use ($uuid) {return 'df_' . $uuid . '_' . $value . '_${1}${2}${3}';};
    $replacements = array_map($map_to_replacements, $module_slugs);

    $divi_library_shortcode = do_shortcode('[et_pb_section global_module="' . $id . '"][/et_pb_section]');
    $divi_library_shortcode .= '<style type="text/css">' . ET_Builder_Element::get_style() . '</style>';
    ET_Builder_Element::clean_internal_modules_styles(false);

    return preg_replace($regex, $replacements, $divi_library_shortcode);
}

function dg_load_library() {
    $args = array(
        'post_type'      => 'et_pb_layout',
        'posts_per_page' => -1,
    );

    if ( false === ( $dg_library_list = get_transient( 'dg_load_library' ) ) ) {

        $dg_library_list = array( 'none' => '-- Select Library --' );

        if ( $categories = get_posts( $args ) ) {
            foreach ( $categories as $category ) {
                $dg_library_list[ $category->ID ] = $category->post_title;
            }
        }

        set_transient( 'dg_load_library', $dg_library_list, 24 * HOUR_IN_SECONDS );
    }

    return get_transient( 'dg_load_library' );
}
function dg_delete_library_transient() {
    delete_transient( 'dg_load_library' );
}
add_action( 'save_post_et_pb_layout', 'dg_delete_library_transient', 10, 3 );
add_action( 'deleted_post_et_pb_layout', 'dg_delete_library_transient', 10, 3 );
add_action( 'edit_post_et_pb_layout', 'dg_delete_library_transient', 10, 3 );

/* Default Value Set Function */

if ( ! function_exists( 'dg_backend_support_for_divi' ) ):
	// wp-content/plugins/divi-shop-builder/divi-shop-builder.php:1457
	function dg_backend_support_for_divi( $defs ) {


		$modules_defaults = array(
			'title'    => _x( 'Your Title Goes Here', 'Modules dummy content', 'et_builder' ),
			'subtitle' => _x( 'Subtitle goes Here', 'et_builder' ),
			'body'     => _x(
				'<p>Your content goes here. Edit or remove this text inline or in the module Content settings. You can also style every aspect of this content in the module Design settings and even apply custom CSS to this text in the module Advanced settings.</p>', // phpcs:ignore WordPress.WP.I18n.NoHtmlWrappedStrings -- Need to have p tag.
				'et_builder'
			),
			'number'   => 50,
			'button'   => _x( 'Click Here', 'Modules dummy content', 'et_builder' ),
			'icon'     => array(
				'icon_list'       => '&#x5a;||divi||400',
			),
			'image'    => array(
				'landscape'       => ET_BUILDER_PLACEHOLDER_LANDSCAPE_IMAGE_DATA,
				'portrait'        => ET_BUILDER_PLACEHOLDER_PORTRAIT_IMAGE_DATA,
			),
			'video'    => 'https://www.youtube.com/watch?v=FkQuawiGWUw',
		);

		$single_shortcode = sprintf(
			'[dgat_advancedtabitem title="%1$s" use_icon="on" font_icon="%2$s"]%3$s[/dgat_advancedtabitem]',
			$modules_defaults['title'],
			$modules_defaults['icon']['icon_list'],
			$modules_defaults['body']
		);

		$shortcodes = implode( '', array( $single_shortcode, $single_shortcode, $single_shortcode , $single_shortcode ) );


		return $defs . sprintf(
				'; window.DGAT_AdvancedTab_Backend=%s;',
				et_fb_remove_site_url_protocol(
					wp_json_encode(
						array(
							// wp-content/themes/Divi/includes/builder/functions.php:11181
							// wp-content/themes/Divi/includes/builder/frontend-builder/helpers.php:727
							
							'AdvancedTabDefault'       => array(
								'content' => et_fb_process_shortcode( $shortcodes ),
								'icon_placement' => 'flex_left'
							),
							'AdvancedTabItemDefault'  => array(
								'title'     	=> $modules_defaults['title'],
								'content'   	=> $modules_defaults['body'],
								'use_icon'      => 'on',
								'font_icon' 	=> $modules_defaults['icon']['icon_list'],
								'admin_label' 	=> 'Tab Item',
							),
						),
						ET_BUILDER_JSON_ENCODE_OPTIONS
					)
				)
			);
	}

	add_filter( 'et_fb_get_asset_definitions', 'dg_backend_support_for_divi', 11 );
endif;