<?php
class UploadFile
{
    public static function sendRestrictedFiles($dir, $file, $fileName, $allowedFiles, $newFileName = null)
    {
        if (!is_dir($dir))
            mkdir($dir, 0755, true);
        if ($file['error'] !== 0)
            return null;

        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = explode(",", str_replace(" ", "", strtoupper($allowedFiles)));

        if (!in_array(strtoupper($ext), $allowed)) {
            throw new Exception("Formato inválido. Aceitos: " . implode(", ", $allowed));
        }

        $finalName = $newFileName ?? ($fileName == "default" ? date('Ymdhis') . "-" . rand(0, 999) : $fileName . "-" . rand(0, 999)) . '.' . $ext;

        if (move_uploaded_file($file['tmp_name'], $dir . '/' . $finalName))
            return $finalName;
        throw new Exception("Erro ao enviar o arquivo!");
    }

    public static function sendFiles($dir, $file, $fileName = "default", $newFileName = null)
    {
        if (!is_dir($dir))
            mkdir($dir, 0755, true);
        if ($file['error'] !== 0)
            return null;

        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $finalName = $newFileName ?? ($fileName == "default" ? date('Ymdhis') . "-" . rand(0, 999) : $fileName . "-" . rand(0, 999)) . '.' . $ext;

        if (move_uploaded_file($file['tmp_name'], $dir . '/' . $finalName))
            return $finalName;
        throw new Exception("Erro ao enviar o arquivo!");
    }

    public static function sendImageBase64($dir, $file, $fileName, $newFileName = null)
    {
        if (!is_dir($dir))
            mkdir($dir, 0755, true);
        if (!$file)
            return null;

        $parts = explode(";base64,", $file);
        $image_type = str_replace("data:image/", "", $parts[0]);
        $data = base64_decode($parts[1]);

        $finalName = $newFileName ?? ($fileName == "default" ? date('Ymdhis') . "-" . rand(0, 999) : $fileName . "-" . rand(0, 999)) . '.' . $image_type;

        if (file_put_contents($dir . '/' . $finalName, $data))
            return $finalName;
        throw new Exception("Erro ao gravar arquivo!");
    }
}