<?php

namespace App\Http\Controllers\Gnight;

use App\Exceptions\AlertException;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Miniprogram\Auth;
use App\Models\Gnight\UserModel;
use App\Models\Gnight\VoiceInviteModel;

class VoiceInvite extends Controller
{
    /**
     * @param  int  $share_uid
     * @return array
     * @throws AlertException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @api {get} /api/gnight/voiceinvite/check 分享邀请
     * @apiName check
     * @apiGroup Gnight
     *
     * @apiParam {int} $share_uid 分享链接id
     *
     */
    public function check($share_uid)
    {
        $uid = Auth::auth();
        $user = UserModel::findOrFail($share_uid);
        if (
            VoiceInviteModel::where([
            ['uid', $share_uid],
            ['invite_uid', $uid]
            ])->exists()
        ) {
            throw new AlertException("你已为TA助力", 102);
        }
        \DB::beginTransaction();
        try {
            \DB::table('kdgx_gnight_voice_invite')->insert([
                'created_at' => time(),
                'uid' => $share_uid,
                'invite_uid' => $uid
            ]);
            $voice_id = Voice::pop($share_uid);
            \DB::table('kdgx_gnight_get_voice')->insert([
                'created_at' => time(),
                'uid' => $share_uid,
                'get_uid' => $voice_id
            ]);
            \DB::commit();
            $notive = new Notive();
            $notive->getVoice($share_uid);
            return array(
                'code' => 200,
                'message' => 'success'
            );
        } catch (\Exception $e) {
            \DB::rollBack();
            throw $e;
        }
    }
}
