<?php

namespace App\Services\Vendor\Miniprogram;

use App\Models\Common\TokenModel;
use App\Services\Service;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\File;
use Ixudra\Curl\Facades\Curl;

class Security extends Service
{
    public const IMG_API_URL = 'https://api.weixin.qq.com/wxa/img_sec_check';

    public const MSG_API_URL = 'https://api.weixin.qq.com/wxa/msg_sec_check';

    protected $token;

    protected $guzzleHttpClient;

    public function __construct()
    {
        $this->token = TokenModel::getToken(config('miniprogram.public_id'));
        $this->guzzleHttpClient = new Client();
    }

    public function imgSecCheck($imageUrl)
    {
        $filename = storage_path() . '/app/' . uniqid() . '.png';
        File::put($filename, Curl::to($imageUrl)->get());
        $resource = fopen($filename, 'r');
        File::delete($filename);
        $response = $this->guzzleHttpClient->request('post', self::IMG_API_URL, [
            'query' => [
                'access_token' => $this->token,
            ],
            'multipart' => [
                [
                    'name' => 'media',
                    'contents' => $resource,
                ],
            ],
        ]);
        $response = json_decode($response->getBody()->getContents(), true);

        return $response;
    }


    public function msgSecCheck($content)
    {
        $response = $this->guzzleHttpClient->request('post', self::MSG_API_URL, [
            'query' => [
                'access_token' => $this->token,
            ],
            'body' => json_encode([
                'content' => $content,
            ], JSON_UNESCAPED_UNICODE),
        ]);
        $response = json_decode($response->getBody()->getContents(), true);

        return $response;
    }
}
