<?php
// CoreFlux/core/FileUpload.php

namespace Core\Utilities;

class FileUpload
{
    /**
     * Handle file upload.
     *
     * @param array $file The $_FILES['field'] array.
     * @param string $subFolder Subdirectory inside storage to save file (e.g., "vehicles").
     * @param array $allowedTypes Allowed MIME types (default: common images).
     * @param int $maxSize Maximum size in bytes (default: 5MB).
     * @return string|null Relative path to saved file (e.g., "vehicles/abc123.jpg") or null on failure.
     */
    public static function upload(array $file, string $subFolder = 'uploads', array $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'video/x-m4v'], int $maxSize = 20971520): ?string
    {
        // 1. Validate upload errors
        if (!isset($file['error']) || is_array($file['error'])) {
            error_log("FileUpload Error: Invalid upload parameters.");
            return null;
        }

        if ($file['error'] !== UPLOAD_ERR_OK) {
            error_log("FileUpload Error: Upload failed with error code {$file['error']}.");
            return null;
        }

        // 2. Validate size
        if ($file['size'] > $maxSize) {
            error_log("FileUpload Error: File too large ({$file['size']} bytes).");
            return null;
        }

        // 3. Validate MIME type
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = $finfo ? finfo_file($finfo, $file['tmp_name']) : null;
        finfo_close($finfo);

        if ($mimeType === false || !in_array($mimeType, $allowedTypes, true)) {
            error_log("FileUpload Error: Invalid MIME type '{$mimeType}'.");
            return null;
        }

        // 4. Create storage directory
        $targetDir = FS_STORAGE_PATH . DIRECTORY_SEPARATOR . $subFolder;
        if (!is_dir($targetDir) && !mkdir($targetDir, 0777, true)) {
            error_log("FileUpload Error: Failed to create storage directory '{$targetDir}'.");
            return null;
        }

        // 5. Generate unique filename
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $safeName = bin2hex(random_bytes(8)) . '.' . strtolower($extension);
        $targetPath = $targetDir . DIRECTORY_SEPARATOR . $safeName;

        // 6. Move uploaded file
        if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
            error_log("FileUpload Error: Failed to move uploaded file to '{$targetPath}'.");
            return null;
        }

        // Return relative path (e.g., "uploads/abc123.jpg")
        return $subFolder . '/' . $safeName;
    }
}
