<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Lib\Site\SlugLib;
use Lib\Util\RVLog;
use Mockery\Exception;
use Rvsitebuilder\Core\Models\CoreMenu;
use Rvsitebuilder\Core\Models\CorePage;
use Rvsitebuilder\Core\Models\CoreSeo;
use Rvsitebuilder\Core\Models\CoreSetting;
use Rvsitebuilder\Core\Models\CoreSlug;
use Rvsitebuilder\Wysiwyg\Http\Requests\AddPageRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\CheckSlugExist;
use Rvsitebuilder\Wysiwyg\Http\Requests\CheckSlugExistRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveCssJsRequest;
use Rvsitebuilder\Wysiwyg\Http\Requests\SaveMetaTagRequest;

class PageController extends Controller
{
    public function pageData()
    {
        $page = CorePage::with([
            'getSlug' => function ($query) {
                $query->select('slugble_id', 'slug_name', 'id')->pluck('id');
            },
            ])->get();
        $page_arr = [];
        $homepage = config('core.db.home_page');
        foreach ($page as $key => $value) {
            $menu = CoreMenu::whereIn('slug_id', CoreSlug::where('slugble_id', '=', $value->getSlug->slugble_id)->where('slugble_type', '=', 'Rvsitebuilder\Core\ModelsCorePage')->pluck('id')->toArray())->pluck('id');

            if ($value->getSlug->slug_name == $homepage) {
                $is_homepage = 1;
            } else {
                $is_homepage = 0;
            }

            array_push($page_arr, (object) [
                    'page_name' => $value->page_name,
                    'is_published' => $value->is_published,
                    'id' => $value->id,
                    'slug' => (object) [
                        'slug_name' => $value->getSlug->slug_name,
                    ],
                    'menu' => $menu,
                    'is_homepage' => $is_homepage,
                ]);
        }

        return json_encode($page_arr);
    }

    public function addPage(AddPageRequest $request)
    {
        //all route
        //         $routeCollection = Route::getRoutes();

        //         foreach ($routeCollection as $value) {
        //             echo $value->getPath();
        //         }

        try {
            $showMenu = $request->input('showMenu');

            // 日 ?<b>sd"l"m';'asdsd</b>#?YhoâîôüïçObกา$ภา*๒ /+%.#?|fsfsdf|s(sdsadsdadsds)wereef/\&&
            $pageName = SlugLib::genPagename($request->input('page_name'));
            $slug = SlugLib::genSlug($request->input('page_name'));

            $newSlug = SlugLib::checkSlugExist($slug);

            DB::beginTransaction();

            $new_page = new CorePage();

            // fix sidebar 0
            $new_page->sidebar_id = 0;

            $new_page->footer_id = config('core.db.footer');
            $new_page->header_id = 0;

            $new_page->content_view = self::contentPage()->content_view;
            $new_page->content_edit = self::contentPage()->content_edit;
            $new_page->is_published = config('core.db.public');
            $new_page->page_name = $pageName;
            $new_page->user_id = Auth::user()->id;
            $new_page->published_at = date('Y-m-d H:i:s');
            $new_page->created_at = date('Y-m-d H:i:s');
            $new_page->save();

            $insertSlug = new CoreSlug();
            $insertSlug->slugble_id = $new_page->id;
            $insertSlug->slugble_type = config('core.model.page');
            $insertSlug->slug_name = $newSlug;
            $insertSlug->created_at = date('Y-m-d H:i:s');
            $insertSlug->save();

            $insertSEO = new CoreSeo();
            $insertSEO->seoble_id = $new_page->id;
            $insertSEO->seoble_type = config('core.model.page');
            $insertSEO->meta_title_auto = $pageName;
            $insertSEO->focus_keywords_auto = '';
            $insertSEO->meta_des_auto = 'This is description '.$pageName.' in RVsitebuilder CMS';
            $insertSEO->use_type = 1;
            $insertSEO->created_at = date('Y-m-d H:i:s');
            $insertSEO->save();

            if ('1' == $showMenu) {
                $newPriority = 1;
                $priority = CoreMenu::where('location', '=', '1')->where('parent_id', '=', '0')->orderBy('priority', 'DESC')->first();
                if (!empty($priority->priority)) {
                    $newPriority = ((int) ($priority->priority) + 1);
                }
                $menu = new CoreMenu();
                $menu->slug_id = $insertSlug->id;
                $menu->menu_title = mb_substr($pageName, 0, 150); // limit menu 150 character
                $menu->fontawesome = '';
                $menu->badge_title = '';
                $menu->badge_style = 'uk-badge-transparent';
                $menu->parent_id = '0';
                $menu->menu_type = '1';
                $menu->external_url = '';
                $menu->priority = $newPriority;
                $menu->location = 1;
                $menu->target = '_self';
                $menu->save();
            }

            DB::commit();

            return $newSlug;
        } catch (\Exception $e) {
            DB::rollBack();
            $errorMsg = 'false:'.$e->getMessage().' at line:'.$e->getLine();
            RVLog::error(sprintf('Error Msg %s at %s :: LINE %s ::  %s', $errorMsg, __FILE__, __LINE__, __METHOD__));
        }
    }

    // ไม่ได้ใข้
    public function saveCssJs(SaveCssJsRequest $request)
    {
        try {
            DB::beginTransaction();

            $page_id = $request->input('page_id');

            // Page Custom
            $cssCustom = $request->input('cssCustom');
            $jsCustom = $request->input('jsCustom');

            // Global
            $jsGlobal = $request->input('jsGlobal');
            $cssGlobal = $request->input('cssGlobal');

            $pageUpdate = CorePage::find($page_id);
            $pageUpdate->embed_js = $jsCustom;
            $pageUpdate->embed_css = $cssCustom;
            $pageUpdate->save();

            CoreSetting::updateOrCreate([
                'key' => 'embed_js',
            ], [
                'value' => $jsGlobal,
            ]);

            CoreSetting::updateOrCreate([
                'key' => 'embed_css',
            ], [
                'value' => $cssGlobal,
            ]);

            DB::commit();

            return response()->json([
                'status' => 'success',
            ], 200);
        } catch (Exception $e) {
            DB::rollBack();

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

    // ไม่ได้ใช้
    public function saveMetaTag(SaveMetaTagRequest $request)
    {
        $page_id = $request->input('page_id');
        $meta = $request->input('meta');
        $globalMeta = $request->input('globalMeta');

        CoreSetting::updateOrCreate([
            'key' => 'embed_meta',
        ], [
            'value' => $globalMeta,
        ]);

        $pageUpdate = CorePage::find($page_id);
        $pageUpdate->embed_meta = $meta;
        $pageUpdate->save();

        return response()->json([
            'status' => 'success',
        ], 200);
    }

    public function getPageData($page_id)
    {
        $page = CorePage::with([
            'getSlug' => function ($query) {
                $query->select('slugble_id', 'slug_name', 'id')->pluck('id');
            },
            ])->where('id', '=', $page_id)->get();

        $page_arr = [];
        $homepage = config('core.db.home_page');
        foreach ($page as $key => $value) {
            $menu = CoreMenu::whereIn('slug_id', CoreSlug::where('slugble_id', '=', $value->getSlug->slugble_id)->where('slugble_type', '=', 'Rvsitebuilder\Core\ModelsCorePage')->pluck('id')->toArray())->pluck('id');

            // if is home page
            if ($value->getSlug->slug_name == $homepage) {
                $is_homepage = 1;
            } else {
                $is_homepage = 0;
            }

            // if sidebar style
            if (0 == $value->sidebar_left && 0 == $value->sidebar_right) {
                $sidebarStyle = 'none';
            } elseif (0 != $value->sidebar_left && 0 == $value->sidebar_right) {
                $sidebarStyle = 'left';
            } elseif (0 == $value->sidebar_left && 0 != $value->sidebar_right) {
                $sidebarStyle = 'right';
            } elseif (0 != $value->sidebar_left && 0 != $value->sidebar_right) {
                $sidebarStyle = 'full';
            }

            $embed_meta = config('core.db.embed_meta');
            $embed_js = config('core.db.embed_js');
            $embed_css = config('core.db.embed_css');

            array_push($page_arr, (object) [
                    'page_name' => $value->page_name,
                    'is_published' => $value->is_published,
                    'id' => $value->id,
                    'slug' => (object) [
                        'slug_name' => $value->getSlug->slug_name,
                    ],
                    'menu' => $menu,
                    'is_homepage' => $is_homepage,
                    'metatag' => $value->embed_meta,
                    'js' => $value->embed_js,
                    'css' => $value->embed_css,
                    'sidebarStyle' => $sidebarStyle,
                    'sidebarLeft' => $value->sidebar_left,
                    'sidebarRight' => $value->sidebar_right,
                    'global' => (object) [
                        'meta' => $embed_meta,
                        'js' => $embed_js,
                        'css' => $embed_css,
                    ],
                    'seo' => (object) [
                        'titleAuto' => $value->getSeo->meta_title_auto,
                        'titleCustom' => $value->getSeo->meta_title_custom,
                        'descriptionAuto' => $value->getSeo->meta_des_auto,
                        'descriptonCustom' => $value->getSeo->meta_desc_custom,
                        'useType' => $value->getSeo->use_type,
                        'image' => $value->getSeo->featured_image,
                    ],
                ]);
        }

        return json_encode($page_arr);
    }

    public function checkSlugExist(CheckSlugExistRequest $request)
    {
        $slug = $request->input('slug');

        $newSlug = SlugLib::checkSlugExist($slug);
        $newSlug = SlugLib::genSlug($newSlug);

        return $newSlug;
    }

    public function contentPage()
    {
        $content = (object) [
            'content_view' => '<div class="uk-container uk-container-center rv-block-full lazy">
<!-- Set Row Full width must use class  of Design block -->
<div class="rvsb_design_block bgContent">
<!-- Set Background of Design block -->
<div class="uk-container uk-container-center ">
<!-- Set Full width must use class  of Design block -->
<div class="uk-grid" data-uk-grid-margin="">
<div class="uk-width-small-1-3 uk-row-first">
<div contenteditable="false" style="background: #4a4a4a;">
<h3 class="rv-panel-box">
<font face="Open Sans" color="#FFFFFF">Your Title Here</font>
</h3>
</div>
<div contenteditable="false">
<p class="rv-panel-box">This is a text box. This is an
excellent place for you to add a paragraph.</p>
</div>
</div>
<div class="uk-width-small-1-3">
<div contenteditable="false" style="background: #4a4a4a;">
<h3 class="rv-panel-box">
<font face="Open Sans" color="#FFFFFF">Your Title Here</font>
</h3>
</div>
<div contenteditable="false">
<p class="rv-panel-box">This is a text box. This is an
excellent place for you to add a paragraph.</p>
</div>
</div>
<div class="uk-width-small-1-3">
<div contenteditable="false" style="background: #4a4a4a;">
<h3 class="rv-panel-box">
<font face="Open Sans" color="#FFFFFF">Your Title Here</font>
</h3>
</div>
<div contenteditable="false">
<p class="rv-panel-box">This is a text box. This is an
excellent place for you to add a paragraph.</p>
</div>
</div>
<div class="uk-row-first"></div>
</div>
</div>
</div>
</div>',
            'content_edit' => '<div id="editable_area_content" class="editable_area">
<div class="mg">
<div class="uk-container uk-container-center rv-block-full">
<!-- Set Row Full width must use class  of Design block -->
<div class="rvsb_design_block bgContent">
<!-- Set Background of Design block -->
<div class="uk-container uk-container-center ">
<!-- Set Full width must use class  of Design block -->
<div class="uk-grid" data-uk-grid-margin="">
<div class="uk-width-small-1-3 uk-row-first">
<div contenteditable="true" style="background: #4a4a4a;">
<h3 class="rv-panel-box">
<font face="Open Sans" color="#FFFFFF">Your Title Here</font>
</h3>
</div>
<div contenteditable="true">
<p class="rv-panel-box">This is a text box. This is an
excellent place for you to add a paragraph.</p>
</div>
</div>
<div class="uk-width-small-1-3">
<div contenteditable="true" style="background: #4a4a4a;">
<h3 class="rv-panel-box">
<font face="Open Sans" color="#FFFFFF">Your Title Here</font>
</h3>
</div>
<div contenteditable="true">
<p class="rv-panel-box">This is a text box. This is an
excellent place for you to add a paragraph.</p>
</div>
</div>
<div class="uk-width-small-1-3">
<div contenteditable="true" style="background: #4a4a4a;">
<h3 class="rv-panel-box">
<font face="Open Sans" color="#FFFFFF">Your Title Here</font>
</h3>
</div>
<div contenteditable="true">
<p class="rv-panel-box">This is a text box. This is an
excellent place for you to add a paragraph.</p>
</div>
</div>
<div class="uk-row-first"></div>
</div>
</div>
</div>
</div>
</div>
</div>',
        ];

        return $content;
    }
}
