<?php
/**
 * File that does SVG Generation.
 *
 * @package Row Separators
 */

$main_svg_php_filename = 'svgs.php';
$saved_svg_filename = '-dev-separator-template.svg';

// Process the SVG file.
$file = file_get_contents( $saved_svg_filename );

$file = str_replace( "\n", '', $file );
preg_match_all( '#((<g[^>]+>)(.*?)</g>)#', $file, $svg_matches );


$svgs = array();
foreach ( $svg_matches[3] as $key => $svg_match ) {
	$svg = trim( $svg_match );
	if ( empty( $svg ) ) {
		continue;
	}

	$svg = preg_replace( '/\s+/', ' ', $svg );
	$svg = str_replace( '<', "\n<", $svg );
	$svg = preg_replace( '/id=(\'|")[^\'"]+(\'|")\s?/', '', $svg );

	$title = $svg_matches[2][ $key ];
	preg_match( '/id=[\'"]([^\'"]+)[\'"]/', $title, $title_matches );
	$title = $title_matches[1];

		preg_match_all( '/(\_x..\_)/', $title, $special_matches );
	foreach ( $special_matches[1] as $special_match ) {
		$title = str_replace( $special_match, hex_to_str( trim( $special_match, '_x' ) ), $title );
	}
	$title = str_replace( '_', ' ', $title );

	$id = $title;
	$name = '';
	$height = '200';

	if ( stripos( $title, '|' ) != false ) {
		list( $id, $name, $height ) = explode( '|', $title );
	} else {
		continue;
	}
	if ( empty( $name ) ) {
		$name = $id;
	}

	// If there are duplicate layer names, this will show up in the height parameter as a number, get rid of it.
	$height = preg_replace( '/[^0-9].*$/', '', $height );

	$svgs[ $id ] = "
	\$ret['$id'] = array(
		'name' => __( '$name', GAMBIT_ROW_SEPARATORS ),
		'width' => 1600,
		'height' => $height,
		'svg' => '$svg',
	);
";
}

// Sort.
ksort( $svgs );

/**
 * Converts hex to string.
 *
 * @param string $hex - The input, in hexadecimal form.
 * @return string $string - The input, now in alphanumeric string form.
 */
function hex_to_str( $hex ) {
	$string = '';
	for ( $i = 0; $i < strlen( $hex ) -1; $i += 2 ) {
		$string .= chr( hexdec( $hex[ $i ] . $hex[ $i + 1 ] ) );
	}
	return $string;
}



/**
 * Save the new PHP contents.
 */
$main_script = explode( "\n", file_get_contents( $main_svg_php_filename ) );

$new_file_contents = '';
$wait_for_end = false;
foreach ( $main_script as $line ) {
	if ( $wait_for_end ) {
		if ( preg_match( '/\/\/ DECOR SVG CODE END/', $line ) ) {
			$wait_for_end = false;
		}
		if ( $wait_for_end ) {
			continue;
		}
	}
	if ( preg_match( '/\/\/ DECOR SVG CODE START/', $line ) ) {
		$wait_for_end = true;
		$new_file_contents .= $line . "\n";

		foreach ( $svgs as $svg ) {
			$new_file_contents .= $svg;
		}
		continue;
	}
	$new_file_contents .= $line . "\n";
}

$main_script = fopen( $main_svg_php_filename, 'w' );
fwrite( $main_script, $new_file_contents );
fclose( $main_script );


