<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\OtpServer;
use App\Models\Service;
use App\Models\TopService;
use Illuminate\Http\Request;

class TopServiceController extends Controller
{
    public function index(Request $request)
    {
        $title = 'Top Services';
        $query = TopService::query();
        if ($request->filled('search')) {
            $term = $request->search;
            $query->where('server_id', 'like', "%{$term}%")
                ->orWhere('service_id', 'like', "%{$term}%");
        }
        $topServices = $query->latest()->paginate(15)->withQueryString();
        $servers = OtpServer::where('status', '1')->get();
        $search = $request->search ?? '';
        return view('backend.top-services.index', compact('title', 'topServices', 'servers', 'search'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'server_id' => 'required|string',
            'service_id' => 'required|string',
            'status' => 'required|in:0,1',
        ]);
        TopService::create($request->only('server_id', 'service_id', 'status'));
        return redirect()->back()->with('success', 'Top service added successfully');
    }

    public function destroy($id)
    {
        TopService::findOrFail($id)->delete();
        return redirect()->back()->with('success', 'Top service removed successfully');
    }
}