<?php

namespace App\Modules\Bookings;

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

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

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

        foreach ($query as $value) {
            // Load all the clients
            // unfortuately eager loading is not available
            // for polymorphic relationships at the moment..
            if ($request->input('client') && $request->input('client') != 'false') {
                $value->client;
            }

            if ($request->input('total_items')) {
                $value->total_items = RmaItem::where('task_id', '=', $value->id)->count();
            }

            // Load all the comment stats
            $value->comments_count = [
                'total'   => $value->comments()->count(),
                'unread'  => $value->comments()->unread()->count(),
            ];
        }

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

        return Response::json($response, ($response['success']) ? 200 : 400);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request, $task_id)
    {
        $data = [
            'task_id'  => $task_id,
            'stock_id' => $request->input('stock_id'),
            'quantity' => $request->input('quantity'),
        ];

        $status = Status::rma()->first();
        if ($status) {
            $data['status_id'] = $status->id;
        }

        $rma_item = RmaItem::create($data);

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

        $rma_item->load('stock');

        return Response::json($rma_item->toArray());
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function show($task_id, $id)
    {
        $rma = RmaItem::find($id);

        $this->validateTask($rma, $task_id);

        $rma->load('stock');

        $rma->statuses = Status::rma()->get();

        if (! $rma) {
            return Response::json(['error' => 'Rma item not found.'], 404);
        }

        return Response::json($rma->toArray());
    }

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

        $this->validateTask($rma, $task_id);

        $rma->fill($request->except('id'));

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return Response
     */
    public function destroy($task_id, $id)
    {
        $rma = RmaItem::find($id);

        $this->validateTask($rma, $task_id);

        // Access validations
        // should be implemented here...

        if (! $rma) {
            return Response::json(['error' => 'Rma item not found.'], 404);
        }

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

    protected function validateTask($rma, $task_id)
    {
        if ($rma->task_id != $task_id) {
            return Response::json(['error' => 'Rma item not found.'], 400);
        }
    }
}
