<?php

namespace App\Http\Controllers;

use App\Model\User;
use Carbon\Carbon;
use App\Model\Message;
use App\Model\Participant;
use App\Model\Thread;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Eloquent\QUERY;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use App\Events\MessageSent;

class MessagesController extends Controller
{
    /**
     * Show all of the message threads to the user.
     *
     * @return mixed
     */
    public function index()
    {
        // All threads, ignore deleted/archived participants
        // $threads = Thread::getAllLatest()->get();
        // All threads that user is participating in
        $threads = Thread::forUser(Auth::id())->latest('updated_at')->get();
        // All threads that user is participating in, with new messages
        //$threads = Thread::forUserWithNewMessages(Auth::id())->latest('updated_at')->get();
        return view('messenger.index', compact('threads'));
    }
    /**
     * Shows a message thread.
     *
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        try {
            $thread = Thread::findOrFail($id);
            $users = $thread->participantsUserIds();
            $userId = Auth::user()->id;
            if(!in_array($userId,$users)){
                alert()->error('Usted no pertenece a esta conversación.')->persistent('Cerrar');
                return redirect('messages');
            }
        } catch (ModelNotFoundException $e) {
            alert()->error('Esta conversación no existe')->persistent('Cerrar');
            return redirect('messages');
        }
        // show current user in list if not a current participant
        // $users = User::whereNotIn('id', $thread->participantsUserIds())->get();
        // don't show the current user in list

        $users = User::whereNotIn('id', $thread->participantsUserIds($userId))->get();
        $thread->markAsRead($userId);
        return view('messenger.show', compact('thread', 'users'));
    }
    /**
     * Creates a new message thread.
     *
     * @return mixed
     */
    public function create()
    {
        $users = User::select('usuario.nombres','usuario.id')->where('id','!=',Auth::id())->get();
        return view('messenger.create', compact('users'));
    }
    /**
     * Stores a new message thread.
     *
     * @return mixed
     */
    public function store()
    {
        $input = Input::all();
        $thread = Thread::create(
            [
                'subject' => $input['subject'],
            ]
        );
        // Message
        Message::create(
            [
                'thread_id' => $thread->id,
                'user_id'   => Auth::user()->id,
                'body'      => $input['message'],
            ]
        );
        // Sender
        Participant::create(
            [
                'thread_id' => $thread->id,
                'user_id'   => Auth::user()->id,
                'last_read' => new Carbon,
            ]
        );
        // Recipients
        if (Input::has('recipients')) {
            $thread->addParticipant($input['recipients']);
        }
        return redirect('messages');
    }
    /**
     * Adds a new message to a current thread.
     *
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        try {
            $thread = Thread::findOrFail($id);
        } catch (ModelNotFoundException $e) {
            return response()->json(['error' => 'Mensaje no enviado']);
        }
        try {
            $thread->activateAllParticipants();
            // Message
            $aux = Input::all();

            $message = Message::create(
                [
                    'thread_id' => $thread->id,
                    'user_id' => Auth::id(),
                    'body' => Input::get('message'),
                ]
            );

            $participants = $thread->participantsIds(Auth::id());
//            foreach($participants as $aux) {
//                broadcast(new MessageSent(Auth::user(),$message, $thread,$aux))->toOthers();
//            }
            // Add replier as a participant
            $participant = Participant::firstOrCreate(
                [
                    'thread_id' => $thread->id,
                    'user_id' => Auth::user()->id,
                ]
            );
            $participant->last_read = new Carbon;
            $participant->save();
            // Recipients
            if (Input::has('recipients')) {
                $thread->addParticipant(Input::get('recipients'));
            }
            return response()->json(['message' => Input::get('message'), 'user' => Auth::user()->nombres]);
        }catch(\Illuminate\Database\QueryException $e){
            return response()->json(['error' => 'Ha ocurrido un error'],'400');
        }
    }

    public function getLastMessages(){
        $threads = Thread::forUserWithNewMessages(Auth::id())->latest('updated_at')->get();
        $users = [];
        foreach($threads as $thread){
            $aux['user'] = $thread->participantsString(Auth::id());
            $aux['message'] = $thread->subject;
            $aux['created_at'] = $thread->latestMessage->created_at->format('d/m/Y');
            $aux['id'] = $thread->id;
            array_push($users,$aux);
        }
        return response()->json(['participants' => $users]);
    }
}
