<?php
namespace boru\ai\Asset;

class MimeTypeResolver
{
    public static function detect($path, $fallback = 'application/octet-stream')
    {
        $extensionMimeType = static::fromPath($path);
        if ($extensionMimeType !== null) {
            return $extensionMimeType;
        }

        if (function_exists('mime_content_type')) {
            $mimeType = @mime_content_type($path);
            if (is_string($mimeType) && $mimeType !== '') {
                return $mimeType;
            }
        }

        return $fallback;
    }

    public static function fromPath($path)
    {
        $extension = strtolower((string)pathinfo((string)$path, PATHINFO_EXTENSION));
        if ($extension === '') {
            return null;
        }

        $mimeTypes = array(
            'csv' => 'text/csv',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'xls' => 'application/vnd.ms-excel',
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        );

        return isset($mimeTypes[$extension]) ? $mimeTypes[$extension] : null;
    }
}
