<?php

namespace Sitecake\Util;

class Beautifier
{
    protected static $config = [];

    const INDENT = "\t";

    const PATTERN_OPENING_TAG = '/<([^\s>\/]+)/';

    const PATTERN_CLOSING_TAG = '/<\/([^>]*)>/';

    public static function config($options)
    {
        self::$config = array_merge(['indentation_character' => self::INDENT], $options);
    }

    /**
     * Indents passed HTML input string based on options and passed params.
     * Beautification is cosmetic — just normalise tags and return.
     *
     * @param        $input
     * @param string $prefixIndentation
     * @param bool   $skipFirstLine
     *
     * @return string
     */
    public static function indent($input, $prefixIndentation = '', $skipFirstLine = false)
    {
        return self::fixTags($input);
    }

    public static function fixTags($input)
    {
        // Remove space before closing of opening tag
        $input = preg_replace_callback('/(<[^\/][^>]*)(\s>)/', function ($matches) {
            return $matches[1] . '>';
        }, $input);

        // Fix opening tags
        if (preg_match_all(self::PATTERN_OPENING_TAG, $input, $matches)) {
            $matches = array_unique($matches[0]);

            foreach ($matches as $match) {
                // Lowercase opening tags except <!DOCTYPE>
                if ($match !== '<!DOCTYPE') {
                    $input = str_replace($match, strtolower($match), $input);
                }
            }
        }

        // Fix closing tags
        if (preg_match_all(self::PATTERN_CLOSING_TAG, $input, $matches)) {
            $matches = array_unique($matches[0]);

            foreach ($matches as $match) {
                // Lowercase closing tags
                $input = str_replace($match, strtolower($match), $input);
            }
        }

        return $input;
    }
}
