<?php

namespace App\Modules\Bookings;

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

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

        if ($request->input('query')) {
            $query->where('description', 'like', '%'.$request->input('query').'%');
        }

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

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
        ];

        return Response::json($response);
    }

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

        if (! $item->id) {
            return Response::json(['errors' => $item->errors->all()], 400);
        }

        return $item;
    }

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

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

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

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

        DB::transaction(function () use (&$item) {
            DB::table('task_template_items')->where('template_item_id', $item->id)->delete();

            if (! $item->delete()) {
                throw new Exception('Unable to delete the template item');
            }

        });

        return $item;
    }
}
