<?php

namespace App\Http\Controllers\Miniprogram;

use App\Http\Controllers\Controller;
use App\Models\AppProfileModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class App extends Controller
{
    private $appModel;

    public function __construct()
    {
        $this->appModel = new AppProfileModel();
    }

    /**
     * 添加配置
     * @param  Request  $request
     * @return array
     * @throws \ApiException
     */
    public function store(Request $request)
    {
        $public_id = config('miniprogram.public_id');
        $configs = $request->toArray();
        foreach ($configs as $field => $value) {
            Redis::hset("app:config:{$public_id}", $field, $value);
        }
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 更新配置
     * @param  Request  $request
     * @param  string  $app
     * @return array
     * @throws \ApiException
     */
    public function update(Request $request, string $app)
    {
        $public_id = config('miniprogram.public_id');
        $configs = $request->toArray();
        foreach ($configs as $field => $value) {
            Redis::hset("app:config:{$public_id}", $field, $value);
        }
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 获取配置信息
     * @param  string  $app
     * @return array
     * @throws \ApiException
     */
    public function show(string $app)
    {
        $public_id = config('miniprogram.public_id');
        $profile = Redis::hgetall("app:config:{$public_id}");
        return response([
            'code' => 200,
            'message' => 'success',
            'data' => $profile
        ]);
    }


    /**
     * 阅读教程
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function readCourse(Request $request)
    {
        $uid = \App\Http\Controllers\Miniprogram\Auth::auth();
        $version = $request->input('version');
        Redis::SETBIT("app:version:{$version}:course", $uid, 1);
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }


    /**
     * 教程是否阅读
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function course($version)
    {
        $uid = \App\Http\Controllers\Miniprogram\Auth::auth();
        $course = Redis::getbit("app:version:{$version}:course", $uid);
        return response([
            'code' => 200,
            'message' => 'OK',
            'data' => [
                'course' => $course
            ]
        ]);
    }
}
