<?php
/**
 * Visibility trait — PHP CSS emit. Owns per-breakpoint hide rules for
 * any block declaring `"blocksifySupports": [..., "visibility"]`.
 *
 * Single bag attr `visibility = { hideDesktop, hideTablet, hideMobile }`.
 * NOT per-device flat-suffix because the three flags ARE the per-device
 * gates — each one emits a `display:none !important` rule scoped to its
 * own @media block.
 *
 * Output contract: `::emit_rules( $uid, $attrs, $base_class )` returns
 * the FULL @media wrapped rules (not just decls) — the visibility rules
 * live OUTSIDE the per-device wrapper rule emit, since each flag
 * targets a different viewport range. Caller appends as-is.
 *
 * @package Blocksify
 */

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

class Blocksify_Visibility_Trait {

	/**
	 * Attribute schema fragment. Mirror of `src/shared/traits/visibility.js`
	 * `attributes` const. See spacing trait header for rationale + sync rule.
	 */
	public static function attributes() {
		return array(
			'visibility' => array( 'type' => array( 'object', 'null' ) ),
		);
	}

	/**
	 * Emit @media display:none rules for active flags. Specificity bump
	 * via `!important` because authors might layer inline styles or
	 * custom CSS that would otherwise show the element.
	 *
	 * @param string $uid
	 * @param array  $attrs
	 * @param string $base_class        Per-block class prefix (e.g.
	 *                                  `'bsy-section-'`).
	 * @param string $selector_override When non-empty, emit on this exact
	 *                                  selector instead of the per-instance
	 *                                  class. Used by blocks that route
	 *                                  visibility to a parent (Image's
	 *                                  figure-via-`:has()`) so the whole
	 *                                  figure (incl. caption) hides, not
	 *                                  just the per-instance element.
	 * @return string Full CSS (with @media wrappers) or '' when no flags.
	 */
	public static function emit_rules( $uid, $attrs, $base_class, $selector_override = '' ) {
		if ( empty( $attrs['visibility'] ) || ! is_array( $attrs['visibility'] ) ) {
			return '';
		}
		$v        = $attrs['visibility'];
		$selector = '' !== $selector_override ? $selector_override : '.' . $base_class . $uid;
		$rule     = $selector . '{display:none !important;}';
		$css      = '';

		if ( ! empty( $v['hideDesktop'] ) ) {
			$css .= '@media (min-width:' . ( Blocksify_CSS_Generator::TABLET_MAX + 1 ) . 'px){' . $rule . '}';
		}
		if ( ! empty( $v['hideTablet'] ) ) {
			$css .= '@media (min-width:' . ( Blocksify_CSS_Generator::MOBILE_MAX + 1 ) . 'px) and (max-width:' . Blocksify_CSS_Generator::TABLET_MAX . 'px){' . $rule . '}';
		}
		if ( ! empty( $v['hideMobile'] ) ) {
			$css .= '@media (max-width:' . Blocksify_CSS_Generator::MOBILE_MAX . 'px){' . $rule . '}';
		}
		return $css;
	}
}
