<?php
/**
 * Brentwood "Red Border" section setting — a solid border in the brand red
 * (palette colour 1) that authors turn on per-section with a single toggle,
 * instead of configuring Kadence's own border controls (colour + width + side
 * + style) by hand each time.
 *
 * Built the same way as the Column Curve feature (brentwood-curve.php):
 *   - assets/bw-redborder-editor.js declares attributes on kadence/column and
 *     adds the "Red Border" sidebar panel (toggle + optional side/width/colour).
 *   - This file (render_block) reads those attributes on the front end and adds
 *     the bw-redborder classes (+ any CSS-var overrides) onto the column's inner
 *     wrapper. assets/bw-redborder.css paints the border.
 *
 * Defaults (agreed standard): right side, 4px, solid, --global-palette1.
 *
 * @package Kadence-Child
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Register the front-end stylesheet.
 */
add_action(
	'init',
	function () {
		$theme = get_stylesheet_directory();
		$uri   = get_stylesheet_directory_uri();
		wp_register_style( 'bw-redborder', $uri . '/assets/bw-redborder.css', array(), filemtime( $theme . '/assets/bw-redborder.css' ) );
	}
);

/**
 * Load the border preview stylesheet into the Gutenberg editor canvas, so the
 * section shows the same red border while editing that it does on the front end.
 *
 * enqueue_block_assets fires for both the front end and the editor; styles
 * enqueued here are injected into the iframed canvas (unlike
 * enqueue_block_editor_assets, which only reaches the outer editor document).
 * We gate on is_admin() so this preview CSS loads in the editor only — the front
 * end gets its border from bw-redborder.css via render_block. filemtime keeps it
 * cache-busted on every edit.
 */
add_action(
	'enqueue_block_assets',
	function () {
		if ( ! is_admin() ) {
			return;
		}
		$theme = get_stylesheet_directory();
		$file  = $theme . '/assets/bw-redborder-editor.css';
		if ( ! file_exists( $file ) ) {
			return;
		}
		wp_enqueue_style(
			'bw-redborder-editor',
			get_stylesheet_directory_uri() . '/assets/bw-redborder-editor.css',
			array(),
			filemtime( $file )
		);
	}
);

/**
 * Load the editor script early (priority 1) so its attribute filter is in place
 * before Kadence registers kadence/column.
 */
add_action(
	'enqueue_block_editor_assets',
	function () {
		$theme = get_stylesheet_directory();
		$file  = $theme . '/assets/bw-redborder-editor.js';
		if ( ! file_exists( $file ) ) {
			return;
		}
		wp_enqueue_script(
			'bw-redborder-editor',
			get_stylesheet_directory_uri() . '/assets/bw-redborder-editor.js',
			array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-compose', 'wp-hooks', 'wp-i18n' ),
			filemtime( $file ),
			true
		);
	},
	1
);

/**
 * Front end: when a Kadence Column has the red border enabled, add the
 * bw-redborder classes (+ optional CSS-var overrides) onto its inner wrapper
 * (.kt-inside-inner-col) — the same element Kadence paints its own border on, so
 * the border hugs the section's padded content box and respects its corners.
 *
 * @param string $html  Rendered block HTML.
 * @param array  $block Parsed block (blockName, attrs, …).
 * @return string
 */
function bw_redborder_render_column( $html, $block ) {
	if ( ( $block['blockName'] ?? '' ) !== 'kadence/column' ) {
		return $html;
	}
	if ( empty( $block['attrs']['bwRedBorder'] ) ) {
		return $html;
	}

	$side    = strtolower( (string) ( $block['attrs']['bwRbSide'] ?? 'right' ) );
	$allowed = array( 'right', 'left', 'top', 'bottom', 'all' );
	if ( ! in_array( $side, $allowed, true ) ) {
		$side = 'right';
	}
	$classes = 'bw-redborder bw-redborder--' . $side;

	// Optional CSS-var overrides → inline style on the same wrapper.
	$style_vars = array();
	$width = trim( (string) ( $block['attrs']['bwRbWidth'] ?? '' ) );
	if ( '' !== $width ) {
		$style_vars[] = '--bw-rb-width:' . $width;
	}
	$color = trim( (string) ( $block['attrs']['bwRbColor'] ?? '' ) );
	if ( '' !== $color ) {
		$style_vars[] = '--bw-rb-color:' . $color;
	}
	$style = $style_vars ? esc_attr( implode( ';', $style_vars ) ) : '';

	wp_enqueue_style( 'bw-redborder' );

	// Inject onto the opening tag of the inner wrapper (.kt-inside-inner-col).
	// Merge into existing class= / style= attributes when present, otherwise add
	// them. preg_replace_callback avoids $-interpolation in the replacement.
	$count = 0;
	$out   = preg_replace_callback(
		'/<div\b[^>]*\bkt-inside-inner-col\b[^>]*>/',
		function ( $m ) use ( $classes, $style ) {
			$tag = $m[0];

			// Merge classes.
			if ( preg_match( '/\bclass="/', $tag ) ) {
				$tag = preg_replace( '/\bclass="/', 'class="' . $classes . ' ', $tag, 1 );
			} else {
				$tag = preg_replace( '/<div\b/', '<div class="' . $classes . '"', $tag, 1 );
			}

			// Merge inline style vars (only if any overrides were set).
			if ( '' !== $style ) {
				if ( preg_match( '/\bstyle="/', $tag ) ) {
					$tag = preg_replace( '/\bstyle="/', 'style="' . $style . ';', $tag, 1 );
				} else {
					$tag = preg_replace( '/<div\b/', '<div style="' . $style . '"', $tag, 1 );
				}
			}

			return $tag;
		},
		$html,
		1,
		$count
	);

	return $count ? $out : $html;
}
add_filter( 'render_block', 'bw_redborder_render_column', 12, 2 );
