<?php

namespace App\Http\Controllers\Franchise;

use App\Http\Controllers\Controller;
use App\Models\IpLog;
use App\Models\UserDevice;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;

class SecurityController extends Controller
{
    public function index(): View
    {
        $userId = (int) auth()->id();

        $devices = UserDevice::query()
            ->where('user_id', $userId)
            ->orderByDesc('last_seen_at')
            ->paginate(10, ['*'], 'devices');

        $ipLogs = IpLog::query()
            ->where('user_id', $userId)
            ->latest('created_at')
            ->paginate(20, ['*'], 'logs');

        return view('franchise.security', compact('devices', 'ipLogs'));
    }

    public function terminateDevice(UserDevice $device): RedirectResponse
    {
        if ($device->user_id !== auth()->id()) {
            abort(403);
        }

        $device->is_active = false;
        $device->save();

        return back()->with('status', 'Device session terminated.');
    }
}

