<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Lokasi;
use App\User;

class LokasiController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $lokasi = Lokasi::all();
        $users = [];
        foreach($lokasi as $l)
        {
            $users[] = User::find($l->user_id);
        }
        
        //$data = [$lokasi, $users];
        
        return response()->json([
           'users' => $users,
           'lokasi' => $lokasi
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $isUserId = Lokasi::where('user_id', $request->user_id)->get();
        
        if(count($isUserId)>0)
        {
            $lokasi = Lokasi::where('user_id', $request->user_id)->first();
            $lokasi->latitude = $request->latitude;
            $lokasi->longitude = $request->longitude;
            $lokasi->update();
            return response()->json([
                'lokasi' => $lokasi,
            ]);
        }
        else{
            $lokasi = new Lokasi();
            $lokasi->latitude = $request->latitude;
            $lokasi->user_id = $request->user_id;
            $lokasi->longitude = $request->longitude;
            $lokasi->save();
            return response()->json([
                'lokasi' => $lokasi,
            ]);
        }
        
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
