<?php

namespace Rvsitebuilder\Wysiwyg\Http\Controllers\Backend;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Lib\Util\RVLog;
use Lib\Site\SlugLib;
use Rvsitebuilder\Blog\Models\BlogCategory;
use Rvsitebuilder\Blog\Models\BlogPost;
use Rvsitebuilder\Blog\Models\BlogPostCategory;
use Rvsitebuilder\Core\Models\CoreOldSlug;
use Rvsitebuilder\Core\Models\CorePage;
use Rvsitebuilder\Core\Models\CoreSetting;
use Rvsitebuilder\Core\Models\CoreSlug;
use Rvsitebuilder\Core\Models\CoreSystemPage;
use Rvsitebuilder\Core\Models\CoreVisibility;
use Rvsitebuilder\Wysiwyg\Http\Requests\PageProperty;
use Rvsitebuilder\Wysiwyg\Http\Requests\PagePropertyRequest;
// use Arcanedev\Support\Collection;
use Rvsitebuilder\Wysiwyg\Http\Requests\PostPropertyRequest;

class SitePropertyController extends Controller
{
    /**
     * Get data page information for page property.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function getActivePageinfo(Request $request)
    {
        $page = CorePage::with([
            'getSlug' => function ($query) {
                $query->select('slugble_id', 'slug_name', 'id')->pluck('id');
            },
            ])->where('id', '=', $request->data_id)->first();

        $role_id = '';
        if (0 != $page->visibility_id) {
            $vis = CoreVisibility::find($page->visibility_id);
            $visibility = $vis['visibility'];

            if (2 == $visibility) {
                //find id visibility
                $roleArr = json_decode($vis->role, true);
                $role_id = $roleArr['role_id'];
            }
        }

        $data = (object) [
                'id' => $page->id,
                'name' => htmlentities($page->page_name),
                'is_published' => $page->is_published,
                'ishomepage' => $page->getSlug->isHomepage(),
                'slug_id' => $page->getSlug->id,
                'slug_name' => $page->getSlug->slug_name,
                'metatag' => $page->embed_meta,
                'js' => $page->embed_js,
                'css' => $page->embed_css,
                'seo' => (object) [
                    'titleAuto' => optional($page->getSeo)->meta_title_auto,
                    'titleCustom' => optional($page->getSeo)->meta_title_custom,
                    'descriptionAuto' => optional($page->getSeo)->meta_des_auto,
                    'descriptionCustom' => optional($page->getSeo)->meta_des_custom,
                    'useType' => optional($page->getSeo)->use_type,
                    'image' => optional($page->getSeo)->featured_image,
                ],
                'visibility_id' => $page->visibility_id,
                'visibility' => (!empty($visibility) ? $visibility : 0),
                'ChildRestricted' => $role_id,
            ];

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

    /**
     * Get data page information for post property.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function getActivePostinfo(Request $request)
    {
        if (false !== strpos($request->data_id, 'category')) {
            $data_id = str_replace('category', '', $request->data_id);
            $post = BlogCategory::with('getSlug')->where('id', '=', $data_id)->first();
        } elseif (false !== strpos($request->data_id, 'blogindex')) {
            $data_id = str_replace('blogindex', '', $request->data_id);
            $post = CoreSystemPage::with('getSlug')->where('id', '=', $data_id)->first();
        } else {
            $post = BlogPost::with('getSlug')->where('id', '=', $request->data_id)->first();
        }

        $role_id = '';
        if (0 != $post->visibility_id) {
            $vis = CoreVisibility::find($post->visibility_id);
            $visibility = $vis['visibility'];

            if (2 == $visibility) {
                //find id visibility
                $roleArr = json_decode($vis->role, true);
                $role_id = $roleArr['role_id'];
            }
        }

        $data = (object) [
            'id' => $post->id,
            'name' => $post->post_name ? htmlentities($post->post_name) : htmlentities($post->category_name),
            'is_published' => $post->is_published,
            'slug_id' => $post->getSlug->id,
            'slug_name' => $post->getSlug->slug_name,
            'slug_prefix' => $post->getSlug->slug_prefix,
            'metatag' => $post->embed_meta,
            'js' => $post->embed_js,
            'css' => $post->embed_css,
            'seo' => (object) [
                'titleAuto' => optional($post->getSeo)->meta_title_auto,
                'titleCustom' => optional($post->getSeo)->meta_title_custom,
                'descriptionAuto' => optional($post->getSeo)->meta_des_auto,
                'descriptionCustom' => optional($post->getSeo)->meta_des_custom,
                'useType' => optional($post->getSeo)->use_type,
                'image' => optional($post->getSeo)->featured_image,
            ],
            'visibility_id' => $post->visibility_id,
            'visibility' => (!empty($visibility) ? $visibility : 0),
            'ChildRestricted' => $role_id,
        ];

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

    /**
     * Get data page information for page property.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function getActiveSysteminfo(Request $request)
    {
        $page = CoreSystemPage::with([
            'getSlug' => function ($query) {
                $query->select('slugble_id', 'slug_name', 'id')->pluck('id');
            },
            ])->where('id', '=', $request->data_id)->first();

        $role_id = '';
        if (0 != $page->visibility_id) {
            $vis = CoreVisibility::find($page->visibility_id);
            $visibility = $vis['visibility'];

            if (2 == $visibility) {
                //find id visibility
                $roleArr = json_decode($vis->role, true);
                $role_id = $roleArr['role_id'];
            }
        }

        $data = (object) [
                'id' => $page->id,
                'name' => htmlentities($page->page_name),
                'is_published' => $page->is_published,
                'ishomepage' => $page->getSlug->isHomepage(),
                'slug_id' => $page->getSlug->id,
                'slug_name' => $page->getSlug->slug_name,
                'metatag' => $page->embed_meta,
                'js' => $page->embed_js,
                'css' => $page->embed_css,
                'seo' => (object) [
                    'titleAuto' => optional($page->getSeo)->meta_title_auto,
                    'titleCustom' => optional($page->getSeo)->meta_title_custom,
                    'descriptionAuto' => optional($page->getSeo)->meta_des_auto,
                    'descriptionCustom' => optional($page->getSeo)->meta_des_custom,
                    'useType' => optional($page->getSeo)->use_type,
                    'image' => optional($page->getSeo)->featured_image,
                ],
                'visibility_id' => $page->visibility_id,
                'visibility' => (!empty($visibility) ? $visibility : 0),
                'ChildRestricted' => $role_id,
            ];

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

    /**
     * Save data Page Property.
     *
     * @param PagePropertyRequest $request
     *
     * @return Response
     */
    public function pageProperty(PagePropertyRequest $request)
    {
        try {
            DB::beginTransaction();

            $status = true;
            $slug_id = $request->slug_id;
            $slug = CoreSlug::findOrFail($slug_id);
            $request->slug_name = SlugLib::genSlug($request->slug_name);

            // ไม่ custom
            if (0 == $slug->slugble->visibility_id) {
                $status = false;
            }

            if (!empty($request->role)) {
                $roleArr = explode(',', $request->role);
                foreach ($roleArr as $k => $v) {
                    $arr[] = "$v";
                }
                $role = ['role_id' => $arr];
                $jsrole = json_encode($role);
            } else {
                $jsrole = '';
            }

            // สำหรับ visibility ที่ lock ไว้ จะไม่สามารถ setting visibility ได้
            if (1 != $slug->slugble->getVisibility->locked) {
                // All member (1) and Restricted member (2)
                if (0 != $request->visibility) { // locked ตั้งค่าที่ไหน ????
                    if (false == $status) {  // ยังไม่มีใน DB
                        $instVisty = new CoreVisibility();
                        $instVisty->visibility = $request->visibility;
                        $instVisty->role = $jsrole;
                        $instVisty->locked = 0;
                        $instVisty->created_at = date('Y-m-d H:i:s');
                        $instVisty->save();

                        // update core_page / core_post , visibility_id
                        $slug->slugble->where('id', '=', $slug->slugble->id)->update(['visibility_id' => $instVisty->id]);
                    } else {
                        // update
                        $upVisty = CoreVisibility::find($slug->slugble->visibility_id);
                        $upVisty->visibility = $request->visibility;
                        $upVisty->role = $jsrole;
                        $upVisty->updated_at = date('Y-m-d H:i:s');
                        $upVisty->save();
                    }
                } else {
                    if (0 != $slug->slugble->visibility_id) {
                        // delete core_visibility
                        $delVisty = CoreVisibility::find($slug->slugble->visibility_id);
                        $delVisty->delete();
                        // update core_page / core_post , visibility_id
                        $slug->slugble->update(['visibility_id' => $request->visibility]);
                    }
                }
            }

            if ($slug->slug_name != $request->slug_name) {
                $oldSlug = new CoreOldSlug();
                $oldSlug->slug_id = $slug->id;
                $oldSlug->slug_name = $slug->slug_name;
                $oldSlug->save();
            }

            $slug->slugble->getBookmark()->update([
                'slug_name' => trim($request->slug_name),
            ]); //Change to PageOption function rename

            $slug->slugble->update([
                'embed_js' => $request->editorJsCustom,
                'embed_meta' => $request->editorMetaCustom,
                'embed_css' => $request->editorCssCustom,
            ]);

            if (1 == $request->seoType) {
                $slug->slugble->getSeo()->update([
                    //'meta_title_auto' => $request->metaTitle, //??
                    //'meta_des_auto' => $request->metaDes, //??
                    //'focus_keywords_auto' => '$request->focusKeyword', //send empty value??
                    'use_type' => 1,
                ]);
            } elseif (0 == $request->seoType) {
                $slug->slugble->getSeo()->update([
                    'meta_title_custom' => trim($request->metaTitle),
                    'meta_des_custom' => trim($request->metaDes),
                    //'focus_keywords_custom' => $request->focusKeyword,
                    'use_type' => 0,
                ]);
            }

            $homepage = config('core.db.home_page');
            if ($slug->slug_name == $homepage) {
                CoreSetting::updateOrCreate([
                    'key' => 'home_page',
                ], [
                    'value' => trim($request->slug_name),
                ]);
            }

            $redirect_url = url($slug->slug_prefix.'/'.$request->slug_name);
            DB::commit();

            return response()->json([
                'status' => true,
                'data' => [
                    'url' => $redirect_url,
                    'slug_name' => $request->slug_name,
                    'slug_id' => $slug_id,
                ],
            ], 200);
        } 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__));

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

    public function postProperty(PostPropertyRequest $request)
    {
        try {
            $this->postBaseUrl($request->postBaseUrl);
            $this->categoryBaseUrl($request->categoryBaseUrl);

            $slug = CoreSlug::where('id', '=', $request->slug_id)->first();
            $url = '';
            if (false == empty($slug)) {
                $url = $slug->slug_prefix.'/'.$slug->slug_name;
            }

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

            return response()->json([
                'status' => false,
                'data' => [
                    'msg' => $errorMsg,
                ],
            ], 500);
        }
    }

    /**
     * Save data Site Global Setting.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function siteProperty(Request $request)
    {
        try {
            DB::beginTransaction();

            CoreSetting::updateOrCreate([
                'key' => 'embed_css',
            ], [
                'value' => $request->editorCssGlobal,
            ]);
            CoreSetting::updateOrCreate([
                'key' => 'embed_js',
            ], [
                'value' => $request->editorJsGlobal,
            ]);
            CoreSetting::updateOrCreate([
                'key' => 'embed_meta',
            ], [
                'value' => $request->editorMetaGlobal,
            ]);

            $seo_append = ('other' == $request->editorSeoappendGlobal) ? $request->appendother : $request->editorSeoappendGlobal;
            $seo_prepend = ('other' == $request->editorSeoprependGlobal) ? $request->prependother : $request->editorSeoprependGlobal;

            CoreSetting::updateOrCreate([
                'key' => 'embed_seo_append',
            ], [
                'value' => $seo_append,
            ]);

            CoreSetting::updateOrCreate([
                'key' => 'embed_seo_prepend',
            ], [
                'value' => $seo_prepend,
            ]);
            DB::commit();
            if ('- %SITE_NAME%' == $seo_append) {
                $seo_append = str_replace('%', '/%', $seo_append);
            }
            if ('%SITE_NAME% -' == $seo_prepend) {
                $seo_prepend = str_replace('%', '/%', $seo_prepend);
            }

            return response()->json([
                'status' => true,
                'seo_append' => $seo_append,
                'seo_prepend' => $seo_prepend,
            ], 200);
        } 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__));

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

    protected function postBaseUrl($postBaseUrl)
    {
        if (config('core.db.post_base_url') != $postBaseUrl) {
            if ('%BLOG_NAME%/category/%CATEGORY_NAME%' != $postBaseUrl) {
                CoreSetting::updateOrCreate(['key' => 'post_base_url'], ['value' => $postBaseUrl]);
            } else {
                CoreSetting::where('key', '=', 'post_base_url')->delete();
            }

            //replace  %BLOG_NAME%
            $postBaseUrl = mb_ereg_replace('%BLOG_NAME%', config('core.db.blog_index'), $postBaseUrl);

            // insert core_old_slug
            $postType = CoreSlug::where('slugble_type', '=', config('core.model.post'))->get();
            foreach ($postType as $k => $postval) {
                CoreOldSlug::create([
                    'slug_id' => $postval->id,
                    'slug_name' => $postval->slug_name,
                    'slug_prefix' => $postval->slug_prefix,
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
            }

            $BlogPostCategory = BlogPostCategory::get();
            foreach ($BlogPostCategory as $key => $BPC) {
                $cat = CoreSlug::where('slugble_type', '=', config('core.model.category'))->where('slugble_id', '=', $BPC->category_id)->first();

                $slugPrefix = mb_ereg_replace('%CATEGORY_NAME%', $cat->slug_name, $postBaseUrl);

                // update core_slug update slug_prefix post
                CoreSlug::where('slugble_id', '=', $BPC->post_id)
                ->where('slugble_type', '=', config('core.model.post'))
                ->update(['slug_prefix' => mb_strtolower($slugPrefix)]);
            }
        }
    }

    protected function categoryBaseUrl($categoryBaseUrl)
    {
        if (config('core.model.category') != $categoryBaseUrl) {
            if ('%BLOG_NAME%/category' != $categoryBaseUrl) {
                CoreSetting::updateOrCreate(['key' => 'category_base_url'], ['value' => $categoryBaseUrl]);
            } else {
                CoreSetting::where('key', '=', 'category_base_url')->delete();
            }
            $CatTypes = CoreSlug::where('slugble_type', '=', config('core.model.category'))->get();

            // Replace %BLOG_NAME%
            $categoryBaseUrl = mb_ereg_replace('%BLOG_NAME%', config('core.db.blog_index'), $categoryBaseUrl);

            // insert core_old_slug
            foreach ($CatTypes as $k => $catval) {
                CoreOldSlug::create([
                    'slug_id' => $catval->id,
                    'slug_prefix' => $catval->slug_prefix,
                    'slug_name' => $catval->slug_name,
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
                // Replace %CATEGORY_NAME%
                $catBase_prefix = mb_ereg_replace('%CATEGORY_NAME%', $catval->slug_name, $categoryBaseUrl);

                // update core_slug
                CoreSlug::where('id', '=', $catval->id)
                ->where('slugble_type', '=', config('core.model.category'))
                ->update(['slug_prefix' => mb_strtolower($catBase_prefix)]);
            }
        }
    }
}
