<?php

namespace App\Api\Controllers;

use App\Models\Article;
use App\Models\User;
use App\Models\Vote;
use Illuminate\Http\Request;
use Jason\Api;

class IndexController extends Controller
{

    public function index(Request $request)
    {
        $user    = Api::user();
        $license = Article::where('id', 1)->value('content');
        $license = str_replace('{username}', $user->name, $license);
        $license = str_replace('{mobile}', $user->mobile, $license);

        $voteShow = false;

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

        if ($vote && ! $vote->logs()->where('user_id', Api::id())->exists()) {
            $voteShow = true;
        }

        return $this->success([
            'user'     => Api::user(),
            'sign'     => Api::user()->sign,
            'can_sign' => config('open_sign'),
            'license'  => $license,
            'vote'     => $voteShow,
            'dested'   => (bool) config('dested'),
        ]);
    }

    public function sign()
    {
        if (config('open_sign')) {
            $user = Api::user();

            $user->sign = 1;
            $user->save();

            return $this->success('签到成功');
        } else {
            return $this->failed('签到已关闭');
        }
    }

    function agent()
    {
        if (Api::user()->type == 1) {
            $users = User::where('parent_id', Api::id())->select(['id', 'mobile', 'name', 'sign'])->orderBy('sign')->get();
        } else {
            $users = User::where('type', 0)->select(['id', 'mobile', 'name', 'sign'])->orderBy('sign')->get();
        }

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

        if ($vote) {
            foreach ($users as $user) {
                $user->vote = $vote->logs()->where('user_id', $user->id)->exists();
            }
        }

        return $this->success([
            'now_vote' => $vote->title ?? '',
            'user'     => Api::user(),
            'desserts' => $users,
        ]);
    }

}
