<?php

class Uploader
{
    // Default settings
    private static $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'docx'];
    private static $maxFileSize = 5 * 1024 * 1024; // 5 MB
    private static $uploadBaseDir = '../public/uploads/';
    private static $baseUrl = URLROOT . '/uploads/';

    /**
     * Upload single or multiple files
     */
     
    public static function upload($fileInput, $options = [])
    {
        $allowedExtensions = $options['allowedExtensions'] ?? self::$allowedExtensions;
        $maxFileSize = $options['maxFileSize'] ?? self::$maxFileSize;
        $keepOriginalName = $options['keepOriginalName'] ?? false;

        // Normalize $_FILES array
        $files = self::normalizeFilesArray($fileInput);

        $uploadedFiles = [];

        foreach ($files as $file) {
            if ($file['error'] !== UPLOAD_ERR_OK) {
                throw new Exception("File upload error: " . self::fileUploadErrorMessage($file['error']));
            }

            if ($file['size'] > $maxFileSize) {
                throw new Exception("File {$file['name']} is too large. Max size allowed is " . self::formatBytes($maxFileSize));
            }

            $fileNameCmps = explode(".", $file['name']);
            $fileExtension = strtolower(end($fileNameCmps));

            if (!in_array($fileExtension, $allowedExtensions)) {
                throw new Exception("File {$file['name']} has invalid type. Allowed: " . implode(", ", $allowedExtensions));
            }

            // Auto-create folder
            $uploadDir = self::uploadPath();
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            $newFileName = $keepOriginalName ? self::sanitizeFileName(implode('.', array_slice($fileNameCmps, 0, -1))) . '.' . $fileExtension
                                              : md5(time() . $file['name']) . '.' . $fileExtension;

            $destPath = $uploadDir . $newFileName;

            if (!move_uploaded_file($file['tmp_name'], $destPath)) {
                throw new Exception("Error moving file {$file['name']}");
            }

            $uploadedFiles[] = [
                'newName' => $newFileName,
                'originalName' => $file['name'],
                'size' => $file['size'],
                'type' => $file['type'],
                'path' => $destPath,
                'url' => self::$baseUrl . date('Y') . '/' . date('m') . '/' . $newFileName
            ];
        }

        return count($uploadedFiles) === 1 ? $uploadedFiles[0] : $uploadedFiles;
    }

    /**
     * Normalize $_FILES array to easily loop through
     */
    private static function normalizeFilesArray($fileInput)
    {
        $files = [];

        if (is_array($fileInput['name'])) {
            $fileCount = count($fileInput['name']);
            for ($i = 0; $i < $fileCount; $i++) {
                $files[] = [
                    'name' => $fileInput['name'][$i],
                    'type' => $fileInput['type'][$i],
                    'tmp_name' => $fileInput['tmp_name'][$i],
                    'error' => $fileInput['error'][$i],
                    'size' => $fileInput['size'][$i],
                ];
            }
        } else {
            $files[] = $fileInput;
        }

        return $files;
    }

    /**
     * Return proper error message for file upload errors
     */
    private static function fileUploadErrorMessage($error_code)
    {
        $errors = [
            UPLOAD_ERR_INI_SIZE   => 'The uploaded file exceeds the upload_max_filesize limit.',
            UPLOAD_ERR_FORM_SIZE  => 'The uploaded file exceeds the MAX_FILE_SIZE directive.',
            UPLOAD_ERR_PARTIAL    => 'The uploaded file was only partially uploaded.',
            UPLOAD_ERR_NO_FILE    => 'No file was uploaded.',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
            UPLOAD_ERR_EXTENSION  => 'A PHP extension stopped the file upload.',
        ];

        return $errors[$error_code] ?? 'Unknown upload error.';
    }

    /**
     * Create upload path with Year/Month folders
     */
    private static function uploadPath()
    {
        return self::$uploadBaseDir . date('Y') . '/' . date('m') . '/';
    }

    /**
     * Clean filename to avoid issues
     */
    private static function sanitizeFileName($filename)
    {
        return preg_replace('/[^A-Za-z0-9\-\_]/', '_', $filename);
    }

    /**
     * Format bytes to human-readable
     */
    private static function formatBytes($bytes, $precision = 2)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= (1 << (10 * $pow));
        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}