<?php

namespace App\Modules\Bookings;

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

class TemplatesControllerRESTv1 extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $query = Template::select('*')->with('items')->with('taskTypes');

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

        if (request()->get('task_type')) {
            $query->whereHas('taskTypes', function ($q) {
                $q->where('name', '=', request()->get('task_type'));
            });
        }

        if (request()->get('order_by')) {
            $query->orderBy(request()->get('order_by'));
        }

        // Apply limits and execute the query
        $query = $query->paginate(request()->get('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()
    {
        $template = Template::create(request()->all());

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

        //Link template and task_types
        if (request()->has('task_types')) {
            $task_types = Arr::pluck(request()->get('task_types', []), 'id');
            $template->taskTypes()->sync($task_types);
        }

        $template->load('items', 'taskTypes');

        return $template;
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function update($id)
    {
        $template = Template::findOrFail($id);

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

        if ($template->save()) {
            //Delete all the taskTypes
            $template->taskTypes()->detach();

            //Link template and taskTypes
            if (request()->has('task_types')) {
                $task_types = Arr::pluck(request()->get('task_types', []), 'id');
                $template->taskTypes()->sync($task_types);
            }

            $template->load('items', 'taskTypes');

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

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

        DB::transaction(function () use (&$template) {
            $template->items()->delete();
            DB::table('task_templates')->where('template_id', $template->id)->delete();
            DB::table('task_template_items')->where('template_id', $template->id)->delete();

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

        });

        return $template;
    }
}
