<?php

namespace App\Api\Controllers;

use App\Api\Resources\ItemResource;
use App\Models\Vote;
use Illuminate\Http\Request;
use Jason\Api;

class VoteController extends Controller
{

    public function index()
    {
        $vote = Vote::where('status', 1)->first();

        return $this->success([
            'vote' => $vote,
            'lock' => $vote->logs()->where('user_id', Api::id())->exists(),
        ]);
    }

    public function show(Vote $vote, Request $request)
    {
        return $this->success([
            'lock' => $vote->logs()->where('user_id', Api::id())->exists(),
            'info' => $vote,
            'list' => ItemResource::collection($vote->items()->orderBy('sort', 'asc')->get()),
        ]);
    }

    public function submit(Vote $vote, Request $request)
    {
        if ($vote->status != 1) {
            return $this->success([
                'icon' => 'mdi-close-circle',
                'msg'  => '投票通道已关闭',
                'tips' => '本轮推举已结束，您在规定时间内未提交结果。'
            ]);
        }
        if ($vote->logs()->where('user_id', Api::id())->exists()) {
            return $this->success([
                'icon' => 'mdi-close-circle',
                'msg'  => '重复提交',
                'tips' => '您已经参与过推举，请不要重复提交。'
            ]);
        }

        if ($vote->type == 'equal') {
            foreach ($request->data as $item) {
                $vote->logs()->create([
                    'user_id' => Api::id(),
                    'item_id' => $item['id'],
                    'result'  => $item['result'],
                ]);
            }
        } else {
            foreach ($request->data as $item) {
                $vote->logs()->create([
                    'user_id' => Api::id(),
                    'item_id' => $item,
                    'result'  => 1,
                ]);
            }
        }

        return $this->success([
            'icon' => 'mdi-checkbox-marked-circle',
            'msg'  => '投票成功，感谢您的参与',
            'tips' => '您已提交本轮次推举票，为保密，已隐藏您的推举结果，任何人无法查询。'
        ]);
    }

}
