<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;

class ProfileCompletionCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next)
    {
        // Check if the user is authenticated
        if (Auth::check()) {
            $user = Auth::user()->load('customer');

            // Check if the profile is complete
            $profileStatus = $this->isProfileComplete($user);

            if (!$profileStatus['is_completed']) {
                return response()->json([
                    'message' => 'Please Complete your profile to access the all features',
                    'incomplete_fields' => $profileStatus['incomplete_fields'],
                    //'fields' =>  $profileStatus['fields'],
                ], 403);
            }
        }

        return $next($request);
    }

    protected function isProfileComplete($user)
    {
        //return $user;
        $fieldsToCheck = ['name', 'email', 'phone', 'password'];
        $incompleteFields = [];

        foreach ($fieldsToCheck as $field) {
            if (empty($user->{$field})) {
                $incompleteFields[$field] = true;
            }
        }

        if (empty($user->customer) || empty($user->customer->company_name)) {
            $incompleteFields[] = 'company_name';
        }

        if(empty($user->customer) || empty($user->customer->country_id)) {
            $incompleteFields[] = 'country';
        }
        if(empty($user->customer) || empty($user->customer->state_id)) {
            $incompleteFields[] = 'state';
        }
        if(empty($user->customer) || empty($user->customer->city_id)) {
            $incompleteFields[] = 'city';
        }
        if(empty($user->customer) || empty($user->customer->address)) {
            $incompleteFields[] = 'address';
        }
        if(empty($user->customer) || empty($user->customer->pincode)) {
            $incompleteFields[] = 'pincode';
        }

        return [
            'is_completed' => empty($incompleteFields),
            'incomplete_fields' => $incompleteFields,
            //'fields' => $user
        ];
    }



}
