<?php

namespace App\Services\Quiz\Criteria;

use App\Models\User;
use Carbon\Carbon;

class ConsecutiveDays implements BadgeCriteriaInterface
{
    public function isMet(User $user, array $criteria): bool
    {
        // Required streak value (default = 7 days)
        $requiredStreak = isset($criteria['value']) ? (int) $criteria['value'] : 7;

        // Get unique login dates sorted ASC
        $dates = $user->loginLogs()
            ->selectRaw('DATE(created_at) as date')
            ->groupBy('date')
            ->orderBy('date', 'asc')
            ->pluck('date');

        if ($dates->isEmpty()) {
            return false;
        }
 
        $streak = 1;

        for ($i = 1; $i < $dates->count(); $i++) {
            $prev = Carbon::parse($dates[$i - 1]);
            $curr = Carbon::parse($dates[$i]);

            // Check if current date is exactly previous + 1 day
            if ($prev->addDay()->isSameDay($curr)) {
                $streak++;
            } else {
                $streak = 1; // reset streak
            }

            // If streak reached required size
            if ($streak >= $requiredStreak) {
                return true;
            }
        }

        return false;
    }
}
