<?php

namespace App\Http\Controllers\Goodnight;

use App\Http\Resources\Goodnight\EnterCollection;
use App\Http\Resources\Goodnight\EnterResource;
use App\Models\Goodnight\ActivityModel;
use App\Models\Goodnight\EnterModel;
use App\Models\Goodnight\RoomModel;
use App\Services\Goodnight\EnterService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Miniprogram\Auth;

class EnterController extends Controller
{
    // 创建报名
    public function store(Request $request)
    {
        $type = $request->input('type', '报名');

        $uid = Auth::auth();
        \DB::beginTransaction();
        try {
            $enterService = new EnterService();
            $enter_id = $enterService->enter($uid, $type);
            \DB::commit();
            return response()->json([
                'code' => 200,
                'message' => 'OK',
                'data' => [
                    'enter' => $enter_id
                ]
            ]);
        } catch (\Exception $exception) {
            \DB::rollBack();
            return array(
                'code' => $exception->getCode(),
                'message' => $exception->getMessage()
            );
        }
    }


    // 报名列表
    public function index(Request $request)
    {
        $uid = Auth::auth();
        $builder = EnterModel::where('uid', $uid);
        $enters = $builder->orderBy('activity_id', 'desc')->paginate($request->get('per_page', 20));
        foreach ($enters as $enter) {
            $enter->activity;
        }
        return new EnterCollection($enters);
    }


    // 查看报名信息
    public function show(Request $request, $id)
    {
        $uid = Auth::auth();
        $enter = EnterModel::findOrFail($id);
        $enter->activity;
        return new EnterResource($enter);
    }


    public function today(Request $request)
    {
        $activity = ActivityModel::whereRaw("from_unixtime(`showed_at`, '%Y-%m-%d') = ?", [date('Y-m-d')])->first();
        $uid = Auth::auth();
        $enter = EnterModel::where('uid', $uid)->where('type', '报名')->where('activity_id', $activity->id)->first();
        $room = null;
        if ($enter) {
            $room = RoomModel::find($enter->room_id);
        } else {
            $activity = ActivityModel::where([
                ['opened_at', '<', time()],
                ['closed_at', '>', time()]
            ])->firstOrFail();
            $enter = EnterModel::where('uid', $uid)->where('type', '报名')->where('activity_id', $activity->id)->first();
            if ($enter) {
                $room = RoomModel::find($enter->room_id);
            }
        }
        return response()->json([
            'code' => 200,
            'message' => 'OK',
            'data' => [
                'activity' => $activity,
                'enter' => $enter,
                'room' => $room
            ]
        ]);
    }
}
