<?php

namespace Ignite\Core\Listeners;

use Carbon\Carbon;
use Ignite\Core\Entities\Login;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
use Jenssegers\Agent\Agent;

class StoreLogin
{
    /**
     * @var Agent
     */
    private $agent;

    /**
     * @var Request
     */
    private $request;

    /**
     * @var Store
     */
    private $session;

    /**
     * StoreLogin constructor.
     *
     * @param Request $request
     * @param Store $session
     * @param Agent $agent
     */
    public function __construct(Request $request, Store $session, Agent $agent)
    {
        $this->agent = $agent;
        $this->request = $request;
        $this->session = $session;
    }

    /**
     * Handle user login events.
     *
     * @param  \Illuminate\Auth\Events\Login $event
     */
    public function handle($event)
    {
        $event->user->forceFill(['last_login_at' => now()])->save();

        Login::create([
            'user_id' => $event->user->getKey(),
            'session_id' => $this->session->getId(),
            'ip_address' => $this->request->ip(),
            'browser_name' => $browser = $this->agent->browser(),
            'browser_version' => $this->agent->version($browser),
            'platform_name' => $platform = $this->agent->platform(),
            'platform_version' => $this->agent->version($platform),
            'device' => $this->agent->device(),
            'created_at' => Carbon::now(),
        ]);
    }
}
