<?php

namespace App\Http\Controllers;

use App\Services\PresenceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class CustomLogoutController extends Controller
{
    public function destroy(Request $request)
    {
        $presenceService = app(PresenceService::class);

        // Log out from all guards and set them offline
        foreach (['web', 'admin', 'bank', 'organization'] as $guard) {
            if (Auth::guard($guard)->check()) {
                $user = Auth::guard($guard)->user();

                // Set user offline before logging out
                $presenceService->setUserOffline($user, $guard);

                // Clear presence caches
                Cache::forget("presence_{$guard}_{$user->id}");
                Cache::forget("presence_last_update_{$guard}_{$user->id}");

                // Logout
                Auth::guard($guard)->logout();
            }
        }

        $request->session()->invalidate();
        $request->session()->regenerateToken();
        
        // For AJAX/Livewire requests, force a hard redirect
        if ($request->expectsJson() || $request->hasHeader('X-Livewire')) {
            $redirectUrl = LaravelLocalization::localizeUrl('/');
            return response('<script>window.location.href = "' . $redirectUrl . '";</script>', 200)
                ->header('Content-Type', 'text/html');
        }
        
        // Force a full page redirect with no-cache headers
        $response = redirect(LaravelLocalization::localizeUrl('/'));
        $response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
        $response->headers->set('Pragma', 'no-cache');
        $response->headers->set('Expires', '0');
        
        return $response;
    }
}