<?php

namespace App\Http\Controllers;

use App\Events\ImpersonationStatusChanged;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class ImpersonateController extends Controller
{
    /**
     * START IMPERSONATE
     */
    public function start(User $user)
    {
        $authUser = Auth::user();

        /**
         * =====================================================
         * CEGAH IMPERSONATE DIRI SENDIRI
         * =====================================================
         */
        abort_if(
            $authUser->id === $user->id,
            403,
            __('You cannot impersonate yourself.')
        );

        /**
         * =====================================================
         * CEGAH IMPERSONATE SUPER ADMIN
         * =====================================================
         */
        abort_if(
            $user->hasRole('Developer', 'web'),
            403,
            __('You cannot impersonate a Super Admin.')
        );

        /**
         * =====================================================
         * CEK STATUS USER
         * =====================================================
         */
        abort_if(
            ! $user->is_active,
            403,
            __('User is inactive.')
        );

        /**
         * =====================================================
         * CEGAH LOOP IMPERSONATE
         * =====================================================
         */
        if (session()->has('impersonator_id')) {
            return redirect()->back()
                ->with('error', __('You are already impersonating another user.'));
        }

        /**
         * =====================================================
         * SIMPAN SUPER ADMIN ID
         * =====================================================
         */
        session([
            'impersonator_id' => $authUser->id,
        ]);

        /**
         * =====================================================
         * LOGIN SEBAGAI USER TARGET
         * =====================================================
         */
        Auth::loginUsingId($user->id);
        session()->regenerate();

        // Mark user as being impersonated in cache for target user awareness
        Cache::put("is_being_impersonated:{$user->id}", Auth::id(), now()->addHours(2));

        // 📡 Broadcast live alert to target user
        event(new ImpersonationStatusChanged($user->id, true));

        return redirect()->route('dashboard')
            ->with('success', __('You are now impersonating this user.'));
    }

    /**
     * STOP IMPERSONATE
     */
    public function stop()
    {
        abort_if(
            ! session()->has('impersonator_id'),
            403,
            __('No impersonation session found.')
        );

        $targetUserId = Auth::id();
        $superAdminId = session()->pull('impersonator_id');
        $superAdmin = User::findOrFail($superAdminId);

        Auth::login($superAdmin);
        session()->regenerate();

        // Clear awareness flag for target user
        Cache::forget("is_being_impersonated:{$targetUserId}");

        // 📡 Broadcast live alert (Remove) to target user
        event(new ImpersonationStatusChanged($targetUserId, false));

        // Sync last_session_id to prevent single session logout
        $superAdmin->update(['last_session_id' => session()->getId()]);

        return redirect()->route('users')
            ->with('success', __('Returned to Super Admin account.'));
    }
}
