<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class SessionController extends Controller
{
    /**
     * Display a listing of all user sessions.
     */
    public function index(Request $request): Response
    {
        $perPage = min($request->get('per_page', 15), 100);
        $sessionsPaginated = DB::table('sessions')
            ->join('users', 'sessions.user_id', '=', 'users.id')
            ->select(
                'sessions.id as session_id',
                'sessions.user_id',
                'sessions.ip_address',
                'sessions.user_agent',
                'sessions.last_activity',
                'users.name as user_name',
                'users.email as user_email',
                'users.role as user_role'
            )
            ->whereNotNull('sessions.user_id')
            ->orderBy('sessions.last_activity', 'desc')
            ->paginate($perPage)
            ->withQueryString();

        $sessions = $sessionsPaginated->getCollection()->map(function ($session) {
            return [
                'id' => $session->session_id,
                'user_id' => $session->user_id,
                'user_name' => $session->user_name,
                'user_email' => $session->user_email,
                'user_role' => $session->user_role,
                'ip_address' => $session->ip_address,
                'user_agent' => $this->parseUserAgent($session->user_agent),
                'last_activity' => date('Y-m-d H:i:s', $session->last_activity),
                'last_activity_timestamp' => $session->last_activity,
            ];
        });

        $paginationData = [
            'data' => $sessions->values()->all(),
            'current_page' => $sessionsPaginated->currentPage(),
            'last_page' => $sessionsPaginated->lastPage(),
            'per_page' => $sessionsPaginated->perPage(),
            'total' => $sessionsPaginated->total(),
            'links' => $sessionsPaginated->linkCollection()->toArray(),
        ];

        \Log::info('Sessions Pagination Data', $paginationData);

        return Inertia::render('Admin/Sessions/Index', [
            'sessions' => $sessions->values()->all(),
            'pagination' => $paginationData,
        ]);
    }

    /**
     * Destroy a specific session.
     */
    public function destroy(string $sessionId): RedirectResponse
    {
        DB::table('sessions')->where('id', $sessionId)->delete();

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

    /**
     * Destroy all sessions for a specific user.
     */
    public function destroyUserSessions(User $user): RedirectResponse
    {
        DB::table('sessions')->where('user_id', $user->id)->delete();

        // Juga revoke semua token jika ada
        $user->tokens()->delete();

        return redirect()->route('admin.sessions.index')->with('success', "Semua session untuk {$user->name} berhasil dihapus.");
    }

    /**
     * Parse user agent string to get browser and OS info.
     */
    protected function parseUserAgent(?string $userAgent): string
    {
        if (! $userAgent) {
            return 'Unknown';
        }

        // Simple parsing untuk browser
        if (str_contains($userAgent, 'Chrome')) {
            return 'Chrome';
        }
        if (str_contains($userAgent, 'Firefox')) {
            return 'Firefox';
        }
        if (str_contains($userAgent, 'Safari') && ! str_contains($userAgent, 'Chrome')) {
            return 'Safari';
        }
        if (str_contains($userAgent, 'Edge')) {
            return 'Edge';
        }
        if (str_contains($userAgent, 'Opera')) {
            return 'Opera';
        }

        // Return shortened version if too long
        if (strlen($userAgent) > 50) {
            return substr($userAgent, 0, 50).'...';
        }

        return $userAgent;
    }
}

