<?php

namespace App\Http\Middleware;

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

class CheckProfileCompletion
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $user = Auth::user();

            $completionStatus = $user->getMeta('profile_completion_status');
            if ($completionStatus === 'complete' || $completionStatus === 'skipped') {
                return $next($request);
            }

            $requiredFields = collect([
                'avatar' => $user->avatar,
                'cover' => $user->cover,
                'name' => $user->name,
                'bio' => $user->bio,
                'address' => $user->address,
            ]);

            // Mark as complete if all fields are present
            if ($requiredFields->every(fn ($value) => !empty($value))) {
                $user->setMeta('profile_completion_status', 'complete');
                $user->setMeta('profile_completion_completed_at', now()->toDateTimeString());
                return $next($request);
            }

            if ($request->routeIs([
                'complete.profile',
                'profile.complete',
                'skip.profile.completion',
                'logout',
            ]) || $request->is('complete-profile*')) {
                return $next($request);
            }

            session(['intended_url' => $request->fullUrl()]);
            session(['url.intended' => $request->fullUrl()]);

            if ($request->expectsJson()) {
                return response()->json([
                    'message' => 'Please complete your profile before continuing.',
                    'redirect' => route('complete.profile'),
                ], 409);
            }

            return redirect()->route('complete.profile');
        }
        
        return $next($request);
    }
}
