<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Mtc\MercuryDataModels\SearchTermLog;

class SearchTermReportController extends Controller
{
    public function index(Request $request): array
    {
        $request->validate([
            'days' => ['sometimes', Rule::in([30, 60, 90])],
        ]);

        $days = (int) $request->input('days', 30);
        $from = now()->subDays($days)->startOfDay();

        $popularTerms = SearchTermLog::query()
            ->where('date', '>=', $from)
            ->selectRaw('normalized_term as term, SUM(hits) as total_hits')
            ->groupBy('normalized_term')
            ->orderByDesc('total_hits')
            ->limit(50)
            ->get();

        $topTerms = SearchTermLog::query()
            ->where('date', '>=', $from)
            ->selectRaw('normalized_term, SUM(hits) as total_hits')
            ->groupBy('normalized_term')
            ->orderByDesc('total_hits')
            ->limit(10)
            ->pluck('normalized_term');

        $chart = $this->buildChart($topTerms, $from);

        return [
            'results' => [
                'popular_terms' => $popularTerms,
                'chart' => $chart,
            ],
        ];
    }

    private function buildChart($topTerms, $from): array
    {
        $colours = [
            '#00236C', '#E63946', '#2A9D8F', '#E9C46A', '#264653',
            '#F4A261', '#6A0572', '#1D3557', '#457B9D', '#A8DADC',
        ];

        $dailyData = SearchTermLog::query()
            ->where('date', '>=', $from)
            ->whereIn('normalized_term', $topTerms)
            ->selectRaw('normalized_term, date, SUM(hits) as total_hits')
            ->groupBy('normalized_term', 'date')
            ->orderBy('date')
            ->get()
            ->groupBy('normalized_term');

        $labels = SearchTermLog::query()
            ->where('date', '>=', $from)
            ->whereIn('normalized_term', $topTerms)
            ->select('date')
            ->distinct()
            ->orderBy('date')
            ->pluck('date')
            ->map(fn ($date) => $date->format('Y-m-d'));

        $dateIndex = $labels->flip();

        $datasets = $topTerms->values()->map(function ($term, $i) use ($dailyData, $labels, $colours) {
            $termData = $dailyData->get($term, collect());
            $hitsByDate = $termData->keyBy(fn ($row) => $row->date->format('Y-m-d'));

            $data = $labels->map(fn ($date) => $hitsByDate->has($date) ? $hitsByDate[$date]->total_hits : 0);

            return [
                'label' => $term,
                'data' => $data->values(),
                'borderColor' => $colours[$i % count($colours)],
                'backgroundColor' => $colours[$i % count($colours)] . '33',
                'fill' => false,
                'tension' => 0.3,
            ];
        });

        return [
            'labels' => $labels->values(),
            'datasets' => $datasets->values(),
        ];
    }
}
