<?php

namespace App\Services\AdminDashboardOverview;

use App\Enums\DifficultyLevelEnums;
use App\Models\Contest;
use App\Models\ContestParticipant;
use Carbon\Carbon;

class ContestParticipantOverview extends BaseOverview
{
    public function overview()
    {
        $from_date = Carbon::now()->subDays(15)->toDateString();
        $to_date = now()->toDateString();

        // Get logs with contest_id and date
        $logs = ContestParticipant::query()
            ->selectRaw('DATE(submitted_at) as date, contest_id, COUNT(*) as total')
            ->whereNotNull('submitted_at')
            ->whereDate('submitted_at', '>=', $from_date)
            ->whereDate('submitted_at', '<=', $to_date)
            ->groupBy('date', 'contest_id')
            ->orderBy('date')
            ->get();

        $days = $this->getDays($from_date, $to_date);

        // Map contest_id to contest_level
        $contestLevels = Contest::whereIn('id', $logs->pluck('contest_id')->unique())
            ->pluck('contest_level', 'id');

        // Group logs by contest_level
        $logsByLevel = [];
        foreach ($logs as $log) {
            $level = $contestLevels[$log->contest_id]; // this is enum instance
            $levelKey = $level->value; // get the scalar value to use as array key

            $logsByLevel[$levelKey][$log->date] = ($logsByLevel[$levelKey][$log->date] ?? 0) + $log->total;
        }

        // Build series
        $series = [];
        foreach ($logsByLevel as $level => $datesData) {
            $data = [];
            foreach ($days as $day) {
                $data[] = $datesData[$day] ?? 0;
            }
            $series[] = [
                'name' => DifficultyLevelEnums::from($level)->label(),
                'data' => $data,
            ];
        }

        return [
            'series' => $series,
            'labels' => $days,
        ];

    }
}
