<?php

/**
 * Plugin Name: Tabbed Contents Block
 * Description: Display responsive, accessible tabs featuring dynamic content.
 * Version: 1.2.2
 * Author: bPlugins
 * Author URI: https://bplugins.com
 * License: GPLv3
 * License URI: https://www.gnu.org/licenses/gpl-3.0.txt
 * Text Domain: tabbed-contents
  * @fs_free_only, /vendor/freemius-lite, /inc/fs-lite.php
 */

// ABS PATH
if (!defined('ABSPATH')) {
	exit;
}


if (function_exists('tc_fs')) {

	tc_fs()->set_basename(true, __FILE__);

} else {
	// Constant
	define('TCB_VERSION', isset($_SERVER['HTTP_HOST']) && 'localhost' === $_SERVER['HTTP_HOST'] ? time() : '1.2.2');
	define('TCB_DIR_URL', plugin_dir_url(__FILE__));
	define('TCB_DIR_PATH', plugin_dir_path(__FILE__));
	define( 'TCB_HAS_PRO', file_exists( TCB_DIR_PATH . 'vendor/freemius/start.php' ) );


	if ( TCB_HAS_PRO ) {
        require_once TCB_DIR_PATH . 'inc/fs.php';
    } else {
        require_once TCB_DIR_PATH . 'inc/fs-lite.php';
    }

	// ... Your plugin's main file logic ...

	function tcbIsPremium()
	{
		return TCB_HAS_PRO ? tc_fs()->can_use_premium_code() : false;
	}

	if (!class_exists('TCBPlugin')) {
		class TCBPlugin
		{
			public function __construct()
			{
				add_action('enqueue_block_assets', [$this, 'enqueueBlockAssets']);
				add_action('init', [$this, 'onInit']);

				// submenu function hooks
				add_action('admin_menu', [$this, 'addSubmenu']);
				add_action('admin_enqueue_scripts', [$this, 'adminEnqueueScripts']);

				// Post Type function hooks 
				add_action('init', array($this, 'tcb_tabbed_contents_post_type'));

				// shortcode type function hooks 
				add_shortcode('tabbed', [$this, 'tcb_shortcode_handler']);

				//manage column 
				add_filter('manage_tabbed_posts_columns', [$this, 'tabbedManageColumns'], 10);

				// Block category
				add_filter('block_categories_all', [$this, 'addCustomBlockCategory'], 10, 2);

				// Custom manage column 
				add_action('manage_tabbed_posts_custom_column', [$this, 'tabbedManageCustomColumns'], 10, 2);

				// frontend notice style
				add_action('wp_enqueue_scripts', [$this, 'tcb_enqueue_notice_style']);

				// ispremium recieved in editor and frontend 
				add_action('enqueue_block_editor_assets', [$this, 'enqueueBlockEditorAssets']);

			}

			// enqueue block editor assets
			// function enqueueBlockEditorAssets() {
			// 	wp_add_inline_script('tcb-advanced-tabs-editor-script', 'const tcbpipecheck = ' . json_encode(tcbIsPremium()) . ';', 'before');
			// }

			function enqueueBlockEditorAssets() {
				wp_add_inline_script(
					'tcb-advanced-tabs-editor-script',
					'window.tcbpipecheck = ' . json_encode(function_exists('tcbIsPremium') ? tcbIsPremium() : false) . ';',
					'before'
				);
			}


			// block category function
				function addCustomBlockCategory($categories, $post){
					array_unshift( $categories, [
					'slug'  => 'tabbed-contents',
					'title' => __( 'Tabbed Contents', 'tabbed-contents' ),
				]);

				return $categories;

				}


			function tcb_enqueue_notice_style() {

				wp_enqueue_style(
					'notice-style',
					plugin_dir_url(__FILE__) . 'build/notice-style.css',
					array(),
					'1.0.0'
				);

			}


			//manage column
			function tabbedManageColumns($defaults)
			{
				unset($defaults['date']);
				$defaults['shortcode'] = 'ShortCode';
				$defaults['date'] = 'Date';
				return $defaults;
			}

			// custom manage column
			function tabbedManageCustomColumns($column_name, $post_ID)
			{
				if ($column_name == 'shortcode') {
					echo '<div class="bPlAdminShortcode" id="bPlAdminShortcode-' . esc_attr($post_ID) . '">
					<input value="[tabbed id=' . esc_attr($post_ID) . ']" onclick="copyBPlAdminShortcode(\'' . esc_attr($post_ID) . '\')" readonly>
					<span class="tooltip">Copy To Clipboard</span>
				</div>';
				}
			}

			function tcb_shortcode_handler($atts)
			{
				$post_id = $atts['id'];
				$post = get_post($post_id);
				if (!$post) {
					return '';
				}
				if (post_password_required($post)) {
					return get_the_password_form($post);
				}
				switch ($post->post_status) {
					case 'publish':
						return $this->displayContent($post);
					case 'private':
						if (current_user_can('read_private_posts')) {
							return $this->displayContent($post);
						}
						return '';
					case 'draft':
					case 'pending':
					case 'future':
						if (current_user_can('edit_post', $post_id)) {
							return $this->displayContent($post);
						}
						return '';
					default:
						return '';
				}
			}


			function displayContent($post)
			{
				$blocks = parse_blocks($post->post_content);
				return render_block($blocks[0]);
			}

			


			// Custom Post Type function calls
			function tcb_tabbed_contents_post_type()
			{

				register_post_type(
					'tabbed',
					array(
						'label' => 'Tabbed Contents',
						'labels' => [
							'name' => 'Tabbed Contents',
							'singular_name' => 'Tabbed Contents',
							'menu_name' => 'Tabbed Contents',
							'all_items' => 'ShortCode Generator',
							'add_new' => 'Add New ShortCode',
							'add_new_item' => 'Add New ShortCode',
							'edit_item' => 'Edit Tabbed',
							'not_found' => 'There is no tabbed please add one',
							'item_published' => 'Tabbed Contents Published',
							'item_updated' => 'Tabbed Contents Updated'
						],
						'public' => false,
						'show_ui' => true,
						'show_in_rest' => true,
						'menu_icon' =>  'dashicons-welcome-widgets-menus',
						'template' => tcbIsPremium() ? [['tcb/cpt-parent-advanced-tabs']] : [[
								'tcb/tabs',
								[],
								[['tcb/tab'], ['tcb/tab'], ['tcb/tab']],
							]],
						'template_lock' => 'all',
					)
				);
			}

			function enqueueBlockAssets()
			{
				wp_register_style('fontAwesome', TCB_DIR_URL . 'public/css/font-awesome.min.css', [], '6.4.2');
			}
			
			
			function onInit()
			{
				$blocks=['tabs', 'tab', 'advanced-tabs', 'advanced-tab','cpt-parent-advanced-tabs'];

				foreach($blocks as $block){
						register_block_type(__DIR__ . "/build/{$block}");
				}
			}

			// All hooks function call here
			function addSubmenu()
			{
				add_submenu_page(
					'edit.php?post_type=tabbed',
					'Demo Page',
					'Help & Demos',
					'manage_options',
					'tcb_demo_page',
					[$this, 'tcb_render_demo_page']
				);
			}

			function renderTemplate($content)
			{
				$parseBlocks = parse_blocks($content);
				return render_block($parseBlocks[0]);
			}

		function tcb_render_demo_page() {
			?>
			<div id="tcbDashboard"
							data-info="<?php echo esc_attr(wp_json_encode([
									'version'=>TCB_VERSION,
									'isPremium' =>tcbIsPremium(),
									'hasPro' => TCB_HAS_PRO,
                            		'licenseActiveNonce' => wp_create_nonce( 'bPlLicenseActivation' )
							]))?>"
							>
			</div>
			<?php
		}

			function adminEnqueueScripts()
			{
				// shortcode copy script and style
				wp_enqueue_style('shortcode-style', TCB_DIR_URL . 'build/shortcode-style.css', [], TCB_VERSION);
				wp_enqueue_script('shortcode-js', TCB_DIR_URL . 'build/shortcode-js.js', [], TCB_VERSION, true);

				wp_register_script('tcb-view', TCB_DIR_URL . 'build/tabs/view.js', ['react', 'react-dom'], TCB_VERSION);
				wp_register_style('fontAwesome', TCB_DIR_URL . 'public/css/font-awesome.min.css', [], TCB_VERSION);
				wp_register_style('tcb-view', TCB_DIR_URL . 'build/tabs/view.css', ['fontAwesome'], TCB_VERSION);

				wp_enqueue_script('fs', TCB_DIR_URL . 'public/js/fs.js', [], '1');
				wp_enqueue_style('tcb-dashboard-style', TCB_DIR_URL . 'build/dashboard.css', ['tcb-view'], TCB_VERSION);
				wp_enqueue_script('tcb-dashboard-help', TCB_DIR_URL . 'build/dashboard.js', ['react', 'react-dom', 'wp-components', 'fs', 'wp-util'], TCB_VERSION);
				wp_set_script_translations('tcb-dashboard-help', 'tabbed-contents', TCB_DIR_PATH . 'languages');
			}


			static function getIconCSS($icon, $isSize = true, $isColor = true)
			{
				extract($icon);
				$fontSize = $fontSize ?? 16;
				$colorType = $colorType ?? 'solid';
				$color = $color ?? 'inherit';
				$gradient = $gradient ?? 'linear-gradient(135deg, #4527a4, #8344c5)';

				$colorCSS = 'gradient' === $colorType ?
					"color: transparent; background-image: $gradient; -webkit-background-clip: text; background-clip: text;" :
					"color: $color;";

				$styles = '';
				$styles .= !$fontSize || !$isSize ? '' : "font-size: " . esc_attr($fontSize) . "px;";
				$styles .= $isColor ? $colorCSS : '';

				return $styles;
			}

			static function getColorsCSS($colors)
			{
				extract($colors);
				$color = $color ?? '#333';
				$bgType = $bgType ?? 'solid';
				$bg = $bg ?? '#0000';
				$gradient = $gradient ?? 'linear-gradient(135deg, #4527a4, #8344c5)';

				$background = $bgType === 'gradient' ? $gradient : $bg;

				$styles = '';
				$styles .= $color ? "color: " . esc_attr($color) . ";" : '';
				$styles .= ($gradient || $bg) ? "background: " . esc_attr($background) . ";" : '';

				return $styles;
			}

			static function getBackgroundCSS($bg, $isSolid = true, $isGradient = true, $isImage = true)
			{
				extract($bg);
				$type = $type ?? 'solid';
				$color = $color ?? '#F5F0BB';
				$gradient = $gradient ?? 'linear-gradient(135deg, #4527a4, #8344c5)';
				$image = $image ?? [];
				$position = $position ?? 'center center';
				$attachment = $attachment ?? 'initial';
				$repeat = $repeat ?? 'no-repeat';
				$size = $size ?? 'cover';
				$overlayColor = $overlayColor ?? '#F5F0BB';

				$gradientCSS = $isGradient ? "background: " . esc_attr($gradient) . ";" : '';

				$imgUrl = $image['url'] ?? '';
				$imageCSS = $isImage ? "background: url(" . esc_url($imgUrl) . "); background-color: " . esc_attr($overlayColor) . "; background-position: " . esc_attr($position) . "; background-size: " . esc_attr($size) . "; background-repeat: " . esc_attr($repeat) . "; background-attachment: " . esc_attr($attachment) . "; background-blend-mode: overlay;" : '';

				$solidCSS = $isSolid ? "background: " . esc_attr($color) . ";" : '';

				$styles = 'gradient' === $type ? $gradientCSS : ('image' === $type ? $imageCSS : $solidCSS);

				return $styles;
			}

			static function generateCss($value, $cssProperty)
			{
				return !$value ? '' : "$cssProperty: $value;";
			}

			static function getTypoCSS($selector, $typo, $isFamily = true)
			{
				extract($typo);
				$fontFamily = $fontFamily ?? 'Default';
				$fontCategory = $fontCategory ?? 'sans-serif';
				$fontVariant = $fontVariant ?? 400;
				$fontWeight = $fontWeight ?? 400;
				$isUploadFont = $isUploadFont ?? true;
				$fontSize = $fontSize ?? ['desktop' => 15, 'tablet' => 15, 'mobile' => 15];
				$fontStyle = $fontStyle ?? 'normal';
				$textTransform = $textTransform ?? 'none';
				$textDecoration = $textDecoration ?? 'auto';
				$lineHeight = $lineHeight ?? '135%';
				$letterSpace = $letterSpace ?? '0px';

				$isEmptyFamily = !$isFamily || !$fontFamily || 'Default' === $fontFamily;
				$desktopFontSize = $fontSize['desktop'] ?? $fontSize;
				$tabletFontSize = $fontSize['tablet'] ?? $desktopFontSize;
				$mobileFontSize = $fontSize['mobile'] ?? $tabletFontSize;

				$styles = ($isEmptyFamily ? '' : "font-family: '$fontFamily', $fontCategory;")
					. self::generateCss($fontWeight, 'font-weight')
					. 'font-size: ' . $desktopFontSize . ';'
					. self::generateCss($fontStyle, 'font-style')
					. self::generateCss($textTransform, 'text-transform')
					. self::generateCss($textDecoration, 'text-decoration')
					. self::generateCss($lineHeight, 'line-height')
					. self::generateCss($letterSpace, 'letter-spacing');

				// Google font link
				$linkQuery = (!$fontVariant || 400 === $fontVariant) ? '' : ('400i' === $fontVariant ? ':ital@1' : (false !== strpos($fontVariant, '00i') ? ': ital, wght@1, ' . str_replace('00i', '00', $fontVariant) . ' ' : ": wght@$fontVariant "));

				$link = $isEmptyFamily ? '' : 'https://fonts.googleapis.com/css2?family=' . str_replace(' ', '+', $fontFamily) . "$linkQuery&display=swap";

				return [
					'googleFontLink' => !$isUploadFont || $isEmptyFamily ? '' : "@import url( $link );",
					'styles' => preg_replace('/\s+/', ' ', trim("
						$selector{ $styles }
						@media (max-width: 768px) {
							$selector{ font-size: $tabletFontSize" . "px; }
						}
						@media (max-width: 576px) {
							$selector{ font-size: $mobileFontSize" . "px; }
						}
					"))
				];
			}

			public static function getBorderBoxCSS($border)
			{
				if (empty($border)) {
					return '';
				}

				// Closure to generate individual border CSS
				$generateBorderCSS = function ($borderObj) {
					$color = isset($borderObj['color']) ? $borderObj['color'] : '#000000';
					$style = isset($borderObj['style']) ? $borderObj['style'] : 'solid';
					$width = isset($borderObj['width']) ? $borderObj['width'] : '0px';
					return "$width $style $color";
				};

				// If the border is an associative array
				if (is_array($border) && array_keys($border) !== range(0, count($border) - 1)) {
					$sides = ['top', 'right', 'bottom', 'left'];
					$css = '';

					foreach ($sides as $side) {
						if (isset($border[$side])) {
							$css .= "border-$side: " . $generateBorderCSS($border[$side]) . "; ";
						}
					}

					// If no specific sides are defined, treat it as a general border
					if (empty(trim($css))) {
						$css = "border: " . $generateBorderCSS($border) . ";";
					}

					return trim($css);
				}

				return '';
			}
		}
		new TCBPlugin();
	}

	if (TCB_HAS_PRO) {
		require_once TCB_DIR_PATH . 'inc/LicenseActivation.php';
	}

}
