<?php

namespace App\Modules\Bookings;

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

class RmaControllerRESTv1 extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $query = Rma::select('tasks.*')->rma()->with('status');

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

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

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

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

        if ($request->input('results')) {
            switch ($request->input('results')) {
                case 'managers':
                    $query->where('completed', '=', 0)->with('user', 'status');
                    break;
                case 'own':
                    $query = $query->where('assigned_to', '=', $request->input('user_id', Auth::user()->id))->open()->orderBy('id', 'desc'); break;
                case 'unassigned':
                    $query = $query->open();
            }
        }

        // Sort results based on priority
        $query->join('severities', 'severities.id', '=', 'tasks.severity_id', 'left')
              ->orderBy('severities.priority', 'desc');

        // 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)
    {
        // Assign a default status
        $status = Status::rma()->first();

        if (! $status) {
            return response()->json(['success' => false, 'errors' => ['No statuses defined']], 400);
        }

        $data = $request->only('client_id', 'client_type', 'problem');
        $data['status_id'] = $status->id;

        $rma = Rma::create($data);

        if (! $rma->id) {
            $response = [
                'success' => false,
                'errors'  => $rma->errors->all(),
            ];
        } else {
            DB::transaction(function () use ($rma, $request) {
                // Store All the items
                foreach ($request->input('items') as $item) {
                    $data = [
                        'task_id'  => $rma->id,
                        'stock_id' => $item['id'],
                        'quantity' => $item['quantity'],
                    ];

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

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

            $response = [
                'success' => true,
                'data'    => $rma->toArray(),
            ];
        }

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

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

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

        $rma->load('user', 'client', 'items', 'items.stock');

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

        if ($rma->client_type == 'client') {
            $rma->load('client.sites', 'client.sites.users', 'site', 'site_user');
        }

        return response()->json($rma->toArray());
    }

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

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

        if ($rma->save()) {
            if ($rma->client_type == 'client') {
                $rma->load('client.sites', 'client.sites.users', 'site', 'site_user');
            }

            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($id)
    {
        $rma = Rma::find($id);

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

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

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