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

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

defined('_JEXEC') or die;

abstract class File
{
    public static function exists(string $file): bool
    {
        return is_file($file);
    }

    public static function delete(string $file): bool
    {
        if (!is_file($file)) {
            return false;
        }

        @chmod($file, 0777);

        return @unlink($file);
    }

    public static function upload(string $src, string $dest): bool
    {
        $baseDir = \dirname($dest);
        if (!file_exists($baseDir)) {
            Folder::create($baseDir);
        }

        $result = false;
        if (is_writable($baseDir) && move_uploaded_file($src, $dest)) {
            @chmod($dest, 0644);
            $result = true;
        }

        return $result;
    }

    public static function getExt(string $file): string
    {
        $dot = strrpos($file, '.');
        if ($dot === false) {
            return '';
        }

        $ext = substr($file, $dot + 1);
        if (str_contains($ext, '/') || (DIRECTORY_SEPARATOR === '\\' && str_contains($ext, '\\'))) {
            return '';
        }

        return $ext;
    }

    public static function makeSafe(string $file): string
    {
        $file = rtrim($file, '.');

        if (\function_exists('transliterator_transliterate') && \function_exists('iconv')) {
            $file = iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", transliterator_transliterate('Any-Latin; Latin-ASCII', $file));
        }

        $regex = ['#(\.){2,}#', '#[^A-Za-z0-9._\- ]#', '#^\.#'];

        return trim(preg_replace($regex, '', $file));
    }

    public static function write(string $file, string $buffer): bool
    {
        if (\function_exists('set_time_limit')) {
            set_time_limit(\ini_get('max_execution_time'));
        }

        $dir = \dirname($file);
        if (!file_exists($dir) && !Folder::create($dir)) {
            return false;
        }

        return file_put_contents($file, $buffer) !== false;
    }

    public static function copy(string $src, string $dest): bool
    {
        if (!is_readable($src)) {
            return false;
        }

        $dir = \dirname($dest);
        if (!file_exists($dir) && !Folder::create($dir)) {
            return false;
        }

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

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

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

    public static function stripExt(string $file): string
    {
        return preg_replace('#\.[^.]*$#', '', $file);
    }
}