<?php

namespace App\Http\Livewire\Admin;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class MaintenanceMode extends Component
{
    public $maintenanceMode = false;
    public $showModal = false;

    public function mount()
    {
        // Check if the active profile is Admin
        if (getActiveProfileType() !== 'Admin') {
            abort(403, 'Only administrators can access this feature.');
        }

        // Load current maintenance mode status
        $this->maintenanceMode = $this->getMaintenanceMode();
    }

    public function openModal()
    {
        $this->showModal = true;
    }

    public function closeModal()
    {
        $this->showModal = false;
    }

    public function toggleMaintenanceMode()
    {
        // Verify admin profile again before toggling
        if (getActiveProfileType() !== 'Admin') {
            $this->dispatch('notify', [
                'type' => 'error',
                'message' => 'You must be logged in as an administrator to toggle maintenance mode.'
            ]);
            return;
        }

        // Toggle the value
        $this->maintenanceMode = !$this->maintenanceMode;

        // If enabling maintenance mode, log out all non-admin users
        if ($this->maintenanceMode) {
            $this->logoutNonAdminUsers();
        }

        // Update in database
        DB::table('system_settings')
            ->where('key', 'maintenance_mode')
            ->update([
                'value' => $this->maintenanceMode ? 'true' : 'false',
                'updated_at' => now(),
            ]);

        // Clear cache
        Cache::forget('system_setting_maintenance_mode');

        // Close modal
        $this->showModal = false;

        // Dispatch event to refresh the maintenance banner
        $this->dispatch('maintenance-mode-changed');

        // Notify user
        $message = $this->maintenanceMode
            ? 'Maintenance mode has been enabled. Only users with admin relationships can now log in.'
            : 'Maintenance mode has been disabled. All users can now log in.';

        $this->dispatch('notify', [
            'type' => 'success',
            'message' => $message
        ]);
    }

    /**
     * Log out all users who don't have admin relationships
     */
    protected function logoutNonAdminUsers()
    {
        // Get the current authenticated user ID to exclude from logout
        $currentUserId = auth()->id();

        // Get all users without admin relationships, excluding current user
        $usersToLogout = \App\Models\User::whereDoesntHave('admins')
            ->where('id', '!=', $currentUserId)
            ->get();

        $logoutCount = 0;

        // First, broadcast logout events to all users
        // This gives browsers a chance to receive the WebSocket message before sessions are deleted
        foreach ($usersToLogout as $user) {
            // Determine the guard for this user
            $guard = 'web'; // Default guard

            // Broadcast forced logout event via WebSocket
            broadcast(new \App\Events\UserForcedLogout($user->id, $guard));

            $logoutCount++;
        }

        // Wait briefly for WebSocket messages to be delivered
        // This helps ensure browsers receive the logout event before sessions are deleted
        sleep(2);

        // Now delete sessions and clear caches
        foreach ($usersToLogout as $user) {
            $guard = 'web';

            // Delete all sessions for this user from database
            \DB::connection(config('session.connection'))
                ->table(config('session.table', 'sessions'))
                ->where('user_id', $user->id)
                ->delete();

            // Clear cached authentication data
            Cache::forget('auth_' . $guard . '_' . $user->id);

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

        // Clear online users cache to force refresh
        Cache::forget("online_users_web_" . \App\Services\PresenceService::ONLINE_THRESHOLD_MINUTES);

        // Log the action for debugging
        info("Maintenance mode enabled: Logged out {$logoutCount} non-admin users. Current admin user ID {$currentUserId} was preserved.");
    }

    protected function getMaintenanceMode()
    {
        return isMaintenanceMode();
    }

    public function render()
    {
        return view('livewire.admin.maintenance-mode');
    }
}
