<?php 
	function recursor($dir, $type) {
		$result = array();

		// create the pattern to get the type
		$x = "/_*.";
		for ($i = 0; $i < strlen($type); $i++){
			$x .= "[" . strtolower($type[$i]) . strtoupper($type[$i]) ."]";
		}

		// get the directories
		foreach(glob($dir . "/*") as $d) {
			if ( is_dir( $d ) ) {

				// find the files in each directory
				foreach (glob($d . $x) as $f) {
					$result[] = $f;
				}
				// $more = recursor($d, $type);
				// $result = array_merge($result, $more);
				$result = array_merge($result, recursor($d, $type));
			}
		}
		return $result;
	}

	$allowed_types = ["scss", "js"];
	$patterns = dirname(dirname(__file__)) . "/src/pg/patterns";


	if (!isset($_SERVER['QUERY_STRING']) || !in_array($_SERVER['QUERY_STRING'], $allowed_types)) {
		echo "File extension type is not defined. Ensure that you have added ?[file extension] to the URL. If you have defined a file extension and it is not allowed, you'll need to contact the an administrator to get the requested files.";
		die();
	}

	$type = $_SERVER['QUERY_STRING'];

	$file_list = recursor($patterns, $type);

	$f = tmpfile();
	$t = stream_get_meta_data($f)['uri'];
	$z = new ZipArchive();

	$zf = $z->open($t, ZipArchive::CREATE);
	foreach($file_list as $f) {
		$z->addFile($f, preg_replace('/^.*?patterns\//', '', $f));
	}
	$z->close();

	header('Content-type: application/zip');
	header(sprintf('Content-Disposition: attachment; filename="%s.zip"', $type));
	echo(file_get_contents($t)); ?>