<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Frontend\Messages\MessagesController;
use App\Models\Auth\Invite;
use App\Models\Boards\Board;
use App\Models\Boards\BoardTemplateType;
use App\Models\Forums\ForumThread;
use App\Models\Lab;
use App\Models\Messages\ExtendedMessage;
use App\Models\Messages\ExtendedThread;
use App\Models\Tag;
use App\Models\UserLab;
use Carbon\Carbon;
use Cmgmyr\Messenger\Models\Message;
use Cmgmyr\Messenger\Models\Participant;
use Cmgmyr\Messenger\Models\Thread;
use Illuminate\Support\Facades\Auth;

/**
 * Class HomeController.
 */
class HomeController extends Controller
{

    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware(function ($request, $next) {

            $this->user = Auth::user();

            return $next($request);
        });
    }

    /**
     * @return \Illuminate\View\View
     */
    public function index()
    {
        //dd(Board::forUser(Auth::id())->whereNotNull('from_template')->pluck('from_template'));
       // dd( $templateboards = Board::bonusTemplates()->get());
        //dd(auth()->user()->boards->whereNull('lab_id')->sortByDesc('created_at')->count());
       // dd(auth()->user()->my_lab->pivot);
        //dd(auth()->user()->my_old_labs->get());
        if (Auth::check()) {
            $tags = Tag::all();
            $board_template_types = BoardTemplateType::all();
            // has the user undergone the onboarding process? if not, sign 'em up :)
//            if (auth()->user()->first_login == 'true') {
//                return redirect(route('frontend.user.firstlogin'));
//            }
            // is the user invited to a lab?

            if ($invite = Invite::where('email', auth()->user()->email)->first()) {

                // send them a notification
                // if so, make the connection
                // 20200519 but only if they're not already added
                if (!$invite->notified) {
                    // 20200529 does the inviter actually have a lab? They may have downgraded or lost it some other way
                    if ($invite->user->myLab) {
                        if (!$invite->user->myLab->members->contains(auth()->user())) {
                            $actions = array(['text' => 'Accept', 'buttonclass' => 'btn-outline-success', 'route' => route('frontend.auth.acceptinvite', $invite->id)],
                                ['text' => 'Reject', 'buttonclass' => 'btn-outline-danger', 'route' => route('frontend.auth.rejectinvite', $invite->id)]);
                            $message = "You have been invited to the lab {$invite->user->myLab->name}";
                            $notification = new ExtendedThread();
                            $notification->makeNotification('Lab invitation', $message, $actions, [auth()->user()->id], $invite->user->id);
                            // save the notification
                            $invite->notified = '1';
                            $invite->notification_id = $notification->id;
                            $invite->save();
                        }
                    } else {
                        // sender does not have the privileges to send this now... is invalid, therefore we kill it off.
                        $invite->delete();
                    }
                }

            }
            // then delete the invite

            //\Session::flash('flash_success', 'You have been added to the lab ' . $invite->user->myLab->name);


            if (!auth()->user()->confirmed) {
                \Session::flash('flash_warning', __('exceptions.frontend.auth.confirmation.resend', ['url' => route('frontend.auth.account.confirm.resend', e(auth()->user()->{auth()->user()->getUuidName()}))]) . '<br/>Studies say you are much prettier if you do.');

            }

            // get notifications
            $notifications = ExtendedThread::notifications()->forUserWithNewMessages(Auth::id())->take(5)->get();
            $notification_count = ExtendedThread::notifications()->forUserWithNewMessages(Auth::id())->count();

            // lab notifications

            $lab_notifications = collect();
            $lab_notifications_count = 0;
            foreach (auth()->user()->labs as $lab) {
                $lab_admin = UserLab::where(['lab_id' => $lab->id, "admin" => 'true'])->first();
//                $lab_notifications=ForumThread::inLabForum($lab->id)->whereHas('channel',function($query){
//                    $query->where('is_announcement_forum',1);
//                })->where('user_id',$lab_admin->user_id)->with('user')->latest('created_at');

                $thislab_notifications = ForumThread::inLabForum($lab->id)->whereIn('user_id', [auth()->user()->id])->with(['user', "tags"])->latest('created_at')->take(5)->get();
                $lab_notifications_count+=ForumThread::inLabForum($lab->id)->whereIn('user_id', [auth()->user()->id])->count();
                // dd($thislab_notifications);
                $lab_notifications = $lab_notifications->concat($thislab_notifications);
//                $notifications=$notificationThread->limit(3)->get();
//                $notification_count = $notificationThread->count();
            }

            //dd($lab_notifications);
            return view('frontend.user.home')
                ->with('lab_notifications', $lab_notifications)
                ->with('lab_notifications_count', $lab_notifications_count)
                ->with('notifications', $notifications)
                ->with('notification_count', $notification_count)
                ->with('tags', $tags)
                ->with('board_template_types', $board_template_types);

        } else {
            return view('frontend.index');

        }
    }

    /**
     * @return \Illuminate\View\View
     */
    public function home()
    {
        $tags = Tag::all();

        return view('frontend.user.home')
            ->with('tags', $tags);
    }

    /**
     * @return \Illuminate\View\View
     */
    public function plans_pricing()
    {
        return view('frontend.plans_pricing');
    }

    /**
     * @return \Illuminate\View\View
     */
    public function about_us()
    {
        //dd(1234);
        return view('frontend.about');
    }

    public function contact()
    {
        return view('frontend.contact');
    }

    public function privacy()
    {
        return view('frontend.privacy');
    }

    public function tos()
    {
        return view('frontend.tos');
    }
}
