<?php

namespace App\Http\Controllers\Frontend\Messages;

use App\Http\Controllers\Controller;
use App\Models\Messages\ExtendedThread;
use App\Models\Auth\User;
use Carbon\Carbon;
use Cmgmyr\Messenger\Models\Message;
use Cmgmyr\Messenger\Models\Participant;
use Cmgmyr\Messenger\Models\Thread;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Session;
use App\Models\Messages\ExtendedMessage;

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 notifications that user is participating in
        $threads = ExtendedThread::notifications()->forUser(Auth::id())->get();//latest('updated_at')->get();
        dd($threads);
        // filter out the ones we sent
        // All threads that user is participating in, with new messages
        // $threads = Thread::forUserWithNewMessages(Auth::id())->latest('updated_at')->get();

        return view('frontend.messaging.index')
            ->with('threads', $threads);
    }

    public function notifications()
    {
        // All threads, ignore deleted/archived participants
        //$threads = Thread::getAllLatest()->get();
        // All notifications that user is participating in
        $threads = ExtendedThread::notifications()->forUser(Auth::id())->get();//latest('updated_at')->get();
        // dd($threads);
        // filter out the ones we sent
        // dd($threads[0]->extendedcreator());
        $mythreads = $threads->reject(function ($value, $key) {
            if ($value->hascreator()) {
                //  dd($value);
                return $value->creator() == \auth()->user();
            } else {
                return false;
            }

        });

        // All threads that user is participating in, with new messages
        // $threads = Thread::forUserWithNewMessages(Auth::id())->latest('updated_at')->get();

        return view('frontend.messaging.index')
            ->with('threads', $threads);
    }


    /**
     * Shows a message thread.
     *
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        try {
            $thread = ExtendedThread::findOrFail($id);
        } catch (ModelNotFoundException $e) {

            return redirect()->route('frontend.messages')->withErrors('Not found.');
        }
        $userId = auth()->user()->id;

        // is this user a participant? ie is this intended for this recipient?

        if ($thread->hasParticipant($userId)) {
            if ($thread->creator_name) {
                $thread->markAsRead($userId);
                // is this an invite?
                return view('frontend.messaging.show', compact('thread'));
            } elseif ($thread->creator() != \auth()->user()) {
                $thread->markAsRead($userId);
                return view('frontend.messaging.show', compact('thread'));
            }

            // 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();

        } else {
            return redirect()->route('frontend.messages')->withErrors('Not found.');
        }
    }

    /**
     * Creates a new message thread.
     *
     * @return mixed
     */
    public function create()
    {
//@TODO add a personal block function here
        $users = User::where('id', '!=', Auth::id())
            ->where('public', '1')->get();
        return view('frontend.messaging.create', compact('users'));
    }

    /**
     * Stores a new message thread.
     *
     * @return mixed
     */
    public function store(Request $request, $toid = -1)
    {
        // where's it from?
        $input = Request::all();
        dd(Request::path());
        $thread = ExtendedThread::create([
            'subject' => $input['subject'],
            'notification' => '1',
        ]);

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

        // Sender
        Participant::create([
            'thread_id' => $thread->id,
            'user_id' => Auth::id(),
            'last_read' => new Carbon,
        ]);

        // Recipients
        if (Request::has('recipients')) {
            $thread->addParticipant(Auth::id());
        }

        return redirect()->route('frontend.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) {
            Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');

            return redirect()->route('messages');
        }

        $thread->activateAllParticipants();

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

        // Add replier as a participant
        $participant = Participant::firstOrCreate([
            'thread_id' => $thread->id,
            'user_id' => Auth::id(),
        ]);
        $participant->last_read = new Carbon;
        $participant->save();

        // Recipients
        if (Request::has('recipients')) {
            $thread->addParticipant(Request::input('recipients'));
        }

        return redirect()->route('frontend.messages.show', $id);
    }

    public function deletethreadforuser(Request $request)
    {

        try {
            $thread = Thread::findOrFail(Request::input('id'));
        } catch (ModelNotFoundException $e) {
            return redirect()->route('frontend.messages')->withErrors('The thread with ID: ' . Request::input('id') . ' was not found.');
        }
        // if there's only one participant, remove the thread
        if ($thread->participants->count() == 1) {
            $thread->delete();
        } else {
            // else just remove this user from this thread
            $thread->removeParticipant(\auth()->user()->id);
        }

        return redirect()->route('frontend.messages')->withFlashSuccess('Notification deleted');
    }
}
