<?php

namespace App\Http\Controllers\API\v1\Voter;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util;
use Illuminate\Http\Request;

class LogoutController extends Controller
{
    public function __invoke(Request $request)
    {
        $user = $request->user();

        if ($user) {
            activity()
                ->performedOn($user)
                ->withProperties([
                    'election_id' => Util::getCurrentElection(),
                    'voter_id' => $user->id,
                    'voter_name' => $user->name,
                    'no_kp' => $user->no_kp,
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log("voter logout: {$user->name}");

            // Revoke current access token if using Passport.
            try {
                if (method_exists($user, 'token') && $user->token()) {
                    $user->token()->revoke();
                }
            } catch (\Throwable $e) {
                // Logging should not block logout.
            }
        } else {
            activity()
                ->withProperties([
                    'ip' => $request->ip(),
                    'user_agent' => $request->userAgent(),
                ])
                ->log('voter logout');
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Logout successfully',
        ]);
    }
}

