<?php
namespace App\Http\Controllers;use App\Http\Requests\LosersReportRequest;use App\Models\Keyword;use App\Services\LosersReportService;use App\Support\KeywordTargetOptions;use Illuminate\Pagination\LengthAwarePaginator;use Illuminate\View\View;
class LosersReportController extends Controller{public function __invoke(LosersReportRequest$r,LosersReportService$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($q=mb_strtolower(trim($r->string('q')->toString())))$keywords=$keywords->filter(fn($k)=>str_contains(mb_strtolower($k->phrase),$q))->values();$all=$s->rows($keywords->pluck('id'),now()->parse($r->input('from'))->startOfDay(),now()->parse($r->input('to'))->endOfDay());$rows=$s->losers($all);if($r->filled('min_lost'))$rows=$rows->filter(fn($x)=>($x['lost']??0)>=(int)$r->input('min_lost'))->values();if($r->filled('min_visibility_loss'))$rows=$rows->where('visibility_loss','>=',(float)$r->input('min_visibility_loss'))->values();if($type=$r->input('loss_type'))$rows=$rows->filter(fn($x)=>match($type){'top3'=>$x['category']==='dropped_top3','top10'=>in_array($x['category'],['dropped_top3','dropped_top10'],true),'top100'=>$x['dropped_out'],'dropped_out'=>$x['dropped_out']});$sort=in_array($r->input('sort'),['current','lost','visibility_loss','checked_at'],true)?$r->input('sort'):'lost';$rows=$rows->sortByDesc(fn($x)=>$x['dropped_out']?PHP_INT_MAX:($x[$sort]??-1))->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.losers',['projects'=>$projects,'rows'=>$pager,'summary'=>$s->summary($rows),'distribution'=>$s->distribution($rows),'critical'=>$s->critical($rows),'countries'=>KeywordTargetOptions::countries(),'languages'=>KeywordTargetOptions::languages()]);}}
