<?php
/**
 * @package   BaForms
 * @author    Balbooa http://www.balbooa.com/
 * @copyright Copyright @ Balbooa
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace Balbooa\Component\Forms\Administrator\Helper\Filesystem;

defined('_JEXEC') or die;

abstract class Folder
{
    protected static array $exclude = ['.svn', 'CVS', '.DS_Store', '__MACOSX', '.', '..'];

    public static function exists(string $path): bool
    {
        return is_dir($path);
    }

    public static function create(string $path = '', int $mode = 0755): bool
    {
        if ($path === '') {
            return false;
        }

        return self::exists($path) || @mkdir($path, $mode, true);
    }

    protected static function items(string $path, string $type = 'file'): array
    {
        if (!is_dir($path)) {
            return [];
        }

        $files = [];
        foreach (scandir($path) ?: [] as $item) {
            if (in_array($item, self::$exclude)) {
                continue;
            }
            $fullPath = $path . DIRECTORY_SEPARATOR . $item;

            if ($type === 'file' && !is_file($fullPath)) {
                continue;
            }

            if ($type === 'dir' && !is_dir($fullPath)) {
                continue;
            }
            $files[] = $item;
        }
        sort($files, SORT_STRING);

        return $files;
    }

    public static function files(string $path): array
    {
        return self::items($path);
    }

    public static function folders(string $path): array
    {
        return self::items($path, 'dir');
    }

    public static function move(string $src, string $dest): bool
    {
        if (!self::exists($src) || self::exists($dest)) {
            return false;
        }

        return @rename($src, $dest);
    }

    public static function delete(string $path): void
    {
        if (!is_dir($path)) {
            return;
        }

        foreach (scandir($path) ?: [] as $item) {
            if (in_array($item, self::$exclude)) {
                continue;
            }

            $fullPath = $path . DIRECTORY_SEPARATOR . $item;

            if (is_link($fullPath) || is_file($fullPath)) {
                @unlink($fullPath);
            } elseif (is_dir($fullPath)) {
                self::delete($fullPath);
            }
        }

        @rmdir($path);
    }
}