<?php
/**
 * Responsive Visibility breakpoints (core). Defaults are filterable via
 * "cafw_breakpoints" so Pro can supply a custom set.
 *
 * @package CraftAddonsForWPBakery
 */

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

/**
 * Class CAFW_Breakpoints
 */
class CAFW_Breakpoints {

	/**
	 * @return array<int,array{key:string,label:string,min:int,max:int}>
	 */
	public static function defaults() {
		return array(
			array(
				'key'   => 'desktop',
				'label' => __( 'Desktop', 'craft-addons-for-wpbakery' ),
				'min'   => 1025,
				'max'   => 0,
			),
			array(
				'key'   => 'tablet',
				'label' => __( 'Tablet', 'craft-addons-for-wpbakery' ),
				'min'   => 768,
				'max'   => 1024,
			),
			array(
				'key'   => 'mobile',
				'label' => __( 'Mobile', 'craft-addons-for-wpbakery' ),
				'min'   => 0,
				'max'   => 767,
			),
		);
	}

	/**
	 * @return array<int,array{key:string,label:string,min:int,max:int}>
	 */
	public static function get() {
		return self::sanitize( apply_filters( 'cafw_breakpoints', self::defaults() ) );
	}

	/**
	 * @param array $list Raw rows.
	 * @return array<int,array{key:string,label:string,min:int,max:int}>
	 */
	public static function sanitize( $list ) {
		if ( ! is_array( $list ) ) {
			return array();
		}

		$clean = array();
		$seen  = array();

		foreach ( $list as $row ) {
			if ( ! is_array( $row ) ) {
				continue;
			}

			$label = isset( $row['label'] ) ? sanitize_text_field( $row['label'] ) : '';
			$key   = isset( $row['key'] ) && '' !== $row['key'] ? $row['key'] : $label;
			$key   = sanitize_key( str_replace( ' ', '-', $key ) );

			if ( '' === $key || '' === $label ) {
				continue;
			}

			$base = $key;
			$i    = 2;
			while ( isset( $seen[ $key ] ) ) {
				$key = $base . '-' . $i;
				++$i;
			}
			$seen[ $key ] = true;

			$clean[] = array(
				'key'   => $key,
				'label' => $label,
				'min'   => isset( $row['min'] ) ? absint( $row['min'] ) : 0,
				'max'   => isset( $row['max'] ) ? absint( $row['max'] ) : 0,
			);
		}

		return $clean;
	}

	/**
	 * @param string $key Breakpoint key.
	 * @return string
	 */
	public static function hide_class( $key ) {
		return 'cafw-hide-' . sanitize_html_class( $key );
	}

	/**
	 * @return string
	 */
	public static function css() {
		$css = '';

		foreach ( self::get() as $bp ) {
			$rule = '.' . self::hide_class( $bp['key'] ) . '{display:none !important}';
			$min  = (int) $bp['min'];
			$max  = (int) $bp['max'];

			if ( $min > 0 && $max > 0 ) {
				$css .= '@media (min-width:' . $min . 'px) and (max-width:' . $max . 'px){' . $rule . '}';
			} elseif ( $min > 0 ) {
				$css .= '@media (min-width:' . $min . 'px){' . $rule . '}';
			} elseif ( $max > 0 ) {
				$css .= '@media (max-width:' . $max . 'px){' . $rule . '}';
			} else {
				$css .= $rule;
			}
		}

		return $css;
	}
}
