<?php
/**
 * Plugin Name: Section Collection
 * Description: A versatile section collection plugin featuring essential UI blocks to craft impactful, engaging, and user-centric web pages.
 * Version: 1.0.36
 * Author: bPlugins
 * Author URI: https://bplugins.com
 * License: GPLv3
 * License URI: https://www.gnu.org/licenses/gpl-3.0.txt
 * Text Domain: section-collection
 */

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

// Constant
define( 'BPSC_VERSION', isset( $_SERVER['HTTP_HOST'] ) && 'localhost' === sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) ? time() : '1.0.36' );
define( 'BPSC_DIR_URL', plugin_dir_url( __FILE__ ) );
define( 'BPSC_DIR_PATH', plugin_dir_path( __FILE__ ) );



if( !class_exists( 'BPSCPlugin' ) ){
	class BPSCPlugin{
		function __construct(){
			add_action( 'init', [ $this, 'onInit' ] );
			add_filter( 'block_editor_settings_all', [ $this, 'addLeafletEditorIframeStyle' ] );
			add_action( 'enqueue_block_editor_assets', [ $this, 'enqueueAssets' ] );
			add_action( 'wp_enqueue_scripts', [ $this, 'enqueueScripts' ] );
			add_action( 'wp_enqueue_scripts', [ $this, 'enqueueLeaflet' ] );
			add_action( 'enqueue_block_editor_assets', [ $this, 'enqueueLeaflet' ] );
			add_filter( 'block_categories_all', [$this, 'registerCategories'] );
		}

		function onInit(){
			$blocks =['testimonial_block', 'timeline_block', 'ticker', 'about-us', 'team-section', 'faq', 'call-to-actions', 'info-list-block', 'hero-section', 'pricing-table-section', 'feature-details', 'info-grid', 'feature-overview-section', 'modern-faq-section', "money-back-guarantee-card", "flip-box-section", "service-section", "counter-section", "fancy-image-box-section", "floating-image-section", "brand-sponsor-section", "slider-section", "mission-and-vision-section", "masonry-image-carousel", "multi-tab-timeline-section", "image-comparison-section", "video-showcase-section", "chart-section", "progress-section", "storytelling-section", "recommendation-section", "filterable-showcase-section", "carousel-testimonial-section", "resource-download-section","snippet-copy-section", "floating-cta-section", "orbiting-team-section", "map-section", "schedule-section", "how-it-works-section", "open-positions-section", "pricing-toggle-section", "social-proof-wall-section", "awards-recognition-section", "tabbed-feature-showcase-section", "food-menu-section", "roi-calculator-section", "press-mentions-section", "project-portfolio-section", "lead-quiz-section", "announcement-bar-section"];
			foreach ( $blocks as $block ) {
				register_block_type( __DIR__ . "/build/".$block );
			}
		}
		function enqueueAssets(){
			wp_enqueue_style( 'bndl-style', BPSC_DIR_URL . 'build/index.css', [], BPSC_VERSION );
			wp_enqueue_script( 'bndl-script', BPSC_DIR_URL . 'build/index.js', ['wp-blocks'], BPSC_VERSION, true );
		}

		function enqueueScripts(){
			wp_enqueue_script( 'bndl-advanced-script', BPSC_DIR_URL . 'build/advanced.js', [], BPSC_VERSION, true );
		}

		function registerCategories( $categories ){
			return array_merge( [ [
				'slug'	=> 'bPlugins',
				'title'	=> __( 'Section Collection', 'section-collection' ),
			] ], $categories );
		} 
		function enqueueLeaflet() {
			// is_admin() covers the block editor. On the frontend we also check
			// the full template (FSE template parts / synced patterns), since
			// has_block() on post content alone can miss blocks placed there.
			$has_map = is_admin() || has_block( 'bpsc/map-section' );

			if ( ! $has_map && function_exists( 'wp_is_block_theme' ) && wp_is_block_theme() ) {
				global $_wp_current_template_content;
				if ( ! empty( $_wp_current_template_content ) && has_block( 'bpsc/map-section', $_wp_current_template_content ) ) {
					$has_map = true;
				}
			}

			if ( $has_map ) {
				$leaflet_js  = BPSC_DIR_PATH . 'assets/leaflet/leaflet.js';
				$leaflet_css = BPSC_DIR_PATH . 'assets/leaflet/leaflet.css';
				$has_local   = file_exists( $leaflet_js ) && file_exists( $leaflet_css );

				if ( file_exists( $leaflet_css ) ) {
					wp_enqueue_style(
						'leaflet',
						BPSC_DIR_URL . 'assets/leaflet/leaflet.css',
						[],
						'1.9.4'
					);
				}
				if ( file_exists( $leaflet_js ) ) {
					wp_enqueue_script(
						'leaflet',
						BPSC_DIR_URL . 'assets/leaflet/leaflet.js',
						[],
						'1.9.4',
						true
					);
				}

				// Safety net: if the locally bundled Leaflet is unavailable (so
				// window.L never loaded), pull it from the public CDN at runtime so
				// the Map block still renders. The URL lives in a JS string (not in
				// a wp_enqueue_* call), so no asset is offloaded by the plugin.
				if ( ! $has_local ) {
					add_action( 'wp_footer', [ $this, 'printLeafletFallback' ], 5 );
					add_action( 'admin_footer', [ $this, 'printLeafletFallback' ], 5 );
				}
			}
		}

		/**
		 * Runtime fallback that injects Leaflet from the CDN only when the locally
		 * bundled copy is missing. Kept out of the asset-enqueue system on purpose.
		 */
		function printLeafletFallback() {
			$css = esc_url( 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css' );
			$js  = esc_url( 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js' );
			?>
			<script>
			( function () {
				if ( window.L ) { return; }
				var c = document.createElement( 'link' );
				c.rel = 'stylesheet';
				c.href = <?php echo wp_json_encode( $css ); ?>;
				document.head.appendChild( c );
				var s = document.createElement( 'script' );
				s.src = <?php echo wp_json_encode( $js ); ?>;
				document.head.appendChild( s );
			} )();
			</script>
			<?php
		}

		/**
		 * The modern block editor renders the canvas inside an iframe with its own
		 * document. Styles enqueued via enqueue_block_editor_assets land in the
		 * OUTER page, not the iframe, so Leaflet's CSS never reaches the map and
		 * tiles render unstyled/scattered in the editor. Injecting the bundled
		 * Leaflet CSS through the editor settings 'styles' array places it inside
		 * the iframe canvas, which is where the block (and therefore the map)
		 * actually renders.
		 */
		function addLeafletEditorIframeStyle( $settings ) {
			$leaflet_css_path = BPSC_DIR_PATH . 'assets/leaflet/leaflet.css';
			if ( ! isset( $settings['styles'] ) || ! is_array( $settings['styles'] ) ) {
				$settings['styles'] = [];
			}
			if ( file_exists( $leaflet_css_path ) ) {
				$settings['styles'][] = [
					'css' => file_get_contents( $leaflet_css_path ), // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading a bundled local CSS file.
				];
			} else {
				// Fallback when the bundled CSS is unavailable. The URL lives in a
				// CSS @import string, not in a wp_enqueue_* call.
				$settings['styles'][] = [
					'css' => "@import url('https://unpkg.com/leaflet@1.9.4/dist/leaflet.css');",
				];
			}
			return $settings;
		}
	}

	
	new BPSCPlugin();
}

