<?php

// helper functions


function mh_content_placeholder($set_options = null)
{

    $default_options = array(
        'output_no_html' => false,
        'output_css' => true,
        'add_headline' => true,
        'content_rows' => 1
    );


    $options = (is_array($set_options)) ? array_merge($default_options, $set_options) : $default_options;
    ob_start();
    ?>
    <div class="mh-dummy-wrapper">
        <?php if (mh_arr_val($options, 'overlay_text')) { ?>
            <div style="position: absolute; width: 100%; height: 100%; background-color: rgba(128,128,128,0.2)">

            </div>
            <div style="position: absolute;transform: translateY(-50%);
                  top: 50%; width: 100%; text-align: center; font-size: 20px; font-weight: bold; font-family: Arial; opacity: 0.5; line-height: 25px;">
                <?php echo $options['overlay_text']; ?>
            </div>
            <!--            <div style="position: absolute; height: 100%; width: 100%; display: block; text-align: center">-->
            <!--            </div>-->
        <?php } ?>
        <?php if (mh_arr_val($options, 'add_headline')) { ?>
            <div class="mh-dummy-header">
                <div class="mh-dummy-item header"></div>
                <div class="mh-dummy-item subheader"></div>
            </div>
        <?php } ?>
        <?php
        if (mh_arr_val($options, 'content_rows')) {
            for ($i = 0; $i < $options['content_rows']; $i++) { ?>
                <div class="mh-dummy-content">
                    <div class="mh-dummy-item img"></div>
                    <div class="mh-dummy-item content content-first-line"></div>
                    <div class="mh-dummy-item content content-second-line"></div>
                    <div class="mh-dummy-item content content-third-line"></div>
                </div>
                <?php
            }
        }
        ?>
    </div>
    <?php

    $html = ob_get_contents();
    ob_end_clean();

    ob_start();
    ?>
    <style type="text/css">

        .mh-dummy-wrapper {
            position: relative;
            min-height: 30px;
            margin-bottom: 10px;
        }

        .mh-dummy-item {
            background: rgba(128, 128, 128, 0.2);
            position: absolute;
        }

        .mh-dummy-header {
            height: 50px;
            position: relative;
        }

        .mh-dummy-content {
            height: 90px;
            position: relative;
            margin-bottom: 15px;
            overflow: hidden;
        }

        .mh-dummy-item.header {
            top: 0;
            left: 0px;
            width: 90%;
            height: 18px;
        }

        .mh-dummy-item.subheader {
            top: 25px;
            left: 0px;
            width: 75%;
            height: 10px;
        }

        .mh-dummy-item.img {
            top: 0px;
            left: 0px;
            width: 90px;
            height: 90px;
        }

        .mh-dummy-item.content {
            height: 10px;
            left: 100px;
            top: 10px;
        }

        .mh-dummy-item.content-first-line {
            width: 70%;
            top: 10px;
        }

        .mh-dummy-item.content-second-line {
            width: 80%;
            top: 30px;
        }

        .mh-dummy-item.content-third-line {
            width: 60%;
            top: 50px;
        }

    </style>
    <?php

    $css = ob_get_contents();
    ob_end_clean();
    $return = '';
    if ($options['output_css']) {
        $return .= $css;
    }
    if (!$options['output_no_html']) {
        $return .= $html;
    }

    return $return;

}


/**
 * Find the resulting colour by blending 2 colours
 * and setting an opacity level for the foreground colour.
 *
 * @param string $foreground Hexadecimal colour value of the foreground colour.
 * @param integer $opacity Opacity percentage (of foreground colour). A number between 0 and 100.
 * @param string $background Optional. Hexadecimal colour value of the background colour. Default is: <code>FFFFFF</code> aka white.
 * @return string Hexadecimal colour value. <code>false</code> on errors.
 * @author J de Silva
 * @link http://www.gidnetwork.com/b-135.html
 */
function mh_color_blend_by_opacity($foreground, $opacity, $background = null)
{
    static $colors_rgb = array(); // stores colour values already passed through the hexdec() functions below.

    $pre = stristr((string)$foreground, '#') ? '#' : '';

    $foreground = str_replace('#', '', (string)$foreground);


    if (is_null($background)) {
        $background = $pre . 'FFFFFF'; // default background.
    }
    $background = str_replace('#', '', (string)$background);

    $pattern = '~^[a-f0-9]{6,6}$~i'; // accept only valid hexadecimal colour values.
    if (!@preg_match($pattern, $foreground) or !@preg_match($pattern, $background)) {
        trigger_error("Invalid hexadecimal colour value(s) found", E_USER_WARNING);
        return false;
    }

    $opacity = intval($opacity); // validate opacity data/number.
    if ($opacity > 100 || $opacity < 0) {
        trigger_error("Opacity percentage error, valid numbers are between 0 - 100", E_USER_WARNING);
        return false;
    }

    if ($opacity == 100) {
        // $transparency == 0
        return $pre . strtoupper($foreground);
    }
    if ($opacity == 0) {
        // $transparency == 100
        return $pre . strtoupper($background);
    }
    // calculate $transparency value.
    $transparency = 100 - $opacity;

    if (!isset($colors_rgb[$foreground])) { // do this only ONCE per script, for each unique colour.
        $f = array('r' => hexdec($foreground[0] . $foreground[1]),
            'g' => hexdec($foreground[2] . $foreground[3]),
            'b' => hexdec($foreground[4] . $foreground[5]));
        $colors_rgb[$foreground] = $f;
    } else { // if this function is used 100 times in a script, this block is run 99 times.  Efficient.
        $f = $colors_rgb[$foreground];
    }

    if (!isset($colors_rgb[$background])) { // do this only ONCE per script, for each unique colour.
        $b = array('r' => hexdec($background[0] . $background[1]),
            'g' => hexdec($background[2] . $background[3]),
            'b' => hexdec($background[4] . $background[5]));
        $colors_rgb[$background] = $b;
    } else { // if this FUNCTION is used 100 times in a SCRIPT, this block will run 99 times.  Efficient.
        $b = $colors_rgb[$background];
    }

    $add = array('r' => ($b['r'] - $f['r']) / 100,
        'g' => ($b['g'] - $f['g']) / 100,
        'b' => ($b['b'] - $f['b']) / 100);

    $f['r'] += intval($add['r'] * $transparency);
    $f['g'] += intval($add['g'] * $transparency);
    $f['b'] += intval($add['b'] * $transparency);

    return $pre . strtolower(sprintf('%02X%02X%02X', $f['r'], $f['g'], $f['b']));
}

// replicate SASS lighten/darken functions
// http://stackoverflow.com/questions/3512311/how-to-generate-lighter-darker-color-with-php

function mh_color_adjust_brightness($hex, $percent, $darken = true)
{
    $brightness = $darken ? -255 : 255;

    // Steps should be between -255 and 255. Negative = darker, positive = lighter
    $steps = $percent * $brightness / 100;

    // Normalize into a six character long hex string
    $hex = str_replace('#', '', (string)$hex);
    if (strlen((string)$hex) == 3) {
        $hex = str_repeat(substr((string)$hex, 0, 1), 2) . str_repeat(substr((string)$hex, 1, 1), 2) . str_repeat(substr((string)$hex, 2, 1), 2);
    }

    // Split into three parts: R, G and B
    $color_parts = str_split((string)$hex, 2);
    $return = '#';

    foreach ($color_parts as $color) {
        $color = hexdec($color); // Convert to decimal
        $color = max(0, min(255, $color + $steps)); // Adjust color
        $return .= str_pad(dechex((int) round($color)), 2, '0', STR_PAD_LEFT); // Ensure integer and avoid precision loss
    }

    return $return;
}

function mh_color_lighten($hex, $percent)
{
    return mh_color_adjust_brightness($hex, $percent, false);
}

function mh_color_darken($hex, $percent)
{
    return mh_color_adjust_brightness($hex, $percent, true);
}


// http://stackoverflow.com/questions/1261033/sorting-by-color


function mh_color_hexToDec($hex)
{

    // Normalize into a six character long hex string
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) == 3) {
        $hex = str_repeat(substr($hex, 0, 1), 2) . str_repeat(substr($hex, 1, 1), 2) . str_repeat(substr($hex, 2, 1), 2);
    }
    $color_parts = str_split($hex, 2);

    $col = array();
    foreach ($color_parts as $color) {
        $col[] = hexdec($color); // Convert to decimal
    }

    return array($col[0], $col[1], $col[2]);
}

function mh_color_rgbToHsl($r, $g, $b)
{
    $r /= 255;
    $g /= 255;
    $b /= 255;

    $max = max($r, $g, $b);
    $min = min($r, $g, $b);

    $h = 0;
    $l = ($max + $min) / 2;
    $d = $max - $min;

    if ($d == 0) {
        $h = $s = 0; // achromatic
    } else {
        $s = $d / (1 - abs(2 * $l - 1));

        switch ($max) {
            case $r:
                $h = 60 * fmod((($g - $b) / $d), 6);
                if ($b > $g) {
                    $h += 360;
                }
                break;

            case $g:
                $h = 60 * (($b - $r) / $d + 2);
                break;

            case $b:
                $h = 60 * (($r - $g) / $d + 4);
                break;
        }
    }
    return array('h' => round($h, 2), 's' => round($s, 2), 'l' => round($l, 2));
}

/**
 * Convert a hexadecimal color in RGB
 * @param string $hex
 * @return array
 */
function mh_color_hexToHsl($hex)
{
    list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
    return mh_color_rgbToHsl($r, $g, $b);
}

function mh_color_huesAreinSameInterval($hue1, $hue2, $interval = 30)
{
    return (round(($hue1 / $interval), 0, PHP_ROUND_HALF_DOWN) === round(($hue2 / $interval), 0, PHP_ROUND_HALF_DOWN));
}

function mh_hsl_color_sort($a, $b)
{
    //Compare the hue when they are in the same "range"
    if (!mh_color_huesAreinSameInterval($a['hsl']['h'], $b['hsl']['h'])) {
        if ($a['hsl']['h'] < $b['hsl']['h'])
            return -1;
        if ($a['hsl']['h'] > $b['hsl']['h'])
            return 1;
    }
    if ($a['hsl']['l'] < $b['hsl']['l'])
        return 1;
    if ($a['hsl']['l'] > $b['hsl']['l'])
        return -1;
    if ($a['hsl']['s'] < $b['hsl']['s'])
        return -1;
    if ($a['hsl']['s'] > $b['hsl']['s'])
        return 1;
    return 0;
}


function mh_hex_color_array_sort($colors_array)
{
    $colors = array();
    foreach ($colors_array as $c) {
        $colors[] = array('color' => $c);
    }

    foreach ($colors as &$color) {
        $color['hsl'] = mh_color_hexToHsl($color['color']);
    }

    usort($colors, 'mh_hsl_color_sort');
    $colors_array_sorted = array_column($colors, 'color');
    return $colors_array_sorted;
}
