<?php
namespace App\Http\Controllers;
use App\Http\Requests\VisibilityReportRequest;use App\Models\Keyword;use App\Services\VisibilityReportService;use App\Support\KeywordTargetOptions;use Illuminate\View\View;
class VisibilityReportController extends Controller{public function __invoke(VisibilityReportRequest $r,VisibilityReportService $service):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')){$project=$projects->firstWhere('ulid',$r->input('project'));abort_unless($project,404);$keywords=$keywords->where('project_id',$project->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();$from=now()->parse($r->input('from'))->startOfDay();$to=now()->parse($r->input('to'))->endOfDay();$days=$from->diffInDays($to)+1;$previousFrom=$from->copy()->subDays($days);$previousTo=$from->copy()->subSecond();$checks=$service->measurements($keywords->pluck('id'),$from,$to);$previousChecks=$r->input('compare','previous')==='none'?collect():$service->measurements($keywords->pluck('id'),$previousFrom,$previousTo);$latest=$service->latest($checks);$previousLatest=$service->latest($previousChecks);$current=$service->score($latest);$previous=$service->score($previousLatest);$contributions=$service->contributions($latest,$previousLatest);$distribution=$service->distribution($latest,$keywords->count());$metrics=['current'=>$current,'previous'=>$previous,'change'=>$current!==null&&$previous!==null?round($current-$previous,2):null,'measured'=>$latest->count(),'top10'=>$distribution['top3']+$distribution['4_10'],'unranked'=>$distribution['unranked']];return view('reports.visibility',compact('projects','keywords','metrics','distribution')+['trend'=>$service->trend($checks),'previousTrend'=>$service->trend($previousChecks),'winners'=>$contributions->where('delta','>',0)->sortByDesc('delta')->take(5),'losers'=>$contributions->where('delta','<',0)->sortBy('delta')->take(5),'coverage'=>[$latest->count(),$keywords->count()],'countries'=>KeywordTargetOptions::countries(),'languages'=>KeywordTargetOptions::languages(),'formulaVersion'=>VisibilityReportService::FORMULA_VERSION]);}}
