<?php
namespace App\Http\Controllers;use App\Http\Requests\VisibilityReportRequest;use App\Models\Keyword;use App\Services\WinnersReportService;use App\Support\KeywordTargetOptions;use Illuminate\Pagination\LengthAwarePaginator;use Illuminate\View\View;
class WinnersReportController extends Controller{public function __invoke(VisibilityReportRequest$r,WinnersReportService$s):View{$projects=$r->user()->projects()->active()->orderBy('name')->get(['id','ulid','name']);$keywords=Keyword::query()->active()->whereHas('project',fn($q)=>$q->where('user_id',$r->user()->id)->whereNull('archived_at'))->with('project:id,ulid,name')->get();if($r->filled('project')){$p=$projects->firstWhere('ulid',$r->input('project'));abort_unless($p,404);$keywords=$keywords->where('project_id',$p->id)->values();}foreach(['country_code'=>'country','language_code'=>'language','device'=>'device','search_engine'=>'engine']as$column=>$key)if($r->filled($key))$keywords=$keywords->where($column,$r->input($key))->values();if($search=trim($r->string('q')->toString()))$keywords=$keywords->filter(fn($k)=>str_contains(mb_strtolower($k->phrase),mb_strtolower($search)))->values();$rows=$s->winners($s->rows($keywords->pluck('id'),now()->parse($r->input('from'))->startOfDay(),now()->parse($r->input('to'))->endOfDay()));if($r->filled('min_gained'))$rows=$rows->filter(fn($x)=>($x['gained']??0)>=(int)$r->input('min_gained'))->values();$sort=in_array($r->input('sort'),['current','gained','contribution','checked_at'],true)?$r->input('sort'):'gained';$rows=$rows->sortByDesc($sort)->values();$page=max(1,(int)$r->input('page',1));$pager=new LengthAwarePaginator($rows->forPage($page,25)->values(),$rows->count(),25,$page,['path'=>$r->url(),'query'=>$r->query()]);return view('reports.winners',['projects'=>$projects,'rows'=>$pager,'summary'=>$s->summary($rows),'distribution'=>$s->distribution($rows),'countries'=>KeywordTargetOptions::countries(),'languages'=>KeywordTargetOptions::languages()]);}}
