<?php

namespace App\Handlers;

use Intervention\Image\Facades\Image;
use Illuminate\Support\Str;

class FileUploadHandler
{
    // 只允许以下后缀名的图片文件上传
    protected $allowed_ext = ["png", "jpg", 'jpeg', 'pdf'];


    public function save($file)
    {

        $folder_name = "/" . date("Ymd", time());
        $upload_path = public_path() . '/uploads' . $folder_name;

        $extension = strtolower($file->getClientOriginalExtension()) ?: 'png';
        $filename = time() . '_' . Str::random(10) . '.' . $extension;

        if (!in_array($extension, $this->allowed_ext)) {
            return false;
        }

        $file->move($upload_path, $filename);


        return "$folder_name/$filename";
    }

    public function reduceSize($file_path, $max_width)
    {

        $image = Image::make($file_path);
        $image->resize($max_width, null, function ($condition) {
            $condition->aspectRatio();

            $condition->upsize();
        });
        $image->save();
    }
}