<?php

namespace App\Http\Controllers\Frontend\Lab;

use App\Helpers\General\StringHelper;
use App\Http\Controllers\Controller;
use App\Models\Boards\BoardTemplateType;
use Illuminate\Support\Facades\Auth;
use App\Models\Auth\User;
use App\Models\Lab;
use App\Models\UserLab;
use App\Models\Forums\ForumThread;
use App\Models\Messages\ExtendedMessage;
use App\Models\Messages\ExtendedThread;
use App\Models\Tag;
use App\Models\Boards\BoardFolder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Validator;


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

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

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

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


    public function redirectPath()
    {
        return route(home_route());
    }

    public function index($id)
    {
        //dd($id);
        $user = User::with(['labs' => function ($query) use ($id) {
            $query->where(['lab_id' => $id]);
        }])->where('id', Auth::id())->first();


        if (!$user || count($user->labs) <= 0) {
            return redirect($this->redirectPath())->withFlashDanger('!You are not in the lab');
        }
        $lab_admin = UserLab::where(['lab_id' => $id, "admin" => 'true'])->first();
        $lab = Lab::with('members')->where(['id' => $id])->first();
        $tags = Tag::all();
        $board_template_types = BoardTemplateType::all();
        $labMembers = [];
        foreach ($lab->members as $member) {
            array_push($labMembers, $member->id);
        }
        $folders = BoardFolder::whereIn('user_id', $labMembers)->where("lab_id", $id)->whereNull('parent_id')->orderBy('order')->get();

        $announcement_threads = ForumThread::inLabForum($id)->whereHas('channel', function ($query) {
            $query->where('is_announcement_forum', 1);
        })->where('user_id', $lab_admin->user_id)->with('user')->latest('created_at');
        $announcements = $announcement_threads->limit(3)->get();
        $announcement_count = $announcement_threads->count();
        $notificationThread = ForumThread::inLabForum($id)->whereHas('channel', function ($query) {
            $query->whereNull('is_announcement_forum');
        })->whereIn('user_id', $labMembers)->with(['user', "tags"])->latest('created_at');
        $notifications = $notificationThread->limit(3)->get();
        $notification_count = $notificationThread->count();

        //Set default color lab accent color not added
        if ($lab->color == '') $lab->color = "#2aa8cc";
        $darkerColor = StringHelper::adjustBrightness($lab->color, -0.2);
        $lighterColor = StringHelper::adjustBrightness($lab->color, 0.2);
        return view('frontend.lab.index')
            ->with('lab', $lab)
            ->with('announcements', $announcements)
            ->with('notifications', $notifications)
            ->with('tags', $tags)
            ->with('board_template_types', $board_template_types)
            ->with('folders', $folders)
            ->with('darkerColor', $darkerColor)
            ->with('lighterColor', $lighterColor)
            ->with('notification_count', $notification_count);
    }


    public function update(Request $request, $id)
    {

        //validation part
        //dd($request->post());
        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect(@route('frontend.lab.index', ['id' => $id]) . "?edit=open")
                ->withErrors($validator)
                ->withInput();
        }
        $lab = Lab::find($id);
        $lab->name = $request['name'];
        $lab->description = $request['description'];
        $lab->color = $request['color'];
        $lab->header_fill_type = $request['header_fill_type'];
        $lab->header_color = $request['header_color'];
        $lab->background_fill_type = $request['background_fill_type'];
        $lab->background_color = $request['background_color'];
        $lab->footer_fill_type = $request['footer_fill_type'];
        $lab->footer_color = $request['footer_color'];
//@TODO validate image
        if ($request->has('icon_path')) {
            $image = $request->file('icon_path');
            $type = strtolower($image->getClientOriginalExtension());
            $filename = $lab->name . '_icon_path_' . time();
            //dd($filename);
            $img = Image::make($image);
            $img->orientate();
            $img->resize(($img->getHeight() > $img->getWidth()) ? 200 : null, ($img->getHeight() > $img->getWidth()) ? null : 200, function ($constraint) {
                $constraint->aspectRatio();
            });
            $img->crop(200, 200);
            // save with the UUID as a filename
            $img->save(Storage::disk('public')->path('lab/') . $filename . '.' . $type);
            $lab->icon_path = 'lab/' . $filename . '.' . $type;
        }
        if ($request->has('header_image_remove') && $request->header_image_remove == 1) {
            $lab->header_image = '';
        } elseif ($request->hasFile('header_image')) {
            $image = $request->file('header_image');
            $type = strtolower($image->getClientOriginalExtension());
            $filename = $lab->name . '_header_image_' . time();
            $img = Image::make($image);

            // save with the UUID as a filename
            $img->save(Storage::disk('public')->path('lab/') . $filename . '.' . $type);

            $lab->header_image = 'lab/' . $filename . '.' . $type;
        }
        if ($request->has('background_image_remove') && $request->background_image_remove == 1) {
            $lab->background_image = '';
        } elseif ($request->hasFile('background_image')) {
            $image = $request->file('background_image');
            $type = strtolower($image->getClientOriginalExtension());
            $filename = $lab->name . '_background_image_' . time();
            $img = Image::make($image);

            // save with the UUID as a filename
            $img->save(Storage::disk('public')->path('lab/') . $filename . '.' . $type);

            $lab->background_image = 'lab/' . $filename . '.' . $type;
        }
        if ($request->has('footer_image_remove') && $request->footer_image_remove == 1) {
            $lab->footer_image = '';
        } elseif ($request->hasFile('footer_image')) {
            $image = $request->file('footer_image');
            $type = strtolower($image->getClientOriginalExtension());
            $filename = $lab->name . '_footer_image_' . time();
            $img = Image::make($image);

            // save with the UUID as a filename
            $img->save(Storage::disk('public')->path('lab/') . $filename . '.' . $type);

            $lab->footer_image = 'lab/' . $filename . '.' . $type;
        }
        $lab->save();
        return redirect()->back()->withFlashSuccess("Lab details updated successfully");
    }

    public function subFolders($id)
    {
        $folders = BoardFolder::where("parent_id", $id)
            ->with('boards')
            ->get();
        $returnFolders = [];
        foreach ($folders as $folder) {
            $folder->subFolders = $this->subFolders($folder->id);
            array_push($returnFolders, $folder);
        }
        return $returnFolders;
    }

    public function searchforselect2(\Illuminate\Support\Facades\Request $request)
    {
        if (auth()->user()->hasRole('administrator')) {
            $input = $request::all();
            $search = $input['q']['term'];
            //  dd($search);
            $returnStr = [];
            $labs = Lab::where('name', 'LIKE', "%{$search}%")->get();
            foreach ($labs as $lab){
                $lab_admin = User::find(UserLab::where(['lab_id' => $lab->id, "admin" => 'true'])->first());
               // dd( User::find(UserLab::where(['lab_id' => $lab->id, "admin" => 'true'])->first()->user_id)->first());
//                try{
//                    $lab_admin = User::find(UserLab::where(['lab_id' => $lab->id, "admin" => 'true'])->first());
//                    dd($lab_admin);//->user_id)->first();
//                }catch (\Exception $e){
//                    dd($lab->id);
//                    dd(User::find(UserLab::where(['lab_id' => $lab->id, "admin" => 'true'])->first()));
//                }

                if( $lab_admin ){
                    //dd($lab_admin[0]);
                    $returnStr[]= ['id'=>$lab->id, 'text'=>"{$lab->name} (admin: ".($lab_admin?"{$lab_admin[0]->first_name} {$lab_admin[0]->last_name} {$lab_admin[0]->email}":"").")" ];
                }else{
                    $returnStr[]= ['id'=>$lab->id, 'text'=>"{$lab->name} (admin: none)" ];
                }

            }
            return \json_encode(['results'=>$returnStr]);
        }
        return null;
        //dd($offerings);
    }
}
