<?php

namespace App\Http\Controllers\Frontend\Board;

use App\Http\Controllers\Controller;
use App\Models\Auth\User;
use App\Models\Boards\Board;
use App\Models\Boards\BoardFolder;
use App\Models\Boards\BoardTemplateType;
use App\Models\Graphics\BackgroundImage;
use App\Models\Graphics\Shape;
use App\Models\Lab;
use App\Models\Tag;
use Barryvdh\DomPDF\PDF;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Image;
use Intervention\Image\Response;
use App\Models\UserLab;

class BoardController extends Controller
{

    const SIZES = ["a4" => ['width' => '492', 'height' => '595'],
        "slide" => ['width' => '800', 'height' => '600'],
        "abstract" => ['width' => '500', 'height' => '200']];


    public function index(Request $request)
    {
        return;
    }

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

        $board = Board::find($id);
        if ($board) {
            //ensure this user can see this board, fail if not
            if ($board->user->id == Auth::id() || auth()->user()->hasRole('administrator') || (isset($board->lab_id) && auth()->user()->labs->pluck('id')->contains($board->lab_id))) {
                $board->width = $board->width ? $board->width : 1000;
                $board->height = $board->height ? $board->height : 1000;
                //check that there's a file
                // first, is there data?
                if ($board->data) {
                    // make a file for the board, transfer data there
                    $data_filename = uniqid("board_{$board->id}", true);
                    Storage::disk('boards')->put($data_filename, $board->data);
                    $board->data_location = $data_filename;
                    $board->data = null;
                    $board->save();
                }

                $has_data = (Storage::disk('boards')->exists($board->data_location) && (Storage::disk('boards')->size($board->data_location) > 5));
                //dd($board);
                $tags = Tag::alphaordered();
                $board_template_types = BoardTemplateType::all();
                // $polygons = Shape::polygons()->get();
                //dd($polygons);
                $backgrounds = BackgroundImage::publicBackgrounds()->get();
                //  dd($backgrounds);
                //dd($board->tags);
                if ($board->lab_id) {
                    $folders = BoardFolder::where("lab_id", $board->lab_id)->whereNull('parent_id')->get();
                } else {
                    $folders = auth()->user()->board_folders()->whereNull('lab_id')->get();
                }
                //dd(array_column($board->tags->toArray(),"id"));
                // does this board live in a lab that's read only?
                $labreadonly = false;
                $lab = Lab::find($board->lab_id);
                if ($lab) {
                    $labreadonly = !is_null($lab->read_only);
                }
                if ($board->readonly || $labreadonly) {
                    return view('frontend.board.show_read_only')
                        ->with('board', $board)
                        ->with('has_data', $has_data);
                } else {
                    return view('frontend.board.show')
                        ->with('tags', $tags)
                        ->with('board_template_types', $board_template_types)
                        //->with('polygons', $polygons)
                        ->with('public_backgrounds', $backgrounds)
                        ->with('folders', $folders)
                        ->with('board_tags_id', array_column($board->tags->toArray(), "id"))
                        ->with('board_template_types_id', array_column($board->board_template_types->toArray(), "id"))
                        ->with('board', $board)
                        ->with('has_data', $has_data);
                }
            } else {
                return redirect()->route('frontend.index')->withFlashDanger('You don\'t have permission to access this board');
            }
        } else {
            return redirect()->route('frontend.index')->withFlashDanger('Board not found');
        }

    }

    public function public(Request $request, $id)
    {
        $board = Board::find($id);
        if ($board) {
            // is the board allowed to be public?
            if (!isNull($board->public)) {
                // if read only, show an SVG
                // if not, show the interactive view
            } else {
                abort(404);
            }
        }

    }

    public function store(Request $request)
    {

        // Am I allowed to make a board? @TODO tweak this to include board limits
        if ((auth()->user()->hasPermissionTo('create board'))) {
            // some presets
            $width = '800';
            $height = '600';
            if ($request['size'] == 'custom') {
                if ($request['units'] && $request['units'] == '1') {
                    // in mm- will need to
                    $width = floor($request['cust_width'] * 3.779528);
                    $height = floor($request['cust_height'] * 3.779528);
                } else {
                    $width = $request['cust_width'];
                    $height = $request['cust_height'];
                }

            } else {
                $width = explode('_', $request['size'])[0];
                $height = explode('_', $request['size'])[1];
            }
            // blank thumbnail
            $thumb = Image::canvas($width / 5, $height / 5, '#f0f0f0')->encode('data-url');
            // new board entry
            //@TODO make different sizes,  etc
            $board = Board::create(['user_id' => auth()->user()->id,
                'name' => $request['name'],
                'description' => $request['description'],
                'public' => $request['public'],
                'width' => $width,
                'height' => $height,
                'thumb' => $thumb,
                "lab_id" => $request['lab_id'],
            ]);

            // make a file for the board
            $data_filename = uniqid("board_{$board->id}", true);
            Storage::disk('boards')->put($data_filename, '');
            $board->data_location = $data_filename;
            $board->save();
            return redirect($board->path());
        } else {
            return array(
                'status' => '1'
            );
        }
    }

    /**
     * Update the board from the builder (with metadata)
     * @param Request $request
     * @param $id
     */
    public function update(Request $request, $id)
    {
        //dd($request->post());
        // some presets
        $board = Board::find($id);
        // is it my board? @TODO Or am I allowed to update it (lab member,public etc)
        if ($board->user->id == Auth::id() || auth()->user()->hasRole('administrator') || (isset($board->lab_id) && auth()->user()->labs->pluck('id')->contains($board->lab_id))) {
            $width = '800';
            $height = '600';
            if ($request['size'] == 'custom') {
                $width = $request['cust_width'];
                $height = $request['cust_height'];
            } else if ($request['width'] && $request['height']) {
                $width = $request['width'];
                $height = $request['height'];
            } else {
                $width = explode('_', $request['size'])[0];
                $height = explode('_', $request['size'])[1];
            }

            // handle swapping between landscape and portait
            if ($request['board_structure']) {
                // landscape
                if ($request['board_structure'] == "landscape") {
                    if ($width < $height) {
                        $t = $width;
                        $width = $height;
                        $height = $t;
                    }
                }
                // portrait
                if ($request['board_structure'] == "portrait") {
                    if ($width > $height) {
                        $t = $width;
                        $width = $height;
                        $height = $t;
                    }
                }
            }


            // $width = $request['cust_width'];
            // $height = $request['cust_height'];
            // new board entry
            $board = Board::updateOrCreate(['id' => $id], ['user_id' => auth()->user()->id,
                'name' => $request['name'],
                'description' => $request['description'],
                'public' => $request['public'],
                'width' => $width,
                'height' => $height,
                'board_folder_id' => $request['board_folder_id'],
                'is_template' => $request['is_template'] ? $request['is_template'] : null,
                'base_template' => $request['base_template'] ? $request['base_template'] : null,
                'bonus_template' => $request['bonus_template'] ? $request['bonus_template'] : null,
            ]);
            // tags
            $sync_status = true;
            if (isset($request['tags'])) {
                $tags = [];
                foreach ($request['tags'] as $item) {
                    if (!(Tag::where('id', $item)->exists())) {
                        $new = Tag::updateOrCreate(['text' => $item]);
                        $tags[] = $new->id;
                    } else {
                        $tags[] = $item;
                    }
                }
                $result = $board->tags()->sync($tags);
                $sync_status = ((count($result['attached']) != 0) || (count($result['detached']) != 0) || (count($result['updated']) != 0));
            }
            if (isset($request['board_template_types'])) {
                $template_types = [];
                foreach ($request['board_template_types'] as $item) {
                    if (!(BoardTemplateType::where('id', $item)->exists())) {
                        $new = BoardTemplateType::updateOrCreate(['text' => $item]);
                        $template_types[] = $new->id;
                    } else {
                        $template_types[] = $item;
                    }
                }
                $result = $board->board_template_types()->sync($template_types);
                $sync_status = ((count($result['attached']) != 0) || (count($result['detached']) != 0) || (count($result['updated']) != 0));
            }
            return array(
                'status' => ($board->wasChanged() || $sync_status) ? '0' : '1',
                'name' => $board->name,
                'width' => $board->width,
                'height' => $board->height
            );
        } else {
            return array(
                'status' => '1'
            );
        }
    }

    /**
     * Update the board  metadata from listing page
     * @param Request $request
     */
    public function updatemetadata(Request $request)
    {
        //dd($request);

        // some presets
        $board = Board::find($request['id']);
        // is it my board? @TODO Or am I allowed to update it (lab member,public etc)
        if ($board->user->id == Auth::id() || auth()->user()->hasRole('administrator') || (isset($board->lab_id) && auth()->user()->labs->pluck('id')->contains($board->lab_id))) {

            // new board entry
            $board = Board::updateOrCreate(['id' => $request['id']], [
                'name' => $request['name'],
                'description' => $request['description'],
                'public' => $request['public'],
                'folder_id'
            ]);
            // tags
            $sync_status = true;
            if (isset($request['tags'])) {
                $tags = [];
                foreach ($request['tags'] as $item) {
                    if (!(Tag::where('id', $item)->exists())) {
                        $new = Tag::updateOrCreate(['text' => $item]);
                        $tags[] = $new->id;
                    } else {
                        $tags[] = $item;
                    }
                }
                $result = $board->tags()->sync($tags);
                $sync_status = ((count($result['attached']) != 0) || (count($result['detached']) != 0) || (count($result['updated']) != 0));
            }

            return array(
                'status' => ($board->wasChanged() || $sync_status) ? '0' : '1'
            );
        } else {
            return array(
                'status' => '1'
            );
        }
    }

    /**
     * Sends a board to users and/or labs
     * @param Request $request
     * @return string[]
     */
    public function sendCanvas(Request $request, $id)
    {
        if (auth()->user()->hasRole('administrator')) {
            $board = Board::find($id);
            $sent_boards_count = 0;
            //dd($request['user_ids']);

            if (isset($request['user_ids'])) {
                foreach ($request['user_ids'] as $user_id) {
                    $duplicateBoard = $board->replicate();
                    $data_filename = uniqid("board_{$duplicateBoard->id}", true);
                    Storage::disk('boards')->copy($board->data_location, $data_filename);
                    $duplicateBoard->data_location = $data_filename;
                    $duplicateBoard->is_template = null;
                    $duplicateBoard->bonus_template = null;
                    $duplicateBoard->from_template = null;
                    // $duplicateBoard->exclude_from_limit = 'true';
                    $duplicateBoard->user_id = $user_id;
                    $duplicateBoard->save();
                    $sent_boards_count++;
                }
            }

            if (isset($request['lab_ids'])) {
                foreach ($request['lab_ids'] as $lab_id) {
                    $lab_admin = User::find(UserLab::where(['lab_id' => $lab_id, "admin" => 'true'])->first());
                    $duplicateBoard = $board->replicate();
                    $data_filename = uniqid("board_{$duplicateBoard->id}", true);
                    Storage::disk('boards')->copy($board->data_location, $data_filename);
                    $duplicateBoard->data_location = $data_filename;
                    $duplicateBoard->is_template = null;
                    $duplicateBoard->bonus_template = null;
                    $duplicateBoard->from_template = null;
                    $duplicateBoard->lab_id = $lab_id;
                    // $duplicateBoard->exclude_from_limit = 'true';
                    $duplicateBoard->user_id = $lab_admin[0]->id;
                    $duplicateBoard->save();
                    $sent_boards_count++;
                }
            }


            return array(
                'status' => ($sent_boards_count > 0) ? '0' : '1',
                'count' => $sent_boards_count
            );
        }
        return null;

    }


    /**
     * Toggle whether or not the board is a favourite
     * @param Request $request
     * @param $id
     */
    public function toggleFavourite(Request $request, $id)
    {
        $board = Board::find($id);
        //dd($request);
        // is it my board? @TODO Or am I allowed to update it (lab member,public etc)
        if ($board->user->id == Auth::id() || auth()->user()->hasRole('administrator') || (isset($board->lab_id) && auth()->user()->labs->pluck('id')->contains($board->lab_id))) {
            return array(
                'status' => $board->update(['favourite' => $request['favourite'] ? 1 : 0]) ? '0' : '1',
                'value' => $board->favourite
            );

        } else {
            return array(
                'status' => '1'
            );
        }
    }

    /**
     * Gets the boards for a particular folder
     * @param Request $request
     * @param $id
     */
    public function getBoardsForFolder(Request $request)
    {
        //  dd($request);
        $where = [];
        if ($request->post('favorite') && $request->post('favorite') == true) {
            $where['favourite'] = '1';
        }
        $orderBy = "name";
        $dir = "ASC";
        if ($request->post('column') && $request->post('dir')) {
            $orderBy = $request->post('column');
            $dir = $request->post('dir');
        }
        if ($request['id'] > 0) {
            if (count($request['tags']) > 0) {
                $boards = Board::forUser(Auth::id())
                    ->inUserFolderWithId($request['id'])
                    ->where($where)
                    ->where("name", "LIKE", '%' . $request->post('searchText') . '%')
                    ->withTags($request['tags'])
                    ->orderBy($orderBy, $dir)
                    ->get();
            } else {
                $boards = Board::forUser(Auth::id())
                    ->inUserFolderWithId($request['id'])
                    ->where($where)
                    ->where("name", "LIKE", '%' . $request->post('searchText') . '%')
                    ->orderBy($orderBy, $dir)
                    ->get();
            }
        } else {
            if (count($request['tags']) > 0) {
                $boards = Board::forUser(Auth::id())
                    ->whereNull('lab_id')
                    ->where($where)
                    ->where("name", "LIKE", '%' . $request->post('searchText') . '%')
                    ->withTags($request['tags'])
                    ->orderBy($orderBy, $dir)
                    ->get();
            } else {
                $boards = Board::forUser(Auth::id())
                    ->whereNull('lab_id')
                    ->where($where)
                    ->where("name", "LIKE", '%' . $request->post('searchText') . '%')
                    ->orderBy($orderBy, $dir)
                    ->get();
            }

        }
        // return $boards;
        return $boards->map(function ($board) {
            $board['author'] = $board->user->name;
            $board['formattedtags'] = $board->tags->pluck('text')->join(', ');
            $board['created_timestamp'] = strtotime($board->created_at);
            $board['created_str'] = $board->created_at->format('d/m/y');
            $board['updated_str'] = $board->updated_at->format('d/m/y');
            $board['read_only'] = is_null($board->readonly) ? 'false' : 'true';
            //$board['folder'] = $board->folder ? $board->folder->id : '';
            return $board;
        })->makeHidden(['data', 'is_template', 'state']);

    }

    /**
     * Add the board to a folder
     * @param Request $request
     * @param $id
     * @return string[]
     */
    public function addToFolder(Request $request, $id)
    {
        $board = Board::find($id);
        $board->folder_id = $request['folder_id']->save();

        return array(
            'status' => $board->wasChanged() ? '0' : '1',
        );

    }


    /**
     * Save the canvas data
     * @param Request $request
     * @param $id
     */
    public function saveCanvas(Request $request, $id)
    {
        $board = Board::find($id);
        // is it my board? @TODO Or am I allowed to update it (lab member,public etc)
        if ($board->user->id == Auth::id() || auth()->user()->hasRole('administrator') || (isset($board->lab_id) && auth()->user()->labs->pluck('id')->contains($board->lab_id))) {
            //if ($board->user->id == Auth::id()) {
            // validate JSON
            if ($this->isJSON($request['data'])) {
                // save the data as a file, making the file if it's not there
                if ($board->data_location) {
                    Storage::disk('boards')->put($board->data_location, $request['data']);
                } else {
                    $data_filename = uniqid("board_{$board->id}", true);
                    Storage::disk('boards')->put($data_filename, $request['data']);
                    $board->update(['data_location' => $data_filename]);
                }
                //$board->update(['data' => $request['data'], 'thumb' => $request['thumb'], 'state' => $request['state']]);
                $board->update(['thumb' => $request['thumb'], 'state' => $request['state']]);
                return array(
                    'status' => $board->wasChanged() ? '0' : '1'
                );
            } else {
                return array(
                    'status' => '1',
                    'message' => 'invalid save data'
                );
            }
        } else {
            return array(
                'status' => '1'
            );
        }
    }

    /**
     * Download an artboard as a PDF. Currently it essentially takes a picture and puts it on a PDF, future iterations will use Inkscape
     * @param Request $request
     * @return mixed
     */
    public function downloadaspdf(Request $request)
    {
        $size = getimagesize($request['img']);
        $pdf = App::make('dompdf.wrapper');
        $width = $size[0];
        $height = $size[1];
        $customPaper = array(0, 0, $width / 3.125, $height / 3.125);
        $html = "<body style='height:100%; width:100%; border:1px solid black; background: url({$request['img']});  background-repeat:no-repeat;'></body>";
        $pdf->setOptions(['dpi' => 300, 'enable_remote' => true])->setPaper($customPaper)->loadHTML($html);
        return $pdf->stream();

    }

    /**
     * Retrieve a thumbnail for an artboard
     * @param $id
     * @return mixed
     */
    public function thumb($id)
    {
        $board = Board::find($id);
        // is it my board? @TODO Or am I allowed to look at it (lab member,public etc)
        $image = \Intervention\Image\Facades\Image::make($board->thumb);
        // create response and add encoded image data
        return ($image)->response();
    }

    /**
     * Get the board's data
     * @param $id
     * @return mixed
     */
    public function data($id)
    {
        // is it my board? @TODO Or am I allowed to look at it (lab admin etc)
        $board = Board::find($id);
        // $content_typestr = 'image/png';
        //  dd($board->thumb);
        return Storage::disk('boards')->get($board->data_location);

    }

    /**
     * Get the board's metadata only
     * @param $id
     * @return mixed
     */
    public function metadata($id)
    {
        // is it my board? @TODO Or am I allowed to look at it (lab admin etc)
        $board = Board::find($id)->makeHidden(['data', 'is_template', 'state', 'thumb']);
        $tags = $board->tags->pluck('id')->join(',');
        //dd($tags);
        $board['tags_str'] = $tags;
        return $board;

    }

    /**
     * Search by tags and text. @TODO search by ID, too?
     * Return paginated
     * @param Request $request
     * @return mixed
     */
    public function searchTemplatesByTagsAndText(Request $request)
    {
//dd($request);
        $perpage = 10;
        $returnVal = [];
        $fields = ['id', 'name', 'description', 'created_at', 'updated_at'];
        if ($request['tags'] || $request['types']) {
            //  dd($request['types']);
            if (isset($request['search']) && strlen($request['search']) > 1) {
                $returnVal['items'] = Board::whereNotNull('is_template')->withTypeOrTag(['tags' => $request['tags'], 'types' => $request['types']])->where('name', 'like', "%{$request['search']}%")->skip(($request['page'] - 1) * $perpage)->offset(($request['page'] - 1) * $perpage)->limit($perpage)->get($fields);
            } else {
                $returnVal['items'] = Board::whereNotNull('is_template')->withTypeOrTag(['tags' => $request['tags'], 'types' => $request['types']])->skip(($request['page'] - 1) * $perpage)->offset(($request['page'] - 1) * $perpage)->limit($perpage)->get($fields);
            }
            $returnVal['count'] = Board::whereNotNull('is_template')->withTypeOrTag(['tags' => $request['tags'], 'types' => $request['types']])->count();
        } else {
            if (isset($request['search']) && strlen($request['search']) > 1) {
                $returnVal['items'] = Board::whereNotNull('is_template')->where('name', 'like', "%{$request['search']}%")->skip(($request['page'] - 1) * $perpage)->offset(($request['page'] - 1) * $perpage)->limit($perpage)->get($fields);
            } else {
                $returnVal['items'] = Board::whereNotNull('is_template')->skip(($request['page'] - 1) * $perpage)->offset(($request['page'] - 1) * $perpage)->limit($perpage)->get($fields);
                $returnVal['count'] = Board::whereNotNull('is_template')->count();
            }

        }


        $returnVal['items']->map(function ($board) {
            // $board['author'] = $board->user->name;
            $board['formattedtags'] = $board->tags->pluck('text')->join(', ');
            $board['formattedtypes'] = $board->board_template_types->pluck('text')->join(', ');
//            $board['created_timestamp'] = strtotime($board->created_at);
//            $board['created_str'] = $board->created_at->format('d/m/y');
//            $board['updated_str'] = $board->updated_at->format('d/m/y');
            return $board;
        });
        return $returnVal;//->pluck(['id', 'name', 'description'] );
    }

    /**
     * Delete the selected resource
     * @param $id
     * @return int[]
     */
    public function destroy($id)
    {
// Can the user in fact destroy this resource?
        $board = Board::find($id);
// is it my board? @TODO Or am I allowed to delete it (lab admin etc)
        if ($board->user->id == Auth::id() || auth()->user()->hasRole('administrator') || (isset($board->lab_id) && auth()->user()->labs->pluck('id')->contains($board->lab_id))) {
            $status = Board::destroy($id);
            $response = array(
                'status' => ($status > 0) ? 0 : 1,
                //'status' => 0,
            );

        } else {
            $response = array(
                'status' => 1
                //'status' => 0,
            );
        }
        return $response;
    }


    public function getBoardsForLab(Request $request)
    {
        $labMembers = UserLab::where(['lab_id' => $request["lab_id"]])->get();
        $members = [];
        $where['lab_id'] = $request["lab_id"];
        foreach ($labMembers as $member) {
            array_push($members, $member->user_id);
        }

        if ($request->post('myboard') && $request->post('myboard') == true) {
            $where['user_id'] = Auth::id();
        }
        if ($request->post('favorite') && $request->post('favorite') == true) {
            $where['favourite'] = '1';
        }
        $orderBy = "name";
        $dir = "ASC";
        if ($request->post('column') && $request->post('dir')) {
            $orderBy = $request->post('column');
            $dir = $request->post('dir');
        }

        if ($request['id'] > 0) {
            if (count($request['tags']) > 0) {
                $boards = Board::whereIn('user_id', $members)
                    ->where($where)
                    ->where("name", "LIKE", '%' . $request->post('searchText') . '%')
                    ->inUserFolderWithId($request['id'])
                    ->whereHas("tags", function ($query) use ($request) {
                        $query->whereIn('tags.id', $request['tags']);
                    })
                    ->orderBy($orderBy, $dir)
                    ->get();
            } else {
                $boards = Board::whereIn('user_id', $members)
                    ->where($where)
                    ->where("name", "LIKE", '%' . $request->post('searchText') . '%')
                    ->inUserFolderWithId($request['id'])
                    ->orderBy($orderBy, $dir)
                    ->get();
            }

        } else {

            if (count($request['tags']) > 0) {
                $boards = Board::whereIn('user_id', $members)
                    ->where($where)
                    ->where("name", "LIKE", '%' . $request->post('searchText') . '%')
                    ->whereHas("tags", function ($query) use ($request) {
                        $query->whereIn('tags.id', $request['tags']);
                    })
                    ->orderBy($orderBy, $dir)
                    ->get();
            } else {
                $boards = Board::whereIn('user_id', $members)
                    ->where($where)
                    ->where("name", "LIKE", '%' . $request->post('searchText') . '%')
                    ->orderBy($orderBy, $dir)
                    ->get();
            }

        }
        return $boards->map(function ($board) {
            $board['author'] = $board->user->name;
            $board['formattedtags'] = $board->tags->pluck('text')->join(', ');
            $board['created_timestamp'] = strtotime($board->created_at);
            $board['created_str'] = $board->created_at->format('d/m/y');
            $board['updated_str'] = $board->updated_at->format('d/m/y');
            return $board;
        })->makeHidden(['data', 'is_template', 'state']);

    }

    public function tempFileUpload(Request $Request)
    {
        $img = $Request['img'];
        $img = str_replace('data:image/png;base64,', '', $img);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $file = 'tempFiles/' . uniqid() . '.png';
        $success = file_put_contents($file, $data);
        return $success ? asset($file) : 'Unable to save the file.';
    }

    /**
     * Duplicate a board from an existing board
     * @param Request $request
     * @param $id
     * @return array
     */
    public function saveDuplicate(Request $request, $id)
    {
        $board = Board::find($id);
        $duplicateBoard = $board->replicate();
        $data_filename = uniqid("board_{$duplicateBoard->id}", true);
        Storage::disk('boards')->copy($board->data_location, $data_filename);
        $duplicateBoard->data_location = $data_filename;
        $duplicateBoard->name = $board->name . ' Copy';
        $duplicateBoard->from_template = null;
        $duplicateBoard->exclude_from_limit = null;
        $duplicateBoard->save();
        return ['status' => 200, "id" => $duplicateBoard->id];
    }

    public function newFromTemplate(Request $request)
    {
        $template_id = $request['template_id'];
        $board = Board::find($template_id);
        $duplicateBoard = $board->replicate();
        $data_filename = uniqid("board_{$duplicateBoard->id}", true);
        Storage::disk('boards')->copy($board->data_location, $data_filename);
        $duplicateBoard->data_location = $data_filename;
        $duplicateBoard->name = 'Untitled board';
        $duplicateBoard->is_template = null;
        $duplicateBoard->user_id = Auth::id();
        if ($request['lab_id']) {
            $duplicateBoard->lab_id = $request['lab_id'];
        } else {
            $duplicateBoard->lab_id = null;
        }
        $duplicateBoard->save();
        return array(
            'status' => '0',
            "id" => $duplicateBoard->id
        );
    }

    private function isJSON($string)
    {
        return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
    }
}
