<?php namespace App\Http\Controllers\Frontend;

use App\Exceptions\ResourseNotFoundException;
use App\Http\Controllers\Controller;
use Facades\ModalHelpers\GeofenceModalHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Tobuli\Exceptions\ValidationException;
use Tobuli\Importers\Geofence\GeofenceImportManager;

class GeofencesController extends Controller
{
    public function index()
    {
        $data = GeofenceModalHelper::get();

        return !$this->api ? view('front::Geofences.index')->with($data) : ['items' => $data];
    }

    public function create()
    {
        if (!$this->user->perm('geofences', 'edit'))
            return ['status' => 0, 'perm' => 0];

        return ['status' => 1];
    }

    public function store()
    {
        return GeofenceModalHelper::create();
    }

    public function update()
    {
        return GeofenceModalHelper::edit();
    }

    public function changeActive()
    {
        return GeofenceModalHelper::changeActive();
    }

    public function destroy()
    {
        return GeofenceModalHelper::destroy();
    }

    public function importModal()
    {
        return view('front::Geofences.import');
    }

    public function import(GeofenceImportManager $importManager)
    {
        $this->checkException('geofences', 'store');

        $file = request()->file('file');

        if (is_null($file))
            throw new ResourseNotFoundException(trans('validation.attributes.file'));

        try {
            if ( ! $file->isValid())
                throw new \Exception(trans('front.unsupported_format'));

            $importManager->import($file);

            return Response::json(['status' => 1]);
        } catch (ValidationException $e) {
            return Response::json(['errors' => $e->getErrors()]);
        }
    }

    public function export()
    {
        $data = GeofenceModalHelper::exportData();

        return !$this->api ? view('front::Geofences.export')->with($data) : $data;
    }

    public function exportCreate()
    {
        $data = GeofenceModalHelper::export();

        header('Content-disposition: attachment; filename=geofences_export.gexp');
        header('Content-type: text/plain');

        echo json_encode($data);
    }

    public function exportType()
    {
        return GeofenceModalHelper::exportType();
    }

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

        if ($validator->fails())
            return response()->json(['status' => 0, 'errors' => $validator->errors()]);

        if (is_null($geofences = $this->user->geofences))
            throw new ResourseNotFoundException(trans('front.geofences'));

        return response()->json([
            'status' => 1,
            'zones'  => getPointZones($geofences, $request->lat, $request->lng)
        ]);
    }
}
