<?php

namespace App\Modules\Bookings;

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

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

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

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

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

        if ($request->input('results')) {
            switch ($request->input('results')) {
                case 'all':
                    $query = $query->where('assigned_to', '=', $request->input('user_id', Auth::user()->id)); break;
                case 'open':
                    $query = $query->where('assigned_to', '=', $request->input('user_id', Auth::user()->id))->where('closed', '=', 0);
                case 'own':
                    $query = $query->where('assigned_to', '=', $request->input('user_id', Auth::user()->id))->orderBy('closed', 'asc')->orderBy('id', 'desc');
            }
        }

        if ($request->input('summary')) {
            $query->orderBy('id', 'desc');
        }

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

        // Execute all actions that need to be done on individual messages
        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;
            }

            // 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(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
        ];

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

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $data = $request->only('client_id', 'client_type', 'site_user_id', 'assigned_to', 'message', 'contact_number');

        if ($request->input('direct_dial')) {
            $data['contact_number'] = $request->input('direct_dial');
        }

        $message = Message::create($data);

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

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

        // Mark the message as being read
        $message->status = 'read';
        $message->save();

        $message->load('user', 'client', 'creator');

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

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

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

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

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

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

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

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

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

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

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