<?php

namespace App\Http\Middleware;

use Closure;
use Galahad\TimezoneMapper\Facades\TimezoneMapper;
use Stevebauman\Location\Facades\Location;

class StoreGeoSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $needs_update = false;

        $ip = get_current_ip();
        $encoded_ip = base64_encode($ip);

        if (! $request->session()->has('geokey')) {
            if ($request->session()->get('geokey') != $encoded_ip) {
                $request->session()->put('geokey', $encoded_ip);
                $needs_update = true;
            }
        } else {
            $request->session()->put('geokey', $encoded_ip);
            $needs_update = true;
        }

        if (! $request->session()->has('timezone')) {
            $needs_update = true;
        }

        if ($needs_update) {

            if ($payload = Location::get($ip)) {
                $request->session()->put('geodata', base64_encode(json_encode($payload)));
                $isocode = $payload->isoCode;
            } else {
                $isocode = '*';
            }

            $request->session()->put('country', $isocode);

            if (isset($payload->latitude) && isset($payload->longitude)) {
                $request->session()->put('timezone', TimezoneMapper::mapCoordinates($payload->latitude, $payload->longitude));
            }
        }

        return $next($request);
    }
}
