<?php

namespace App\Modules\Chat\controllers\api\v1;

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use Files;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\App;
use App\Modules\Bookings\Comment;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class MessagesControllerREST extends BaseController
{
    public function index(Request $request)
    {
        $query = Message::query()->orderBy('id', 'desc')->with('from');

        if ($request->input('chat_user')) {
            $query->chatUser($request->input('chat_user'));
        }

        if ($request->input('channel')) {
            $query->where('thread_id', $request->input('channel'));
        }

        // Paginate the results
        $query = $query->paginate($request->input('limit', 20));

        // Grab file attachments
        $results = $query->getCollection()->toArray();
        $files = \Files::query()->where('related_type', '=', 'chat')->where('related_id', '=', $request->input('channel', Message::getThreadId($request->input('chat_user'))))->with('creator')->get()->toArray();

        // Mark notifications as read
        if ($request->input('channel') && strpos($request->input('channel'), '-') === false) {
            $channel = Channel::findOrFail($request->input('channel'));
            $channel->users()->updateExistingPivot(getAuthUserId(), ['notifications' => 0], false);
        }

        // Prepare the response
        $response = [
            'data'         => array_merge($results, $files),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
            'per_page'     => $query->perPage(),
            'from'         => $query->firstItem(),
            'to'           => $query->lastItem(),
            'thread_id'    => Message::getThreadId($request->input('chat_user')),
        ];

        // Return the response
        return $response;
    }

    public function store(Request $request)
    {
        $message = Message::create($request->only('to', 'message', 'channel'));

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

        // Increment the notification on the channel
        if ($request->input('channel')) {
            DB::table('chat_channel_users')->where('channel_id', '=', $request->input('channel'))->where('user_id', '!=', getAuthUserId())->increment('notifications');
        }

        // Save the message as a comment for that particular job
        if ($request->input('save_comment')) {
            $channel = Channel::findOrFail($message->thread_id);
            if ($channel->related_id && $channel->related_type) {
                Comment::create([
                    'related_id'   => $channel->related_id,
                    'related_type' => $channel->related_type,
                    'message'      => $message->message,
                ]);
            }
        }

        // Send text message
        if ($request->input('send_text') == 'true') {
            $user = User::findOrFail($request->input('to'));
            if ($user->mobile && substr($user->mobile, 0, 2) == '07') {
                $agi = App::make('GSM_AGI');

                // Format inputs
                $text_message = $request->input('message').' - via Chat';
                $gateway = rand(1, 2);

                $agi->Command('gsm send sms '.$gateway.' '.$user->mobile.' "'.$text_message.'" 30 '.rand(1000, 9999));
            }
        }

        // Send email
        if ($request->input('send_email') == 'true') {
            $user = User::findOrFail($request->input('to'));

            // Variables
            $from = $message->from;
            $conversation = Message::query()->where('thread_id', $message->thread_id)->orderBy('id', 'desc')->take(10)->with('from')->get();

            if ($user->email) {
                Mail::send('emails.chat.notification', ['conversation' => $conversation, 'from' => $from], function ($message) use ($user, $from) {
                    $message->to($user->email)->subject(trim($from->name).' sent you a message via chat');
                });
            }
        }

        return $message->load('from');
    }
}
