<?php

namespace App\Modules\Reminders;

use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class RemindersControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $query = Reminder::query()->where('user_id', $request->input('user_id', getAuthUserId()))->where(function ($q) {
                $q->future()->orWhere('completed', 0);
            });

        // Apply limits and execute the query
        $query = $query->paginate($request->input('limit', 20));

        // Prepare the response
        $response = [
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'per_page'     => $query->perPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];

        // Return the response
        return $response;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $reminder = Reminder::create($request->all());

        if (! $reminder->exists) {
            return response()->json(['errors' => $reminder->errors->all()], 400);
        }

        return $reminder;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function show($id)
    {
        return Reminder::findOrFail($id)->load('user');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update(Request $request, $id)
    {
        $reminder = Reminder::findOrFail($id);
        $reminder->fill($request->all());

        if (! $reminder->save()) {
            return response()->json(['errors' => $reminder->errors->all()], 400);
        }

        return $reminder;
    }

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