<?php

namespace Modules\Auth\Controllers;

use App\Controllers\BaseController;
use Modules\Auth\Models\LoginAttemptModel;
use Modules\Auth\Models\UserSessionModel;
use Modules\Auth\Services\AuthService;

class SessionController extends BaseController
{
    public function index()
    {
        $userId   = (int) $this->session->get('user_id');
        $sessions = new UserSessionModel();
        $attempts = new LoginAttemptModel();

        return view('Modules\Auth\Views\sessions', array_merge($this->baseViewData(), [
            'title'          => 'Active Sessions',
            'breadcrumbs'    => ['Dashboard' => base_url('dashboard'), 'Active Sessions'],
            'activeSessions' => $sessions->activeForUser($userId),
            'loginHistory'   => $attempts->historyForUser($userId, 25),
            'currentToken'   => $this->session->get('session_token'),
        ]));
    }

    public function revokeOthers()
    {
        $userId = (int) $this->session->get('user_id');
        $token  = (string) $this->session->get('session_token');

        (new AuthService())->forceLogoutOtherDevices($userId, $token);

        return redirect()->to('/account/sessions')->with('success', 'All other devices have been signed out.');
    }
}
