<?php
ini_set( 'display_errors', 0 );
error_reporting( 0 );

//$aColorsInput = Array(
//	1 => '00ff00',
//	2 => '0000ff',
//	3 => '000000'
//);
$aColorsDef = Array(
	1 => 'ff0000',
	2 => '00ff00',
	3 => '0000ff'
);
if( isset( $_GET['aColorsInput'] ) ){
	foreach( $_GET['aColorsInput'] as $key => $val ) if( empty( $val ) ) unset( $_GET['aColorsInput'][$key] );
	$aColorsInput = $_GET['aColorsInput'] + $aColorsDef;
} else{
	$aColorsInput = $aColorsDef;
}
//var_dump( $aColorsInput );
//exit;
foreach( $aColorsInput as &$mColor ){
	if( !preg_match( '|^[0-9a-f]{6}$|', $mColor ) ) die( 'Invalid input color!' );
	$mColor = Array( 'red' => hexdec( substr( $mColor, 0, 2 ) ), 'green' => hexdec( substr( $mColor, 2, 2 ) ), 'blue' => hexdec( substr( $mColor, 4, 2 ) ) );
}
if( !preg_match( '|^[^/]+\\.png$|', $_GET['sFileName'] ) ) die( 'Invalid file name!' );

// function imagepalettetotruecolor(&$img)
// {
	// if (!imageistruecolor($img))
	// {
		// $w = imagesx($img);
		// $h = imagesy($img);
		// $img1 = imagecreatetruecolor($w,$h);
		// imagecopy($img1,$img,0,0,0,0,$w,$h);
		// $img = $img1;
	// }
//}
$imgsrc = imagecreatefrompng( 'templates/images/' . $_GET['sFileName'] );
//imagepalettetotruecolor( $imgsrc );
$width = imagesx( $imgsrc );
$height = imagesy( $imgsrc );
$imgdest = imagecreatetruecolor( $width, $height );
imagealphablending($imgdest, false);
//$col=imagecolorallocatealpha($imgdest,255,255,255,127);
//imagefilledrectangle($imgdest,0,0,$width, $height,$col);
//imagealphablending($imgdest,true);
for( $x = 0; $x < $width; $x++ ) for( $y = 0; $y < $height; $y++ ){
	$rgb = imagecolorat( $imgsrc, $x, $y );
	$colors = imagecolorsforindex($imgsrc, $rgb);
	$aColors = Array();
	$aColorsM = Array( 1 => $colors['red'], 2 => $colors['green'], 3 => $colors['blue'] );
	foreach( Array( 'red', 'green', 'blue' ) as $color ){
		foreach( $aColorsM as $iKey => $iMod ){
			$aColors[$color] = $aColors[$color] + ( $iMod * $aColorsInput[$iKey][$color] / 255 );
		}
		$aColors[$color] = min( 255, $aColors[$color] );
	}
//	var_dump( $colors['alpha'] );
	$colors = imagecolorallocatealpha( $imgdest, $aColors['red'], $aColors['green'], $aColors['blue'], $colors['alpha'] );
	imagesetpixel( $imgdest, $x, $y, $colors );
//	$colors['x'] = $x; $colors['y'] = $y;
	
//	var_dump($colors);
}
if( !is_dir( 'templates/images/' . implode( '_', $_GET['aColorsInput'] ) ) ) mkdir( 'templates/images/' . implode( '_', $_GET['aColorsInput'] ) );
header( 'Content-type: image/png' );
imagesavealpha($imgdest,true);
imagepng( $imgdest, 'templates/images/' . implode( '_', $_GET['aColorsInput'] ) . '/' . $_GET['sFileName'] );
readfile( 'templates/images/' . implode( '_', $_GET['aColorsInput'] ) . '/' . $_GET['sFileName'] );