<?php

namespace App\Http\Controllers\Admin\Searches;

use App\Http\Controllers\Controller;
use App\Models\Search;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class SearchesController extends Controller
{
    /**
     * searches list
     */
    public function index()
    {
        $searches = DB::table('searches')
            ->selectRaw('keyword, COUNT(*) as count')
            ->groupBy('keyword')
            ->orderByRaw('count DESC')
            ->paginate(20);

        $formatted = $searches->getCollection()->mapWithKeys(function ($item) {
            return [$item->keyword => $item->count];
        })->toArray();

        $searches->setCollection(collect($formatted));

        return Inertia::render('Admin/Searches/List', [
            'searches' => $searches
        ]);
    }

    /**
     * destroy search
     */
    public function destroy($search)
    {
        Search::where('keyword', $search)->delete();

        return redirect()->back()->with('message', [__('messages.search_deleted')]);
    }
}
