<?php
namespace App\Http\Controllers\Api;

use App\Models\User;
use EasyWeChat\Factory;
use Auth;

class PassportController extends Controller
{
    public function login()
    {
       $req = request()->post();
       $this->validate(request(), [
            'code'      => 'required',
       ]);

        $app = Factory::miniProgram(config('wechat.mini_program.default'));

        $data = $app->auth->session($req['code']);
        $decryptedData = $app->encryptor->decryptData($data['session_key'], $req['iv'], $req['encryptedData']);

        $user = User::where('openid',$decryptedData['openId'])->first();
        if(!$user){
            $flag = true;
            $user = new User();
            $user->nickname = $decryptedData['nickName'];
            $user->openid = $decryptedData['openId'];
            $user->head_img = $decryptedData['avatarUrl'];
            $user->scene_code = md5(uniqid());
            $response = $app->app_code->getUnlimit($user->scene_code, [
                'page'  => 'pages/index/index',
                'width' => 600,
            ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->saveAs(public_path('assets/qrcode'), "{$user->scene_code}.png");
                $user->share_qrcode = env('APP_URL')."/assets/qrcode/{$user->scene_code}.png";
            }
        }
        $user->remember_token = $data['session_key'];
        $user->save();
        if(isset($flag)){
            $user = User::where('openid',$decryptedData['openId'])->first();
        }

        $token = Auth::guard('api')->fromUser($user);

        return out([
            'token' => 'Bearer ' . $token,
            'user'  => $user
        ]);
    }
}


