<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class CheckPhoneVerification
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */

    public function handle(Request $request, Closure $next)
    {
        // Define the route names that should be accessible even if the user is not verified
    $accessibleRoutes = [
        'verify.form',
        'verify.verify',
        'resend-otp'
    ];

    if (Auth::check()) {
        $user = Auth::user()->fresh();

        Log::info('Middleware: User authenticated', ['user' => $user]);

        if (Auth::User()->isVerified == '0') {
            Log::info('Middleware: User not verified 0', ['user' => $user]);

            if (!in_array($request->route()->getName(), $accessibleRoutes)) {
                Log::info('Middleware: Redirecting to verify.form', ['user' => $user]);
                return redirect()->route('verify.form')->with(['phone' => $user->phone]);
            }
        } else {
            Log::info('Middleware: User verified 1', ['user' => $user]);
        }
    } else {
        Log::info('Middleware: User not authenticated');
    }

    return $next($request);
    }
}
