<?php

namespace App\Http\Controllers;

use App\Models\NetworkSession;
use Illuminate\Http\Request;

class LiveSessionController extends Controller
{
    public function index(Request $request)
    {
        $query = NetworkSession::with(['subscriber', 'router']);

        if ($request->filled('type') && $request->type !== 'All') {
            $query->where('type', $request->type);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('username', 'like', "%{$search}%")
                  ->orWhere('ip_address', 'like', "%{$search}%")
                  ->orWhere('mac_address', 'like', "%{$search}%");
            });
        }

        $sessions = $query->orderBy('started_at', 'desc')->paginate(15);
        $totalSessionsCount = NetworkSession::count();
        $pppoeSessionsCount = NetworkSession::where('type', 'PPPoE')->count();
        $hotspotSessionsCount = NetworkSession::where('type', 'Hotspot')->count();

        return view('admin.network.sessions', compact('sessions', 'totalSessionsCount', 'pppoeSessionsCount', 'hotspotSessionsCount'));
    }

    public function disconnect(NetworkSession $session)
    {
        $session->delete();
        return redirect()->route('admin.network.sessions')->with('success', "Active RADIUS session for {$session->username} disconnected.");
    }
}
