<?php

namespace Modules\User\Listeners;

use Carbon\Carbon;
use Modules\User\Events\UserSignSuccess;
use Modules\User\Models\Sign;
use Modules\User\Models\SignLog;

class UserSignContinueDays
{

    public function handle(UserSignSuccess $event)
    {
        $log = $event->log;

        # todo .连续签到天数的一个计算，用最后的签到日期，是否可行？
        $sign = Sign::updateOrCreate([
            'user_id' => $log->user_id,
        ], [
            'counts'       => SignLog::query()->distinct()->where('user_id', $log->user_id)->count('date'),
            'last_sign_at' => Carbon::now(),
        ]);
        if ($sign->wasRecentlyCreated) {
            $sign->continue_days = 1;
        } else {
            $sign->continue_days = $sign->getContinueDays();
        }
        $sign->save();
    }

}
