<?php
namespace App\Services\Auth\User;
use App\Models\Visitor;
use App\Models\Country;

use App\Services\Currency\CurrencyService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class AccountService
{
    public function getAccount()
    {
        if(Auth::user())
        {
            $user = Auth::user();
            $status = 'user';
        }
        else
        {
            $token = Session::get('token');
            $user = Visitor::where('token',$token)->first();
            $status = 'visitor';
        }
        return [
            'status'=>$status,
            'user'=>$user
        ];
    }
    public function setAccount()
    {
        $user = $this->getAccount();

        if(!$user['user'])
        {
            $token = bcrypt(rand(11111,99999).time());
            Session::put('token', $token);
            $request = Request();
            $currentIp = $request->ip(); 
            $country = (new CurrencyService())->getCurrentCountryFromIp($currentIp);
            $id = Country::where('iso',$country['countryCode'])->first()->id ?? 1 ;
            $user = Visitor::create([
                'token' => $token,
                'currency_id' => $id
            ]);

            $user = [
                'status'=>'visitor',
                'user'=>$user
            ];
        }
        return $user;
    }
}
