<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\ApiDetail;
use App\Models\OtpServer;
use Illuminate\Http\Request;

class OtpServerController extends Controller
{
    public function index(Request $request)
    {
        $title = 'OTP Servers';
        $query = OtpServer::with('apiDetail')->orderBy('server_name', 'asc');
        if ($request->filled('search')) {
            $term = $request->search;
            $query->where('server_name', 'like', "%{$term}%")
                ->orWhere('server_code', 'like', "%{$term}%");
        }
        $servers = $query->paginate(15)->withQueryString();
        $apiDetails = ApiDetail::all();
        $search = $request->search ?? '';
        return view('backend.otp-servers.index', compact('title', 'servers', 'apiDetails', 'search'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'server_name' => 'required|string|max:255',
            'server_code' => 'required|string|max:50',
            'provider_server_id' => 'required|string|max:100',
            'api_id' => 'required|exists:api_details,id',
            'status' => 'required|in:0,1',
        ]);
        OtpServer::create($request->only('server_name', 'server_code', 'provider_server_id', 'api_id', 'status'));
        return redirect()->back()->with('success', 'Server added successfully');
    }

    public function update(Request $request, $id)
    {
        $server = OtpServer::findOrFail($id);
        $request->validate([
            'server_name' => 'required|string|max:255',
            'server_code' => 'required|string|max:50',
            'provider_server_id' => 'required|string|max:100',
            'api_id' => 'required|exists:api_details,id',
            'status' => 'required|in:0,1',
        ]);
        $server->update($request->only('server_name', 'server_code', 'provider_server_id', 'api_id', 'status'));
        return redirect()->back()->with('success', 'Server updated successfully');
    }

    public function destroy($id)
    {
        OtpServer::findOrFail($id)->delete();
        return redirect()->back()->with('success', 'Server deleted successfully');
    }
}