<?php

namespace App\Http\Controllers\Welfare;

use App\Http\Controllers\Miniprogram\Auth;
use App\Models\Welfare\PrizeModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PrizeController extends Controller
{


    /**
     * 奖品列表
     * @param  Request  $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function prizes(Request $request)
    {
        $uid = Auth::auth();
        $per_page = $request->input('per_page', 20);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $per_page;
        $prizes = PrizeModel::where('uid', $uid);
        $count = $prizes->count();
        $list = $prizes->orderBy('created_at', 'desc')->offset($offset)->limit($per_page)->get();
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => [
                'list' => $list
            ]
        ]);
    }


    /**
     * 填写资料
     * @param  Request  $request
     * @return array|\Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function fill(Request $request)
    {
        $uid = Auth::auth();
        $validator = \Validator::make($request->all(), [
            'id' => 'required|integer',
            'name' => 'required',
            'weixin' => 'required'
        ], [
            'id.*' => '请选择一个奖品',
            'name.*' => '请输入姓名',
            'weixin.*' => '请输入微信账号,以便于联系你',
        ]);
        if ($validator->fails()) {
            return ['code' => 422, 'message' => $validator->errors()->first()];
        }
        $prize = PrizeModel::find($request->id);
        if (!$prize) {
            return ['code' => 404, 'message' => '不存在'];
        }
        if ($prize->uid != $uid) {
            return ['code' => 403, 'message' => '无权限'];
        }
        $prize->name = $request->name;
        $prize->weixin = $request->weixin;
        $prize->state = 1;
        $prize->save();
        return response()->json([
            'code' => 200,
            'message' => 'OK'
        ]);
    }
}
