<?php
namespace App\Http\Controllers;
use App\Enums\{KeywordStatus,ProjectStatus,SerpCheckStatus}; use App\Models\Project; use Illuminate\Http\Request; use Illuminate\View\View;
class DashboardController extends Controller
{
 public function __invoke(Request $request):View
 {
  $days=in_array((int)$request->input('days'),[7,30,90],true)?(int)$request->input('days'):30;
  $projects=$request->user()->projects()->active()->orderBy('name')->get(['id','ulid','name']);
  $selected=null;if($request->filled('project')){$selected=$projects->firstWhere('ulid',$request->string('project')->toString());abort_unless($selected,404);}
  $projectIds=$selected?collect([$selected->id]):$projects->pluck('id');
  $keywords=$request->user()->projects()->whereIn('projects.id',$projectIds)->with(['keywords'=>fn($q)=>$q->where('status',KeywordStatus::Active)->with(['serpChecks'=>fn($q)=>$q->where('status',SerpCheckStatus::Completed)->where('checked_at','>=',now()->subDays($days))->latest('checked_at')->with(['results'=>fn($r)=>$r->where('is_project_domain',true)->orderBy('position')])])])->get()->flatMap(fn($p)=>$p->keywords->each->setRelation('project',$p));
  $rows=$keywords->map(function($keyword){$checks=$keyword->serpChecks->filter(fn($c)=>$c->results->isNotEmpty())->values();$current=$checks->get(0);$previous=$checks->get(1);$rank=$current?->results->min('position');$prior=$previous?->results->min('position');return ['keyword'=>$keyword,'project'=>$keyword->project,'current'=>$rank,'previous'=>$prior,'change'=>($rank&&$prior)?$prior-$rank:null,'checked_at'=>$current?->checked_at];})->sortByDesc('checked_at')->values();
  $measured=$rows->whereNotNull('current');
  return view('dashboard',['projects'=>$projects,'selectedProject'=>$selected,'days'=>$days,'rows'=>$rows->take(12),'winners'=>$rows->where('change','>',0)->sortByDesc('change')->take(5),'losers'=>$rows->where('change','<',0)->sortBy('change')->take(5),'metrics'=>['projects'=>$projects->count(),'keywords'=>$keywords->count(),'top10'=>$measured->where('current','<=',10)->count(),'average'=>$measured->isNotEmpty()?round($measured->avg('current'),1):null,'winners'=>$rows->where('change','>',0)->count(),'losers'=>$rows->where('change','<',0)->count()]]);
 }
}
