<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminSession;
use App\Models\User;
use Illuminate\Http\Request;

class SessionController extends Controller
{
    /**
     * Display a listing of admin sessions
     */
    public function index(Request $request)
    {
        $query = AdminSession::with('user');

        // Filter by admin user
        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        // Filter by status
        if ($request->filled('status')) {
            if ($request->status === 'active') {
                $query->where('is_active', true)->whereNull('logout_at');
            } elseif ($request->status === 'inactive') {
                $query->where(function ($q) {
                    $q->where('is_active', false)->orWhereNotNull('logout_at');
                });
            }
        }

        // Search by IP or email
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('ip_address', 'like', "%{$search}%")
                ->orWhereHas('user', function ($q) use ($search) {
                    $q->where('email', 'like', "%{$search}%")
                      ->orWhere('first_name', 'like', "%{$search}%")
                      ->orWhere('last_name', 'like', "%{$search}%");
                });
        }

        $sessions = $query->latest('login_at')->paginate(50);

        // Calculate statistics
        $stats = [
            'total_active' => AdminSession::where('is_active', true)->whereNull('logout_at')->count(),
            'today_logins' => AdminSession::whereDate('login_at', today())->count(),
            'this_week_logins' => AdminSession::where('login_at', '>=', now()->subDays(7))->count(),
            'concurrent_sessions' => AdminSession::where('is_active', true)->whereNull('logout_at')->count(),
        ];

        // Get admin users for filter dropdown
        $admins = User::whereHas('roles', function ($q) {
            $q->whereIn('name', ['admin', 'super_admin']);
        })->select('id', 'first_name', 'last_name', 'email')->get();

        return view('admin.sessions.index', compact('sessions', 'stats', 'admins'));
    }

    /**
     * Display the specified session
     */
    public function show(AdminSession $session)
    {
        $session->load('user');

        return view('admin.sessions.show', compact('session'));
    }

    /**
     * Terminate a specific session
     */
    public function terminate(AdminSession $session)
    {
        $session->update([
            'logout_at' => now(),
            'is_active' => false,
        ]);

        return redirect()->route('admin.sessions.index')
            ->with('success', 'Session terminated successfully.');
    }

    /**
     * Terminate all active sessions except current
     */
    public function terminateAll()
    {
        AdminSession::where('user_id', auth()->id())
            ->where('id', '!=', session('admin_session_id'))
            ->where('is_active', true)
            ->whereNull('logout_at')
            ->update([
                'logout_at' => now(),
                'is_active' => false,
            ]);

        return redirect()->route('admin.sessions.index')
            ->with('success', 'All other sessions terminated successfully.');
    }
}

