<?php

/**
 * Vvveb
 *
 * Copyright (C) 2022  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Vvveb\Plugins\Newsletter\System;

use function \Vvveb\humanReadable;

class Functions {
	static function templatesList($dir, $level = 0) {
		$contents = [];

		foreach (scandir($dir) as $node) {
			if ($node == '.' || $node == '..') {
				continue;
			}
			if (is_dir($dir . '/' . $node)) {
				$folder = humanReadable($node);
				$contents[$folder] = self :: templatesList($dir . DS . $node, ++$level);
				if (is_array($contents[$folder])) {
					$count = count($contents[$folder]);
					if ($count == 1) {
						//move one file per folder one level up
						$contents[$folder] = $contents[$folder][key($contents[$folder])];
					} else if ($count == 0) {
						//remove empty folders
						unset($contents[$folder]);
					} else {
						if ($level > 1) {
							//flatten 3+ level deep folder
							foreach ($contents[$folder] as $name => $file) {
								$contents[$folder . ' - ' . $name] = $file;
							}

							unset($contents[$folder]);
						}
					}
				}
				$level--;
			} else {
				if (substr($node, -5, 5) == '.html') {
					$name = humanReadable(basename($node, '.html'));
					$contents[$name] = $dir . DS . $node;
				}
			}
		}
		return $contents;
	}
}
