<?php
/**
 * Dynamic CSS Style plugin file.
 *
 * @package COCO\Dynamic-style
 */

	$is_wps_theme = COCO()->is_wps_theme();	
	$cookie_consent_custom_background = xbox_get_field_value( 'coco-options', 'cookie-consent-custom-background' );
	$cookie_consent_background_color = xbox_get_field_value( 'coco-options', 'cookie-consent-background-color' );
	$cookie_consent_background_color_opacity = xbox_get_field_value( 'coco-options', 'cookie-consent-background-color-opacity' ) / 100;
	$cookie_consent_button_color = xbox_get_field_value( 'coco-options', 'cookie-consent-button-color' );
	$cookie_consent_privacy_dark_popup = xbox_get_field_value( 'coco-options', 'cookie-consent-privacy-dark-popup' );
?>

<style>
	#cookie-bar {
		background-color: <?php echo coco_hex2rgba($cookie_consent_background_color, $cookie_consent_background_color_opacity); ?>!important;		
	}
	#cookie-bar p {
		color: <?php echo coco_get_brightness( $cookie_consent_background_color, '#FFFFFF', '#000000' ); ?>!important;
	}
	#cookie-bar .cookie-bar__btn {
		background-color: <?php echo $cookie_consent_button_color; ?>!important;
		color: <?php echo coco_get_brightness( $cookie_consent_button_color, '#FFFFFF', '#000000' ); ?>!important;
	}
	<?php if( $cookie_consent_privacy_dark_popup == 'on' ) : ?>
		.cookie-bar-privacy-popup__dialog {
			background-color: #000!important;
			color: #eee!important;
		}
	<?php endif; ?>
</style>

<?php
function coco_get_brightness( $hex, $light_color, $dark_color ) {
	// returns brightness value from 0 to 255
	// strip off any leading #
	$hex = str_replace( '#', '', $hex );

	$c_r = hexdec( substr( $hex, 0, 2 ) );
	$c_g = hexdec( substr( $hex, 2, 2 ) );
	$c_b = hexdec( substr( $hex, 4, 2 ) );

	return ( ( $c_r * 299 ) + ( $c_g * 587 ) + ( $c_b * 114 ) ) / 1000 > 180 ? $dark_color : $light_color;
}

function coco_hex2rgba($color, $opacity = false) {
 
	$default = 'rgb(0,0,0)';

	//Return default if no color provided
	if(empty($color))
	return $default; 

	//Sanitize $color if "#" is provided 
	if ($color[0] == '#' ) {
		$color = substr( $color, 1 );
	}

	//Check if color has 6 or 3 characters and get values
	if (strlen($color) == 6) {
			$hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
	} elseif ( strlen( $color ) == 3 ) {
			$hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
	} else {
			return $default;
	}

	//Convert hexadec to rgb
	$rgb =  array_map('hexdec', $hex);

	//Check if opacity is set(rgba or rgb)
	if($opacity){
		if(abs($opacity) > 1)
			$opacity = 1.0;
		$output = 'rgba('.implode(",",$rgb).','.$opacity.')';
	} else {
		$output = 'rgb('.implode(",",$rgb).')';
	}

	//Return rgb(a) color string
	return $output;
}
