<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Lib\Util\RVLog;
use Mockery\Exception;
use Rvsitebuilder\Blog\Models\BlogCategory;
use Rvsitebuilder\Blog\Models\Post;
use Rvsitebuilder\Core\Models\CoreMenu;
use Rvsitebuilder\Core\Models\CorePage;
use Rvsitebuilder\Wysiwyg\Http\Requests\ChangeBadgeMenu;
use Rvsitebuilder\Wysiwyg\Http\Requests\ChangeIconMenu;
use Rvsitebuilder\Wysiwyg\Http\Requests\ChangeTarget;
use Rvsitebuilder\Wysiwyg\Http\Requests\ChangeUrlMenu;
use Rvsitebuilder\Wysiwyg\Http\Requests\DeleteMenu;
use Rvsitebuilder\Wysiwyg\Http\Requests\MenuSelectRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\NewMenu;
use Rvsitebuilder\Wysiwyg\Http\Requests\RenameMenu;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveMenu;

class MenuController extends Controller
{
    public function menuData(MenuSelectRequest $request)
    {
        $type = $request->input('type');
        $newDataArray = [];

        if (1 == $type) {
            // 1 is request page data
            $pageData = CorePage::select('id', 'page_name')->with([
                    'getSlug' => function ($query) {
                        $query->select('id', 'slugble_id', 'slug_name');
                    },
                    //             ] )->disableCache ()->get ();  TODO:: undefined method Illuminate\\Database\\Eloquent\\Builder::disableCache()
                    ])->get();
            $newDataArray = $pageData->map(function ($page) {
                return [
                        'optgroup' => null,
                        'optid' => null,
                        'data' => [
                                'id' => $page['getSlug']['id'],
                                'page_name' => htmlentities($page['page_name']),
                                'slug_name' => $page['getSlug']['slug_name'],
                        ],
                ];
            });
        } elseif (2 == $type) {
            // 2 is request post data
            $blogData = BlogCategory::with('getPostInCategory.getPost.getSlug')->whereHas('getPostInCategory.getPost.getSlug')->get();
            $newDataArray = $blogData->map(function ($blog) {
                return [
                        'optgroup' => htmlentities($blog['category_name']),
                        'optid' => $blog['id'],
                        'data' => $blog['getPostInCategory']->map(function ($post) use ($blog) {
                            return [
                                    'id' => $post['getPost']['getSlug']['id'],
                                    'page_name' => htmlentities($post['getPost']['post_name']),
                                    'slug_name' => htmlentities('blog/'.$blog['category_name'].'/'.$post['getPost']['getSlug']['slug_name']),
                            ];
                        }),
                ];
            });
        }

        return response()->json($newDataArray);
    }

    public function newMenu(NewMenu $request)
    {
        $newPriority = 1;
        $location = $request->input('location');
        $menutitle = $request->input('title');
        $priority = Coremenu::where('parent_id', '=', '0')->where('location', '=', $location)->orderBy('priority', 'DESC')->first();

        if (!empty($priority->priority)) {
            $newPriority = ((int) ($priority->priority) + 1);
        }

        $menu = new CoreMenu();
        $menu->slug_id = '0';
        $menu->menu_title = $menutitle;
        $menu->fontawesome = '';
        $menu->badge_title = '';
        $menu->badge_style = 'uk-badge-transparent';
        $menu->parent_id = '0';
        $menu->menu_type = '4';
        $menu->external_url = '#';
        $menu->priority = $newPriority;
        $menu->location = $location;
        $menu->target = '_self';
        $menu->created_at = date('Y-m-d H:i:s');
        $menu->save();

        return response()->json($menu->id);
    }

    public function renameMenu(RenameMenu $request)
    {
        $menu_id = $request->input('menu_id');
        $title = $request->input('title');

        $menu = CoreMenu::find($menu_id);
        $menu->menu_title = $title;
        $menu->save();

        return response()->json($menu_id);
    }

    public function changeIcon(ChangeIconMenu $request)
    {
        $menu_id = $request->input('menu_id');
        $icon = $request->input('icon');

        $menu = CoreMenu::find($menu_id);
        $menu->fontawesome = $icon;
        $menu->save();

        return response()->json($menu_id);
    }

    public function changeBadge(ChangeBadgeMenu $request)
    {
        $menu_id = $request->input('menu_id');
        $badge_title = $request->input('badge_title');
        $badge_style = $request->input('badge_style');

        $menu = CoreMenu::find($menu_id);
        $menu->badge_title = $badge_title;
        $menu->badge_style = $badge_style;
        $menu->save();

        return response()->json($menu_id);
    }

    public function changeTarget(ChangeTarget $request)
    {
        $menu_id = $request->input('menu_id');
        $target = $request->input('target');

        $menu = CoreMenu::find($menu_id);
        $menu->target = $target;
        $menu->save();

        return response()->json($menu_id);
    }

    public function changeUrl(ChangeUrlMenu $request)
    {
        $menu_id = $request->input('menu_id');
        $target = $request->input('target');
        $menu_type = $request->input('menu_type');
        $url = $request->input('url');
        $slug = $request->input('slug');

        $menu = CoreMenu::find($menu_id);
        $menu->menu_type = $menu_type;
        $menu->slug_id = $slug;
        $menu->external_url = $url;
        $menu->save();

        return response()->json($menu_id);
    }

    public function delMenu(DeleteMenu $request)
    {
        $aMenuId = $request->input('menu_id');

        if (\count($aMenuId)) {
            CoreMenu::whereIn('id', $aMenuId)->delete();

            return $aMenuId;
        }
    }

    public function saveMenu(SaveMenu $request)
    {
        $stringJson = $request->input('menu_json');
        $menuJson = json_decode($stringJson);

        try {
            foreach ($menuJson as $menuAll) {
                foreach ($menuAll->menu as $level1) {
                    $priority_lv1 = $level1->priority;

                    $menuLv1 = CoreMenu::find($level1->{'menu-id'});
                    if (!empty($menuLv1)) {
                        $menuLv1->priority = $priority_lv1;
                        $menuLv1->location = $menuAll->location;
                        $menuLv1->parent_id = 0;
                        $menuLv1->save();
                    }
                    if (isset($level1->submenu)) {
                        foreach ($level1->submenu as $level2) {
                            $priority_lv2 = $level2->priority;
                            $menuLv2 = CoreMenu::find($level2->{'menu-id'});
                            if (!empty($menuLv2)) {
                                $menuLv2->priority = $priority_lv2;
                                $menuLv2->location = $menuAll->location;
                                $menuLv2->parent_id = $level1->{'menu-id'};
                                $menuLv2->save();
                            }

                            if (isset($level2->submenu)) {
                                foreach ($level2->submenu as $level3) {
                                    $priority_lv3 = $level3->priority;
                                    if (!empty($menuLv3)) {
                                        $menuLv3 = CoreMenu::find($level3->{'menu-id'});
                                        $menuLv3->priority = $priority_lv3;
                                        $menuLv3->location = $menuAll->location;
                                        $menuLv3->parent_id = $level2->{'menu-id'};
                                        $menuLv3->save();
                                    }
                                }
                            }
                        }
                    }
                } // end update menu
            } // end loop location

            return response()->json(['status' => true]);
        } catch (Exception $e) {
            $errorMsg = 'false:'.$e->getMessage().' at line:'.$e->getLine();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));

            return response()->json(['status' => false]);
        }
    }
}
