
<?php

require_once __DIR__ . '/../config/constants.php';

class Upload
{

    public static function image($field, $folder)
    {

        if (!isset($_FILES[$field]) || $_FILES[$field]['error'] !== 0) {
            return null;
        }

        $file = $_FILES[$field];

        /*
        File size validation (1MB)
        */
        if ($file['size'] > 1048576) {
            throw new Exception("File size must be less than 1MB");
        }

        /*
        Allowed mime types
        */
        $allowed = [
            'image/jpeg',
            'image/png',
            'image/webp'
        ];

        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $file['tmp_name']);

        if (!in_array($mime, $allowed)) {
            throw new Exception("Invalid file type");
        }

        /*
        Create upload directory
        */
        $uploadDir = STORAGE_PATH . "uploads/" . $folder . "/";

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        /*
        Random filename
        */
        $filename = bin2hex(random_bytes(16));

        /*
        Destination path
        */
        $destination = $uploadDir . $filename . ".webp";

        /*
        Create image resource
        */
        switch ($mime) {

            case 'image/jpeg':
                $image = imagecreatefromjpeg($file['tmp_name']);
                break;

            case 'image/png':
                $image = imagecreatefrompng($file['tmp_name']);
                break;

            case 'image/webp':
                if (function_exists('imagecreatefromwebp')) {
                    $image = imagecreatefromwebp($file['tmp_name']);
                } else {
                    $image = imagecreatefromjpeg($file['tmp_name']);
                }
                break;

            default:
                throw new Exception("Unsupported image type");
        }

        /*
        Convert to webp if supported
        */
        if (function_exists('imagewebp')) {

            imagewebp($image, $destination, 80);

            imagedestroy($image);

            return "uploads/" . $folder . "/" . $filename . ".webp";

        } else {

            /*
            Fallback to JPG
            */

            $destination = $uploadDir . $filename . ".jpg";

            imagejpeg($image, $destination, 90);

            imagedestroy($image);

            return "uploads/" . $folder . "/" . $filename . ".jpg";
        }

    }

}