<?php

namespace App\Http\Controllers;

use Illuminate\Support\Str;
use Yo;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
  public function image()
  {
    $base64 = request()->post('base64');
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
      $type = ['png', 'jpeg', 'jpg', 'gif'];
      if (!in_array($result[2], $type)) Yo::error_echo(100027);
      $disk = Storage::disk('public');
      $name = Str::orderedUuid();
      $date = date('Y/m');
      $path = "/assets/upload/image/$date/$name.$result[2]";
      $put = $disk->put($path, base64_decode(str_replace($result[1], '', $base64)));
      if (!$put) Yo::error_echo(100028, ['put']);
      $save = "/storage/assets/upload/image/$date/$name.$result[2]";
      return Yo::echo([
        'url' => $save
      ]);
    } else {
      Yo::error_echo(100028, ['base64']);
    }
  }
}
