<?php

namespace App\Managers;

use App\Models\Log\AppSignModel;
use App\Models\Log\SignRewardLogModel;
use App\Models\User\SignModel;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Carbon;

class SignInManager
{

    public static $SIGN_RULE = array(
        1 => [
            "is_big_reward" => 0,
            "reward" => ['flower', 'popularity', 'app_lock']
        ],
        2 => [
            "is_big_reward" => 0,
            "reward" => ['flower', 'popularity', 'app_lock']
        ],
        3 => [
            "is_big_reward" => 1,
            "reward" => ['flower', 'popularity', 'app_lock', 'couponsvip'] // 超级会员满减券抵扣9元
        ],
        4 => [
            "is_big_reward" => 0,
            "reward" => ['flower', 'popularity', 'app_lock']
        ],
        5 => [
            "is_big_reward" => 1,
            "reward" => ['flower', 'popularity', 'app_lock', 'coupon72dis'] // 72小时折扣券
        ],
        6 => [
            "is_big_reward" => 0,
            "reward" => ['flower', 'popularity', 'app_lock']
        ],
        7 => [
            "is_big_reward" => 1,
            "reward" => ['flower', 'popularity', 'app_lock', 'coupon72pair'] // 72小时报名券
        ]
    );


    public function today(int $uid): array
    {
        $be_continuous_day = 1;     // 连续签到几天
        $is_big_reward = 0;         // 是否有礼包
        $is_sign = false;           // 今日是否签到
        $arrReward = array();       // 签到奖励
        try {
            $sign = SignModel::where("uid", $uid)->orderBy("id", 'desc')->firstOrFail();
            if ($sign->sign_at->isToday()) {
                $is_sign = true;
                $be_continuous_day = $sign->be_continuous_day;
                $is_big_reward = self::$SIGN_RULE[$be_continuous_day]['is_big_reward'];
                foreach (self::$SIGN_RULE[$be_continuous_day]['reward'] as $reward) {
                    if (
                        SignRewardLogModel::where([['uid', $uid], ['reward', $reward]])
                        ->where('created_at', '>', Carbon::today()->toDateTimeLocalString())->exists()
                    ) {
                        $arrReward[$reward] = true;
                    } else {
                        $arrReward[$reward] = false;
                    }
                }
            } elseif ($sign->sign_at->isYesterday()) {
                $be_continuous_day = $sign->be_continuous_day;
                $is_big_reward = self::$SIGN_RULE[($be_continuous_day % 7) + 1]['is_big_reward'];
            }
        } catch (ModelNotFoundException $exception) {
            $be_continuous_day = 0;
        }

        return array(
            'be_continuous_day' => $be_continuous_day,
            'is_big_reward' => $is_big_reward,
            'is_sign' => $is_sign,
            'reward' => $arrReward
        );
    }
}
