<?php

namespace App\Http\Controllers\Wechat;

use App\Models\Common\TokenModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Ixudra\Curl\Facades\Curl;

class Media extends Controller
{

    public static function uploadImg($imageUrl, string $public = null)
    {
        if (empty($public)) {
            $token = Base::getAccessToken();
        } else {
            $token = TokenModel::getToken($public);
        }
        $filename = storage_path() . '/app/' . uniqid() . '.png';
        \File::put($filename, Curl::to($imageUrl)->get());
        $http = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $token . '&type=image';
        $response = Curl::to($http)
            ->withData([
                'media' => "@{$filename}"
            ])
            ->withFile('chat_' . uniqid(), $filename)
            ->post();
        \File::delete($filename);
        $result = json_decode($response, true);
        if (isset($result['errcode'])) {
            return ['code' => $result['errcode'], 'msg' => $result['errmsg']];
        } else {
            return ['code' => 0, 'msg' => 'OK', 'data' => $result];
        }
    }
}
