<?php
namespace Modules\User\Services;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Modules\City\Services\CityService;
use Modules\Type\Services\TypeService;
use Modules\User\Enums\AccountStatusEnum;
use Modules\User\Models\Visitor;

class AccountService
{
    public function __construct(
        private AddressService $addressService,
        private TypeService $typeService,
    ){}

    public function getAccount()
    {

        if(Auth::user())
        {
            $user = Auth::user();
            $status = AccountStatusEnum::USER->value;
        }
        else
        {
            $status = AccountStatusEnum::VISITOR->value;
            $token = Session::get('token');
            if(!$token)
            {
                $token = request()->header('tokenDevice');
            }
            if($token)
            {
                $user = Visitor::with(['type','address'])->where('token',$token)->first();
                if($user)
                {
                    return [
                        'status'=>$status,
                        'user'=>$user
                    ];
                }
            }
            $user = $this->setAccount();
        }
        return [
            'status'=>$status,
            'user'=>$user
        ];
    }
    public function setAccount()
    {
        $token = request()->header('tokenDevice');
        if (!$token)
        {
            $token = bcrypt(rand(11111,99999).time());
            Session::put('token', $token);
        }
        $type = $this->typeService->defaultType();
        $user = Visitor::create([
            'token' => $token,
            'type_id'=>$type->id
        ]);
        $address = $this->addressService->createDefault($user->id,AccountStatusEnum::VISITOR->value);
        $user->update([
            'address_id'=>$address->id
        ]);

        return $user;
    }

    public function update(array $request,$user)
    {
        $user->update($request);
        $user = Visitor::with(['type','address'])->find($user->id);
        return $user;
    }
}
