<?php

namespace app\dao;

use App\model\Signlog;



class SignDao {
    /**
     * 签到函数
     * 
     */
    public static function Sign($user_id) {
        $Signlog=new Signlog();
        $Signlog->userid=$user_id;
        $Signlog->save();
        UserRewardDao::sing($user_id,30);
    }
    /**
     * 查询今天是否签到
     * 0没签到1签到
     */
    public static function search_Sign_today($user_id){
        $today = date('Y-m-d');
        $is_sign=Signlog::where('userid',$user_id)->where('created_at', '>=', $today." 00:00:00")->count();
        return $is_sign==0?0:1;
    }
    /**
     * 查询当月签到数据
     * 
     */
    public static function search_Sign_tomon($user_id){
        $startTime = date('Y-m-01',time());//获取该月份的第一天
        $endTime = date('Y-m-t',time());//获取该月份的最后一天
        $mon_data=Signlog::whereBetween('created_at', [$startTime." 00:00:00", $endTime." 23:59:59"])->orderBy('created_at','ASC')->get();
        $signDates = [];
        foreach ($mon_data as $sign) {
            // 将签到日期提取出来
            $signDates[] = $sign->created_at->format('Y-m-d'); // 格式化为 Y-m-d 格式
        }
    
        // 判断是否连续签到
        $consecutiveSign = true;
        $missingDates = []; // 用于记录未签到的日期
    
        for ($i = 1; $i < count($signDates); $i++) {
            // 计算相邻两天的差距
            $currentDate = strtotime($signDates[$i]);
            $previousDate = strtotime($signDates[$i - 1]);
            $diff = ($currentDate - $previousDate) / (60 * 60 * 24); // 日期差值（天数）
    
            if ($diff != 1) {
                $consecutiveSign = false; // 如果差距不为 1 天，说明不是连续签到
                $missingDates[] = date('Y-m-d', strtotime('+1 day', $previousDate)); // 记录缺失的日期
            }
        }
    
        return [
            'consecutive' => $consecutiveSign,
            'missing_dates' => $missingDates
        ];
    }
}
