<?php
declare(strict_types=1);

/**
 * Magnific Popup asset helpers.
 *
 * Uses Divi's `magnific-popup` handle when the theme already registered it; otherwise registers
 * `dsm-magnific-popup` for plugin-owned fallback URLs.
 *
 * @package DiviSupreme
 */

if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access forbidden.' );
}

/**
 * Register Magnific Popup CSS from the active theme chain (matches Divi / Dynamic Assets path).
 *
 * @return void
 */
function dsm_register_magnific_popup_style_if_needed(): void {
	if ( wp_style_is( 'dsm-magnific-popup', 'registered' ) ) {
		return;
	}

	if ( ! function_exists( 'get_theme_file_uri' ) ) {
		return;
	}

	$mfp_css = get_theme_file_uri( 'includes/builder/feature/dynamic-assets/assets/css/magnific_popup.css' );

	if ( ! is_string( $mfp_css ) || '' === $mfp_css ) {
		return;
	}

	$version = defined( 'ET_CORE_VERSION' ) ? ET_CORE_VERSION : ( defined( 'DSM_PRO_VERSION' ) ? DSM_PRO_VERSION : '1.0.0' );

	wp_register_style(
		'dsm-magnific-popup',
		$mfp_css,
		array(),
		$version
	);
}

/**
 * Register Magnific Popup script when Divi/Core has not already registered `magnific-popup`.
 *
 * Resolution order (first wins): Divi constant `ET_BUILDER_5_URI`, parent/child relative file path,
 * classic Divi dynamic-assets Magnific URI.
 *
 * @return bool Whether an active Magnific script handle is available.
 */
function dsm_register_magnific_popup_script_if_needed(): bool {
	if ( wp_script_is( 'magnific-popup', 'registered' ) ) {
		return true;
	}

	if ( wp_script_is( 'dsm-magnific-popup', 'registered' ) ) {
		return true;
	}

	$version = defined( 'ET_CORE_VERSION' ) ? ET_CORE_VERSION : ( defined( 'DSM_PRO_VERSION' ) ? DSM_PRO_VERSION : '1.0.0' );

	$url = '';
	if ( defined( 'ET_BUILDER_5_URI' ) && is_string( ET_BUILDER_5_URI ) && '' !== ET_BUILDER_5_URI ) {
		$url = trailingslashit( ET_BUILDER_5_URI ) . 'visual-builder/build/script-library-magnific-popup.js';
	}

	if ( '' === $url && function_exists( 'get_theme_file_uri' ) ) {
		$candidate = get_theme_file_uri( 'includes/builder-5/visual-builder/build/script-library-magnific-popup.js' );
		if ( is_string( $candidate ) && '' !== $candidate ) {
			$url = $candidate;
		}
	}

	if ( '' === $url && function_exists( 'get_theme_file_uri' ) ) {
		$candidate = get_theme_file_uri( 'includes/builder/feature/dynamic-assets/assets/js/magnific-popup.js' );
		if ( is_string( $candidate ) && '' !== $candidate ) {
			$url = $candidate;
		}
	}

	if ( '' === $url ) {
		return false;
	}

	wp_register_script(
		'dsm-magnific-popup',
		$url,
		array( 'jquery' ),
		$version,
		true
	);

	return true;
}

/**
 * Enqueue Magnific Popup for modules using `$.fn.magnificPopup`.
 *
 * @return void
 */
function dsm_enqueue_magnific_popup_assets() {
	dsm_register_magnific_popup_script_if_needed();
	dsm_register_magnific_popup_style_if_needed();

	if ( wp_style_is( 'dsm-magnific-popup', 'registered' ) ) {
		wp_enqueue_style( 'dsm-magnific-popup' );
	}

	$handle = dsm_get_active_magnific_popup_script_handle();
	if ( '' !== $handle ) {
		wp_enqueue_script( $handle );
	}
}

/**
 * Script handle Magnific Popup init should depend on for load order.
 *
 * @return string Registered handle (`magnific-popup` or `dsm-magnific-popup`), or empty string.
 */
function dsm_get_active_magnific_popup_script_handle(): string {
	if ( wp_script_is( 'magnific-popup', 'registered' ) ) {
		return 'magnific-popup';
	}

	if ( ! dsm_register_magnific_popup_script_if_needed() ) {
		return '';
	}

	return wp_script_is( 'dsm-magnific-popup', 'registered' ) ? 'dsm-magnific-popup' : '';
}

/**
 * Ensure `$dependent_handle` is printed after `$dependency_handle` (e.g. module JS after Magnific).
 *
 * @param string $dependent_handle Registered script handle.
 * @param string $dependency_handle  Registered dependency handle.
 * @return void
 */
function dsm_ensure_registered_script_dependency( string $dependent_handle, string $dependency_handle ): void {
	if ( ! wp_script_is( $dependent_handle, 'registered' ) || ! wp_script_is( $dependency_handle, 'registered' ) ) {
		return;
	}
	$wp_scripts = wp_scripts();
	if ( ! isset( $wp_scripts->registered[ $dependent_handle ] ) ) {
		return;
	}
	$reg = $wp_scripts->registered[ $dependent_handle ];
	if ( ! is_array( $reg->deps ) ) {
		$reg->deps = array();
	}
	if ( in_array( $dependency_handle, $reg->deps, true ) ) {
		return;
	}
	$reg->deps[] = $dependency_handle;
}

/**
 * Walk parsed `innerBlocks` for a child block name; return true if any toggle attr is `on`.
 *
 * @param array<int, mixed> $blocks      Parsed inner blocks list.
 * @param string            $block_name e.g. `dsm/card-carousel-child`.
 * @param list<string>      $toggle_attr_keys Attribute keys under `innerContent.desktop.value`.
 * @return bool
 */
function dsm_parsed_inner_blocks_any_child_toggle_on( array $blocks, string $block_name, array $toggle_attr_keys ): bool {
	foreach ( $blocks as $node ) {
		if ( ! is_array( $node ) ) {
			continue;
		}
		if ( isset( $node['blockName'] ) && $block_name === $node['blockName'] ) {
			$child_attrs = isset( $node['attrs'] ) && is_array( $node['attrs'] ) ? $node['attrs'] : array();
			foreach ( $toggle_attr_keys as $key ) {
				if ( isset( $child_attrs[ $key ]['innerContent']['desktop']['value'] ) && 'on' === $child_attrs[ $key ]['innerContent']['desktop']['value'] ) {
					return true;
				}
			}
		}
		if ( ! empty( $node['innerBlocks'] ) && is_array( $node['innerBlocks'] ) ) {
			if ( dsm_parsed_inner_blocks_any_child_toggle_on( $node['innerBlocks'], $block_name, $toggle_attr_keys ) ) {
				return true;
			}
		}
	}

	return false;
}
