<?php
/**
 * Created by PhpStorm.
 * User: antanas
 * Date: 18.3.12
 * Time: 17.44
 */

namespace App\Http\Controllers\Frontend;


use App\Http\Controllers\Controller;
use Validator;
use Tobuli\Exceptions\ValidationException;

class AddressController extends Controller
{
    public function autocomplete()
    {
        try {
            $locations = \Facades\GeoLocation::listByAddress(request()->input('q'));
        } catch (\Exception $e) {
            $locations = [];
        }

        return response()->json(
            array_map(function($location){ return $location->toArray();}, $locations)
        );
    }

    public function map()
    {
        $data = request()->all();
        $validator = Validator::make($data, [
            'lat' => 'lat',
            'lng' => 'lng',
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator->errors());
        }

        $lat = $data['lat'];
        $lng = $data['lng'];

        $data['coords'] = $lat && $lng ? '['.$lat.', '.$lng.']' : null;

        return view('front::Addresses.index')->with($data);
    }

    public function reverse()
    {
        $result = ['status' => 1];

        $data = request()->all();
        $validator = Validator::make($data, [
            'lat' => 'lat',
            'lng' => 'lng',
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator->errors());
        }

        try {
            $result['data'] = \Facades\GeoLocation::byCoordinates($data['lat'], $data['lng'])->toArray();
        } catch(\Exception $e) {
            $result = [
                'status' => 0,
                'error' => $e->getMessage(),
            ];
        }

        return $result;
    }
}
