<?php

namespace App\Modules\Bookings;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Response;
use Exception;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

class TaskFeedbackControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $query = TaskFeedback::select('*');

        if ($request->input('completed')) {
            $query->whereNotNull('rating');
        }

        if ($request->input('reverse') == 'true') {
            $query->orderBy('created_at', 'desc');
        }

        if ($request->input('user') == 'true') {
            $query->with('user');
        }

        if ($request->input('user_id')) {
            $query->where('user_id', $request->input('user_id'));
        }

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

        foreach ($query as $item) {
            $item->client = $item->task->client;
        }

        $response = [
            'success'      => true,
            '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 Response::json($response);
    }

    public function show($code)
    {
        $feedback = TaskFeedback::findOrFail($code);

        return $feedback->load('user', 'task');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update(Request $request, $code)
    {
        $feedback = TaskFeedback::findOrFail($code);

        $feedback->fill($request->all());

        if ($feedback->save()) {
          Event::dispatch('FeedbackReceived', $feedback);
          return $feedback;
        } else {
            return Response::json(['errors' => $feedback->errors->all()], 400);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $feedback = TaskFeedback::findOrFail($id);

        if (! $feedback->delete()) {
            throw new Exception('Unable to delete the feedback request.');
        }

        return $feedback;
    }
}
