<?php
/**
 * CSSTidy Printing PHP Class
 *
 * @package TablePress
 * @subpackage CSS
 * @author Florian Schmitz, Brett Zamir, Nikolay Matsievsky, Cedric Morin, Christopher Finke, Mark Scherer, Tobias Bäthge
 * @since 1.0.0
 */

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

/**
 * CSS Printing class
 *
 * This class prints CSS data generated by CSSTidy.
 *
 * @package CSSTidy
 * @version 1.1.0
 */
class TablePress_CSSTidy_Print {

	/**
	 * TablePress_CSSTidy instance.
	 *
	 * @since 1.0.0
	 */
	public \TablePress_CSSTidy $parser;

	/**
	 * The parsed CSS.
	 *
	 * @since 1.0.0
	 */
	public array $css = array();

	/**
	 * The output templates.
	 *
	 * @since 1.0.0
	 */
	public array $template = array();

	/**
	 * The raw parsed CSS.
	 *
	 * @since 1.0.0
	 */
	public array $tokens = array();

	/**
	 * The CSS charset.
	 *
	 * @since 1.0.0
	 */
	public string $charset = '';

	/**
	 * All @import URLs.
	 *
	 * @since 1.0.0
	 */
	public array $import = array();

	/**
	 * The namespace.
	 *
	 * @since 1.0.0
	 */
	public string $namespace = '';

	/**
	 * Saves the input CSS string.
	 *
	 * @since 1.0.0
	 */
	public string $input_css = '';

	/**
	 * Saves the formatted CSS string.
	 *
	 * @since 1.0.0
	 */
	public string $output_css = '';

	/**
	 * Saves the formatted CSS string (plain text).
	 *
	 * @since 1.0.0
	 */
	public string $output_css_plain = '';

	/**
	 * Constructor.
	 *
	 * @since 1.0
	 *
	 * @param TablePress_CSSTidy $csstidy Instance of the TablePress_CSSTidy class.
	 */
	public function __construct( TablePress_CSSTidy $csstidy ) {
		$this->parser = $csstidy;
		$this->css = &$csstidy->css;
		$this->template = &$csstidy->template;
		$this->tokens = &$csstidy->tokens;
		$this->charset = &$csstidy->charset;
		$this->import = &$csstidy->import;
		$this->namespace = &$csstidy->namespace;
	}

	/**
	 * Resets output_css and output_css_plain (new CSS code).
	 *
	 * @since 1.0
	 */
	public function _reset(): void {
		$this->output_css = '';
		$this->output_css_plain = '';
	}

	/**
	 * Returns the CSS code as plain text.
	 *
	 * @since 1.0
	 *
	 * @param string $default_media Optional. Default @media to add to selectors without any @media.
	 * @return string Plain CSS.
	 */
	public function plain( string $default_media = '' ): string {
		$this->_print( true, $default_media );
		return $this->output_css_plain;
	}

	/**
	 * Returns the formatted CSS Code and saves it into $this->output_css and $this->output_css_plain.
	 *
	 * @since 1.0
	 *
	 * @param bool   $plain         Optional. Plain text or not.
	 * @param string $default_media Optional. Default @media to add to selectors without any @media.
	 */
	protected function _print( bool $plain = false, string $default_media = '' ): void {
		if ( $this->output_css && $this->output_css_plain ) {
			return;
		}

		$output = '';
		if ( ! $this->parser->get_cfg( 'preserve_css' ) ) {
			$this->_convert_raw_css( $default_media );
		}

		$template = &$this->template;

		if ( $plain ) {
			$template = array_map( 'strip_tags', $template );
		}

		if ( $this->parser->get_cfg( 'timestamp' ) ) {
			array_unshift( $this->tokens, array( TablePress_CSSTidy::COMMENT, ' CSSTidy: ' . gmdate( 'r' ) . ' ' ) );
		}

		if ( ! empty( $this->charset ) ) {
			$output .= $template[0] . '@charset ' . $template[5] . $this->charset . $template[6] . $template[13];
		}

		if ( ! empty( $this->import ) ) {
			for ( $i = 0, $size = count( $this->import ); $i < $size; $i++ ) {
				$import_components = explode( ' ', $this->import[ $i ] );
				if ( str_starts_with( $import_components[0], 'url(' ) && str_ends_with( $import_components[0], ')' ) ) {
					$import_components[0] = '\'' . trim( substr( $import_components[0], 4, -1 ), "'\"" ) . '\'';
					$this->import[ $i ] = implode( ' ', $import_components );
					$this->parser->log( 'Optimised @import : Removed "url("', 'Information' );
				} elseif ( ! preg_match( '/^".+"$/', $this->import[ $i ] ) ) {
					// Fixes a bug for @import ".." instead of the expected @import url("..").
					// If it comes in due to @import ".." the "" will be missing and the output will become @import .. (which is an error).
					$this->import[ $i ] = '"' . $this->import[ $i ] . '"';
				}
				$output .= $template[0] . '@import ' . $template[5] . $this->import[ $i ] . $template[6] . $template[13];
			}
		}

		if ( ! empty( $this->namespace ) ) {
			if ( false !== ( $p = strpos( $this->namespace, 'url(' ) ) && str_ends_with( $this->namespace, ')' ) ) { // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found,Squiz.PHP.DisallowMultipleAssignments.FoundInControlStructure
				$this->namespace = substr_replace( $this->namespace, '"', $p, 4 );
				$this->namespace = substr( $this->namespace, 0, -1 ) . '"';
				$this->parser->log( 'Optimised @namespace : Removed "url("', 'Information' );
			}
			$output .= $template[0] . '@namespace ' . $template[5] . $this->namespace . $template[6] . $template[13];
		}

		$in_at_out = array();
		$out = &$output;
		$indent_level = 0;

		foreach ( $this->tokens as $key => $token ) {
			switch ( $token[0] ) {
				case TablePress_CSSTidy::AT_START:
					if ( $this->parser->get_cfg( 'preserve_css' ) ) {
						$token[1] = str_replace( ',', ",\n", $token[1] );
					}
					$out .= $template[0] . $this->_htmlsp( $token[1], $plain ) . $template[1];
					++$indent_level;
					if ( ! isset( $in_at_out[ $indent_level ] ) ) {
						$in_at_out[ $indent_level ] = '';
					}
					$out = &$in_at_out[ $indent_level ];
					break;
				case TablePress_CSSTidy::SEL_START:
					if ( $this->parser->get_cfg( 'lowercase_s' ) ) {
						$token[1] = strtolower( $token[1] );
					}
					if ( $this->parser->get_cfg( 'preserve_css' ) ) {
						$token[1] = str_replace( ',', ",\n", $token[1] );
					}
					$out .= ( '@' !== $token[1][0] ) ? $template[2] . $this->_htmlsp( $token[1], $plain ) : $template[0] . $this->_htmlsp( $token[1], $plain );
					$out .= $template[3];
					break;
				case TablePress_CSSTidy::PROPERTY:
					if ( 2 === $this->parser->get_cfg( 'case_properties' ) ) {
						$token[1] = strtoupper( $token[1] );
					} elseif ( 1 === $this->parser->get_cfg( 'case_properties' ) ) {
						$token[1] = strtolower( $token[1] );
					}
					$out .= $template[4] . $this->_htmlsp( $token[1], $plain ) . ':' . $template[5];
					break;
				case TablePress_CSSTidy::VALUE:
					$out .= $this->_htmlsp( $token[1], $plain );
					if ( TablePress_CSSTidy::SEL_END === $this->_seeknocomment( $key, 1 ) && $this->parser->get_cfg( 'remove_last_;' ) ) {
						$out .= str_replace( ';', '', $template[6] );
					} else {
						$out .= $template[6];
					}
					if ( $this->parser->get_cfg( 'preserve_css' ) ) {
						$out .= ( TablePress_CSSTidy::COMMENT === $this->tokens[ $key + 1 ][0] ) ? ' ' : "\n";
					}
					break;
				case TablePress_CSSTidy::SEL_END:
					$out .= $template[7];
					if ( TablePress_CSSTidy::AT_END !== $this->_seeknocomment( $key, 1 ) ) {
						$out .= $template[8];
					}
					break;
				case TablePress_CSSTidy::AT_END:
					if ( strlen( $template[10] ) ) {
						// Indent the block we are closing.
						$out = str_replace( "\n\n", "\r\n", $out ); // Don't fill empty lines.
						$out = str_replace( "\n", "\n" . $template[10], $out );
						$out = str_replace( "\r\n", "\n\n", $out );
					}
					if ( $indent_level > 1 ) {
						$out = &$in_at_out[ $indent_level - 1 ];
					} else {
						$out = &$output;
					}
					$out .= $template[10] . $in_at_out[ $indent_level ];
					if ( TablePress_CSSTidy::AT_END !== $this->_seeknocomment( $key, 1 ) ) {
						$out .= $template[9];
					} else {
						$out .= rtrim( $template[9] );
					}
					unset( $in_at_out[ $indent_level ] );
					--$indent_level;
					break;
				case TablePress_CSSTidy::IMPORTANT_COMMENT:
				case TablePress_CSSTidy::COMMENT:
					$out .= $template[11] . '/*' . $this->_htmlsp( $token[1], $plain ) . '*/' . $template[12];
					break;
			}
		}

		if ( ! $this->parser->get_cfg( 'preserve_css' ) ) {
			$output = str_replace( ' !important', '!important', $output );
		}

		$output = trim( $output );

		if ( ! $plain ) {
			$this->output_css = $output;
			$this->_print( true );
		} else {
			// If using spaces in the template, don't want these to appear in the plain output.
			$this->output_css_plain = str_replace( '&#160;', '', $output );
		}
	}

	/**
	 * Gets the next token type which is $move away from $key, excluding comments.
	 *
	 * @since 1.0
	 *
	 * @param int $key  Current position.
	 * @param int $move Move this far.
	 * @return mixed A token type.
	 */
	protected function _seeknocomment( int $key, int $move ) /* : mixed */ {
		$go = ( $move > 0 ) ? 1 : -1;
		for ( $i = $key + 1; abs( $key - $i ) - 1 < abs( $move ); $i += $go ) { // phpcs:ignore Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed
			if ( ! isset( $this->tokens[ $i ] ) ) {
				return;
			}
			if ( TablePress_CSSTidy::COMMENT === $this->tokens[ $i ][0] ) {
				++$move;
				continue;
			}
			return $this->tokens[ $i ][0];
		}
	}

	/**
	 * Converts $this->css array to a raw array ($this->tokens).
	 *
	 * @since 1.0.0
	 *
	 * @param string $default_media Optional. Default @media to add to selectors without any @media.
	 */
	protected function _convert_raw_css( string $default_media = '' ): void {
		$this->tokens = array();
		$sort_selectors = $this->parser->get_cfg( 'sort_selectors' );
		$sort_properties = $this->parser->get_cfg( 'sort_properties' );

		// Important comment section?
		if ( isset( $this->css['!'] ) ) {
			$this->parser->_add_token( TablePress_CSSTidy::IMPORTANT_COMMENT, rtrim( $this->css['!'] ), true );
			unset( $this->css['!'] );
		}

		foreach ( $this->css as $medium => $val ) {
			if ( $sort_selectors ) {
				ksort( $val );
			}
			if ( (int) $medium < TablePress_CSSTidy::DEFAULT_AT ) {
				// An empty medium (containing @font-face or other @) produces no container.
				if ( strlen( trim( $medium ) ) ) {
					$parts_to_open = explode( '{', $medium );
					foreach ( $parts_to_open as $part ) {
						$this->parser->_add_token( TablePress_CSSTidy::AT_START, $part, true );
					}
				}
			} elseif ( $default_media ) {
				$this->parser->_add_token( TablePress_CSSTidy::AT_START, $default_media, true );
			}

			foreach ( $val as $selector => $vali ) {
				if ( $sort_properties ) {
					ksort( $vali );
				}
				$this->parser->_add_token( TablePress_CSSTidy::SEL_START, $selector, true );

				$invalid = array(
					'*' => array(), // IE7 hacks first.
					'_' => array(), // IE6 hacks.
					'/' => array(), // IE6 hacks.
					'-' => array(), // IE6 hacks.
				);
				foreach ( $vali as $property => $valj ) {
					if ( ! str_starts_with( $property, '//' ) ) {
						$matches = array();
						if ( $sort_properties && preg_match( '/^(\*|_|\/|-)(?!(ms|moz|o\b|xv|atsc|wap|khtml|webkit|ah|hp|ro|rim|tc)-)/', $property, $matches ) ) {
							$invalid[ $matches[1] ][ $property ] = $valj;
						} else {
							$this->parser->_add_token( TablePress_CSSTidy::PROPERTY, $property, true );
							$this->parser->_add_token( TablePress_CSSTidy::VALUE, $valj, true );
						}
					}
				}
				foreach ( $invalid as $prefix => $props ) {
					foreach ( $props as $property => $valj ) {
						$this->parser->_add_token( TablePress_CSSTidy::PROPERTY, $property, true );
						$this->parser->_add_token( TablePress_CSSTidy::VALUE, $valj, true );
					}
				}
				$this->parser->_add_token( TablePress_CSSTidy::SEL_END, $selector, true );
			}

			if ( (int) $medium < TablePress_CSSTidy::DEFAULT_AT ) {
				// An empty medium (containing @font-face or other @) produces no container.
				if ( strlen( trim( $medium ) ) ) {
					$parts_to_close = explode( '{', $medium );
					foreach ( array_reverse( $parts_to_close ) as $part ) {
						$this->parser->_add_token( TablePress_CSSTidy::AT_END, $part, true );
					}
				}
			} elseif ( $default_media ) {
				$this->parser->_add_token( TablePress_CSSTidy::AT_END, $default_media, true );
			}
		}
	}

	/**
	 * Same as htmlspecialchars, only that chars are not replaced if $plain is true. This makes print_code() cleaner.
	 *
	 * @since 1.0
	 *
	 * @see CSSTidy_print::_print()
	 *
	 * @param string $a_string String.
	 * @param bool   $plain    Whether to print plain.
	 * @return string Original string or htmlspecialchars() version.
	 */
	protected function _htmlsp( string $a_string, bool $plain ): string {
		if ( ! $plain ) {
			return htmlspecialchars( $a_string, ENT_QUOTES, 'utf-8' );
		}
		return $a_string;
	}

} // class TablePress_CSSTidy_Print
